UNPKG

@tef-novum/webview-bridge

Version:

JavaScript library to access to native functionality. Requires a webview with a postMessage bridge.

1 lines 19.5 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).webviewBridge={})}(this,function(e){"use strict";var t,n=1,r="".concat(Date.now(),"-").concat(String(Math.random()).slice(-8)),o="__tuenti_webview_bridge",i=function(){return!("undefined"==typeof window||!window.tuentiWebView||!window.tuentiWebView.postMessage)},a=function(){return!!("undefined"!=typeof window&&window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.tuentiWebView&&window.webkit.messageHandlers.tuentiWebView.postMessage)},u=function(){return"undefined"==typeof window?null:i()?function(e){window.tuentiWebView.postMessage(e)}:a()?function(e){window.webkit.messageHandlers.tuentiWebView.postMessage(e)}:null},c=[],s=function(e){c.push(e)},l=function(e){c=c.filter(function(t){return t!==e})},f=function(){var e;return"undefined"!=typeof window&&(!!function(){try{return window.self!==window.top}catch(e){return!0}}()&&!(null===(e=null===window||void 0===window?void 0:window.frameElement)||void 0===e?void 0:e.hasAttribute("data-enable-webview-bridge")))},d=void 0,p=function(){return!f()&&(i()||a())},y=function(e,t){var o=e.type,i=e.id,a=void 0===i?"web-".concat(n++,"-").concat(r):i,c=e.payload,f=u(),p=JSON.stringify({type:o,id:a,payload:c});return null===d||void 0===d||d("[WebView Bridge] SEND:",p),f?(setTimeout(function(){f(p)}),new Promise(function(e,n){var r=!1,i=function(t){t.id!==a||r||(t.type===o?e(t.payload):"ERROR"===t.type?n(t.payload):n({code:500,reason:"bad type: ".concat(t.type,". Expecting ").concat(o)}),l(i))};s(i),t&&setTimeout(function(){r=!0,l(i),n({code:408,reason:"request timeout"})},t)})):Promise.reject({code:500,reason:"WebView postMessage not available"})};if("undefined"!=typeof window){var m=null===(t=window[o])||void 0===t?void 0:t.postMessage;window[o]={postMessage:function(e){var t;null===m||void 0===m||m(e),null===d||void 0===d||d("[WebView Bridge] RCVD:",e);try{t=JSON.parse(e)}catch(t){throw Error("Problem parsing webview message: ".concat(e))}c.forEach(function(e){return e(t)})}}}var E=function(e,t){var n=function(n){n.type===e&&Promise.resolve(t(n.payload)).then(function(e){var t=u();t&&t(JSON.stringify({type:n.type,id:n.id,payload:e}))})};return s(n),function(){l(n)}},T=function(){return(T=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function v(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}function _(e,t,n,r){return new(n||(n=Promise))(function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function u(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,u)}c((r=r.apply(e,t||[])).next())})}function A(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=(o=a.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}}var g=function(e){return p()?y({type:"NAVIGATION_BAR",payload:e}):(void 0!==e.title&&"undefined"!=typeof document&&(document.title=e.title),Promise.resolve())},w=null,I=function(){if(w)return Promise.resolve(T({},w));var e=new Promise(function(e){setTimeout(function(){e({result:{}})},500)}),t=y({type:"GET_REMOTE_CONFIG"}).then(function(e){return T({},w=e)});return Promise.race([e,t])},S=function(e){return Math.floor(e/1e3)},O=0,N=function(e){var t=setTimeout(function(){e(),O++},500);return function(){clearTimeout(t),O=0,e()}},b=function(e){var t=e.onAndroid,n=e.onIos,r=e.onWeb;return"undefined"==typeof window?Promise.resolve():window.AnalyticsWebInterface?t(window.AnalyticsWebInterface):window.webkit&&window.webkit.messageHandlers&&window.webkit.messageHandlers.firebase?n(window.webkit.messageHandlers.firebase):window.gtag&&O<3?r(window.gtag):Promise.resolve()},P=function(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")},h=function(e){return P(e).toLocaleLowerCase().replace(/[^a-zß0-9\s\-\_\/\|\:]/g,"").replace(/\s+/g," ").trim().replace(/\s/g,"_").slice(0,100)},R=function(e){var t={};return Object.entries(e).forEach(function(e){var n=e[0],r=e[1],o=r,i=n.slice(0,40);"string"==typeof r&&(o=h(r)),t[i]=o}),t},C={sanitize:!0},M="",D=!1;e.AllowMeApiKeyError=1003,e.AllowMeBiometricsCameraError=1007,e.AllowMeBiometricsCameraPermissionError=1012,e.AllowMeBiometricsCancelledByUserError=1010,e.AllowMeBiometricsCapturingError=1008,e.AllowMeBiometricsInvalidImagesError=1011,e.AllowMeBiometricsResultError=1009,e.AllowMeBiometricsSetupError=1006,e.AllowMeBiometricsTimeoutError=1005,e.AllowMeCanNotOpenFrontCameraError=1013,e.AllowMeCanNotSaveImageError=1017,e.AllowMeFaceDetectionError=1015,e.AllowMeGenericError=500,e.AllowMeGooglePayServicesError=1014,e.AllowMeInstanceCreationError=1004,e.AllowMeProviderError=1016,e.AllowMeSetupSdkError=1001,e.AllowMeTimeoutProcessingError=1002,e.AllowMeUnauthorizedError=401,e.CD_EVENT_VALUE=8,e.CD_NOVUM_UID=7,e.CD_WEBAPP_INSTALLED=4,e.addOrEditContact=function(e){return y({type:"ADD_OR_EDIT_CONTACT",payload:{phoneNumber:e}})},e.attachToEmail=function(e){var t=e.url,n=e.subject,r=e.fileName,o=e.recipient,i=e.body;return y({type:"ATTACH_TO_EMAIL",payload:{url:t,subject:n,fileName:r,recipient:o,body:i}})},e.bottomSheet=function(e){if(D)return Promise.reject({code:423,reason:"BottomSheet is locked. You can only have one bottom sheet in the screen"});D=!0;var t=setTimeout(function(){D=!1},1e3);return y({type:"SHEET",payload:e}).then(function(e){return D=!1,clearTimeout(t),e}).catch(function(e){throw D=!1,clearTimeout(t),e})},e.checkPermissionStatus=function(e,t){return y({type:"OS_PERMISSION_STATUS",payload:{feature:e,params:t}}).then(function(e){return e.granted})},e.createCalendarEvent=function(e){var t=e.beginTime,n=e.endTime,r=e.title;return y({type:"CREATE_CALENDAR_EVENT",payload:{beginTime:S(t),endTime:S(n),title:r}})},e.dismiss=function(e){return y({type:"DISMISS",payload:{onCompletionUrl:e}})},e.displayQualtricsIntercept=function(e){var t=e.interceptId;return y({type:"DISPLAY_QUALTRICS_INTERCEPT",payload:{interceptId:t}})},e.downloadBase64=function(e){return y({type:"DOWNLOAD_BASE64",payload:{content:e.contentInBase64,fileName:e.fileName}})},e.fetch=function(e){var t=e.url,n=e.method,r=e.headers,o=e.body;return y({type:"FETCH",payload:{url:t,method:n,headers:r,body:o}}).catch(function(){return{status:500,headers:{},body:"Bridge call failed"}})},e.fetchContactsByPhone=function(e){return y({type:"FETCH_CONTACTS_DATA",payload:{phoneNumbers:e}})},e.fetchPhoneNumbers=function(){return y({type:"FETCH_PHONE_NUMBERS"})},e.focusNavbar=function(){return y({type:"FOCUS_NAVBAR"})},e.getAppMetadata=function(e){return y({type:"GET_APP_METADATA",payload:{appToken:e}})},e.getAttStatus=function(){return y({type:"GET_ATT_STATUS"}).catch(function(){return null})},e.getBatteryInfo=function(){return y({type:"GET_BATTERY_INFO"})},e.getBiometricsAuthenticationStatus=function(){return y({type:"GET_BIOMETRICS_AUTHENTICATION_STATUS"})},e.getDeviceModel=function(){return y({type:"MODEL"}).catch(function(){return null})},e.getDeviceTac=function(){return y({type:"TAC"}).catch(function(){return{tac:null}})},e.getDiskSpaceInfo=function(){return y({type:"GET_DISK_SPACE_INFO"})},e.getEsimInfo=function(){return y({type:"GET_ESIM_INFO"}).catch(function(){return{supportsEsim:!1,eid:null}})},e.getInstallationId=function(){return y({type:"GET_INSTALLATION_ID"})},e.getLocatorJwtToken=function(){return y({type:"GET_LOCATOR_JWT_TOKEN"})},e.getLocatorPendingPermissions=function(){return y({type:"GET_LOCATOR_PENDING_PERMISSIONS"})},e.getLocatorSdkConfig=function(){return y({type:"GET_LOCATOR_SDK_CONFIG"})},e.getLocatorSdkMode=function(){return y({type:"GET_LOCATOR_SDK_MODE"})},e.getLocatorSdkSession=function(){return y({type:"GET_LOCATOR_SDK_SESSION"})},e.getLocatorSdkState=function(){return y({type:"GET_LOCATOR_SDK_STATE"})},e.getLocatorSdkVersion=function(){return y({type:"GET_LOCATOR_SDK_VERSION"})},e.getNetworkConnectionInfo=function(){return y({type:"DATA_CONNECTION_INFO",payload:{}})},e.getPincodeInfo=function(){return y({type:"GET_PINCODE_INFO"})},e.getProfileImage=function(){return y({type:"GET_PROFILE_IMAGE"})},e.getRemoteConfig=I,e.getTopazToken=function(e){return void 0===e&&(e={}),y({type:"GET_TOPAZ_TOKEN",payload:{}},e.timeout)},e.getTopazValues=function(){return y({type:"GET_TOPAZ_VALUES",payload:{}})},e.getUnseenNotificationsBadge=function(){return _(void 0,void 0,void 0,function(){return A(this,function(e){return[2,y({type:"GET_UNSEEN_NOTIFICATIONS_BADGE"})]})})},e.hideLoadingOverlay=function(){return y({type:"HIDE_LOADING_OVERLAY"})},e.highlightNavigationTab=function(e){var t=e.tab,n=e.highlight,r=e.count;return y({type:"HIGHLIGHT_TAB",payload:{tab:t,highlight:n,count:r}})},e.internalNavigation=function(e){return y({type:"INTERNAL_NAVIGATION",payload:{feature:e}})},e.isABTestingAvailable=function(e){return I().then(function(){return function(e){return"true"===w.result[e]}(e)}).catch(function(){return!1})},e.isQualtricsInterceptAvailableForUser=function(e){var t=e.interceptId;return y({type:"IS_QUALTRICS_INTERCEPT_AVAILABLE_FOR_USER",payload:{interceptId:t}})},e.isWebViewBridgeAvailable=p,e.logEcommerceEvent=function(e,t){return t=T(T({},t),{screenName:t.screenName||M}),b({onAndroid:function(n){return n.logEvent&&n.logEvent(e,JSON.stringify(t)),Promise.resolve()},onIos:function(n){return n.postMessage({command:"logEvent",name:e,parameters:t}),Promise.resolve()},onWeb:function(){return Promise.resolve()}})},e.logEvent=function(e,t){var n,r,o,i,a,u,c=T(T({},C),t).sanitize,s=e.name,l=v(e,["name"]);if(s)Object.keys(l).length>25&&console.warn("Trying to log FirebaseEvent with name ".concat(s," exceeding the limit of ").concat(25," params")),c&&(l=R(l),s=h(s));else{if(!e.category||!e.action)return console.warn('LegacyAnalyticsEvent should have "category" and "action"',{category:e.category,action:e.action}),Promise.resolve();r=(n=e).category,o=n.action,i=n.label,a=n.value,u=v(n,["category","action","label","value"]),i||(i="null_label"),a||(a=0),l=T({eventCategory:r,eventAction:o,eventLabel:P(i),eventValue:a},u),s=e.category}return l=T(T({},l),{screenName:l.screenName||M}),b({onAndroid:function(e){return e.logEvent&&e.logEvent(s,JSON.stringify(l)),Promise.resolve()},onIos:function(e){return e.postMessage({command:"logEvent",name:s,parameters:l}),Promise.resolve()},onWeb:function(e){return new Promise(function(t){e("event",s,T(T({},l),{event_callback:N(t)}))})}})},e.logTiming=function(e){var t=e.category,n=void 0===t?"performance_timer":t,r=e.variable,o=e.value,i=e.label;if(!n||!r||!o)return console.warn('Analytics timing should have "category", "variable" and "value"',{category:n,variable:r,value:o}),Promise.resolve();var a={timingCategory:n,timingVar:r,timingValue:o=Math.round(o),timingLabel:i},u=n;return b({onAndroid:function(e){return e.logEvent&&e.logEvent(u,JSON.stringify(a)),Promise.resolve()},onIos:function(e){return e.postMessage({command:"logEvent",name:u,parameters:a}),Promise.resolve()},onWeb:function(){return new Promise(function(e){gtag("event",u,T(T({},a),{event_callback:N(e)}))})}})},e.logout=function(){return y({type:"LOG_OUT"})},e.nativeAlert=function(e){var t=e.message,n=e.title,r=e.buttonText;return p()?y({type:"ALERT",payload:{title:n,message:t,buttonText:r}}):("undefined"!=typeof window&&window.alert(t),Promise.resolve())},e.nativeConfirm=function(e){var t=e.message,n=e.title,r=e.acceptText,o=e.cancelText,i=e.destructive;return p()?y({type:"CONFIRM",payload:{message:t,title:n,acceptText:r,cancelText:o,destructive:i}}).then(function(e){return e.result}):Promise.resolve("undefined"!=typeof window&&window.confirm(t))},e.nativeMessage=function(e){var t=e.message,n=e.duration,r=e.buttonText,o=e.buttonAccessibilityLabel,i=e.type,a=e.withDismiss;return p()?y({type:"MESSAGE",payload:{message:t,duration:n,buttonText:r,buttonAccessibilityLabel:o,type:i,withDismiss:a}}).then(function(e){return e&&e.action?e:{action:"DISMISS"}}):("undefined"!=typeof window&&window.alert(t),Promise.resolve({action:"DISMISS"}))},e.notifyBridgeReady=function(){return y({type:"BRIDGE_READY"})},e.notifyPageLoaded=function(){return y({type:"PAGE_LOADED"})},e.onNavigationBarIconClicked=function(e){return E("NAVIGATION_BAR_ICON_CLICKED",e)},e.onSessionRenewed=function(e){return E("SESSION_RENEWED",function(t){return e(t.accessToken)})},e.openOcrScanner=function(e){return y({type:"OPEN_OCR_SCANNER",payload:{regex:e.regex,timeoutMs:e.timeoutMs}})},e.openOnboarding=function(){return y({type:"OPEN_ONBOARDING"})},e.readTextFromClipboard=function(){var e;return((null===(e=navigator.clipboard)||void 0===e?void 0:e.readText)?navigator.clipboard.readText():Promise.reject()).catch(function(){return y({type:"CLIPBOARD_READ_TEXT"})})},e.registerDatamobUser=function(e){var t=e.phoneNumber,n=e.tokenPassword;return y({type:"REGISTER_DATAMOB_USER",payload:{phoneNumber:t,tokenPassword:n}})},e.renewSession=function(e,t){return void 0===t&&(t={}),y({type:"RENEW_SESSION",payload:{accessToken:e||null}},t.timeout).then(function(e){return e.accessToken})},e.reportStatus=function(e){var t=e.feature,n=e.status,r=e.reason;return y({type:"STATUS_REPORT",payload:{feature:t,status:n,reason:r}})},e.requestAllowMeBiometrics=function(){return y({type:"REQUEST_ALLOWME_BIOMETRICS"})},e.requestContact=function(e){var t=(void 0===e?{}:e).filter;return y({type:"GET_CONTACT_DATA",payload:{filter:void 0===t?"phone":t}})},e.requestDatamobDeviceAdmin=function(){return y({type:"REQUEST_DATAMOB_DEVICE_ADMIN",payload:{}}).then(function(e){return{isAdmin:e.isAdmin}})},e.requestDeviceImei=function(){return y({type:"IMEI"},200).then(function(e){return e.imei}).catch(function(){return null})},e.requestPermissionBackgroundLocation=function(){return y({type:"REQUEST_PERMISSION_BACKGROUND_LOCATION"})},e.requestPermissionBatteryOptimization=function(){return y({type:"REQUEST_PERMISSION_BATTERY_OPTIMIZATION"})},e.requestPermissionCriticalAlerts=function(){return y({type:"REQUEST_PERMISSION_CRITICAL_ALERTS"})},e.requestPermissionLocation=function(){return y({type:"REQUEST_PERMISSION_LOCATION"})},e.requestPermissionMicrophone=function(){return y({type:"REQUEST_PERMISSION_MICROPHONE"})},e.requestPermissionNotifications=function(){return y({type:"REQUEST_PERMISSION_NOTIFICATIONS"})},e.requestSimIcc=function(){return y({type:"SIM_ICC"},200).then(function(e){return e.icc}).catch(function(){return null})},e.requestSimImsi=function(){return y({type:"IMSI"},200).then(function(e){return e.imsi}).catch(function(){return null})},e.requestVibration=function(e){return y({type:"VIBRATION",payload:{type:e}})},e.sanitizeAnalyticsParam=h,e.sanitizeAnalyticsParams=R,e.setActionBehavior=function(e){return y({type:"SET_ACTION_BEHAVIOR",payload:{actions:e}}).catch(function(){})},e.setBiometricsAuthenticationStatus=function(e){return y({type:"SET_BIOMETRICS_AUTHENTICATION_STATUS",payload:{enable:e.enable}})},e.setLocatorSdkMode=function(e){return y({type:"SET_LOCATOR_SDK_MODE",payload:{mode:e}})},e.setLogger=function(e){d=e},e.setQualtricsProperties=function(e){var t=e.stringProperties,n=void 0===t?{}:t,r=e.numberProperties,o=void 0===r?{}:r,i=e.dateTimePropertyKeys;return y({type:"SET_QUALTRICS_PROPERTIES",payload:{stringProperties:n,numberProperties:o,dateTimePropertyKeys:void 0===i?[]:i}})},e.setScreenName=function(e,t,n){if(void 0===t&&(t={}),!e)return console.warn("Missing analytics screenName"),Promise.resolve();var r=T(T({},C),n).sanitize,o=M;M=e;var i=r?R(t):t;return b({onAndroid:function(t){return t.setScreenNameWithParams?t.setScreenNameWithParams(e,JSON.stringify(i)):t.setScreenName&&t.setScreenName(e),Promise.resolve()},onIos:function(t){return t.postMessage({command:"setScreenName",name:e,parameters:i}),Promise.resolve()},onWeb:function(t){return new Promise(function(n){t("event","page_view",T(T({screenName:e,page_title:e,previousScreenName:o},i),{event_callback:N(n)}))})}})},e.setTrackingProperty=function(e,t,n){return y({type:"SET_TRACKING_PROPERTY",payload:{system:e,name:t,value:n}}).catch(function(){})},e.setUnseenNotificationsBadge=function(e){return _(void 0,void 0,void 0,function(){return A(this,function(t){return[2,y({type:"SET_UNSEEN_NOTIFICATIONS_BADGE",payload:e})]})})},e.setUserProperty=function(e,t){return e&&t?(t=String(t),b({onAndroid:function(n){return n.setUserProperty&&n.setUserProperty(e,t),Promise.resolve()},onIos:function(n){return n.postMessage({command:"setUserProperty",name:e,value:t}),Promise.resolve()},onWeb:function(n){var r;return n("set","user_properties",((r={})[e]=h(t),r)),Promise.resolve()}})):(console.warn("Trying to set analytics user property without name or value",e,t),Promise.resolve())},e.setWebViewTitle=function(e){return p()?g({title:e}):("undefined"!=typeof document&&(document.title=e),Promise.resolve())},e.setupLocatorSdkConfig=function(e){return y({type:"SETUP_LOCATOR_SDK_CONFIG",payload:{config:e}})},e.share=function(e){return y({type:"SHARE",payload:e})},e.shareBase64=function(e){return y({type:"SHARE_BASE64",payload:{content:e.contentInBase64,fileName:e.fileName}})},e.showAppRating=function(){return y({type:"SHOW_APP_RATING"})},e.showLineSelector=function(){return y({type:"SHOW_LINE_SELECTOR"})},e.showLoadingOverlay=function(e){return y({type:"SHOW_LOADING_OVERLAY",payload:e})},e.startProfileImageFlow=function(){return y({type:"START_PROFILE_IMAGE_FLOW"})},e.triggerPinOrBiometricAuthentication=function(e){return y({type:"TRIGGER_PIN_OR_BIOMETRIC_AUTHENTICATION",payload:{maxSecondsSinceLastValidation:e}})},e.unregisterDatamobDeviceAdmin=function(){return y({type:"UNREGISTER_DATAMOB_DEVICE_ADMIN"})},e.updateNavigationBar=g,e.updatePhoneNumbers=function(e){return y({type:"UPDATE_PHONE_NUMBERS",payload:{phoneNumbers:e}})},e.validateDatamobRequirements=function(e){var t=e.phoneNumber,n=e.tokenPassword;return y({type:"VALIDATE_DATAMOB_REQUIREMENTS",payload:{phoneNumber:t,tokenPassword:n}})},e.writeTextToClipboard=function(e){var t;return((null===(t=navigator.clipboard)||void 0===t?void 0:t.writeText)?navigator.clipboard.writeText(e):Promise.reject()).catch(function(){return y({type:"CLIPBOARD_WRITE_TEXT",payload:e})})},Object.defineProperty(e,"__esModule",{value:!0})});