import { Platform, NativeEventEmitter, NativeModules } from 'react-native'; import parseErrorStackLib from 'react-native/Libraries/Core/Devtools/parseErrorStack'; export { AppticsApiTracker } from './api_tracker/AppticsApiTracker'; export type { StartApiTrackingParams, EndApiTrackingParams } from './api_tracker/AppticsApiTracker'; import NativeAppticsReactModuleSpec, { type Spec as AppticsReactModuleSpec, } from './NativeAppticsReactModule'; import NativeAppticsAppUpdateModuleSpec, { type Spec as AppticsAppUpdateModuleSpec, } from './NativeAppticsAppUpdateModule'; import NativeAPRemoteConfigModuleSpec, { type Spec as APRemoteConfigModuleSpec, } from './NativeAPRemoteConfigModule'; import NativeAPRemoteLoggerModuleSpec, { type Spec as APRemoteLoggerModuleSpec, } from './NativeAPRemoteLoggerModule'; import NativeAppticsFeedbackModuleSpec, { type Spec as AppticsFeedbackModuleSpec, } from './NativeAppticsFeedbackModule'; import NativeAppticsPushModuleSpec, { type Spec as AppticsPushModuleSpec, } from './NativeAppticsPushModule'; import NativeAppticsRatingsModuleSpec, { type Spec as AppticsRatingsModuleSpec, } from './NativeAppticsRatingsModule'; const LINKING_ERROR = `The package '@zoho_apptics/apptics-react-native' doesn't seem to be linked. Make sure: \n\n` + Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo managed workflow\n'; // eslint-disable-next-line @typescript-eslint/no-explicit-any const makeProxy = (): any => new Proxy( {}, { get() { throw new Error(LINKING_ERROR); }, } ); const AppticsReactModule = (NativeAppticsReactModuleSpec ?? NativeModules.AppticsReactModule ?? makeProxy()) as AppticsReactModuleSpec; const AppticsAppUpdateModule = (NativeAppticsAppUpdateModuleSpec ?? NativeModules.AppticsAppUpdateModule ?? makeProxy()) as AppticsAppUpdateModuleSpec; const AppticsRemoteControlModule = (NativeAPRemoteConfigModuleSpec ?? NativeModules.APRemoteConfigModule ?? makeProxy()) as APRemoteConfigModuleSpec; const AppticsRemoteLoggerModule = (NativeAPRemoteLoggerModuleSpec ?? NativeModules.APRemoteLoggerModule ?? makeProxy()) as APRemoteLoggerModuleSpec; const AppticsFeedbackModule = (NativeAppticsFeedbackModuleSpec ?? NativeModules.AppticsFeedbackModule ?? makeProxy()) as AppticsFeedbackModuleSpec; const AppticsPushModule = (NativeAppticsPushModuleSpec ?? NativeModules.AppticsPushModule ?? makeProxy()) as AppticsPushModuleSpec; const AppticsRatingsModule = (NativeAppticsRatingsModuleSpec ?? NativeModules.AppticsRatingsModule ?? makeProxy()) as AppticsRatingsModuleSpec; export type AppticsProperties = { // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; }; export namespace AppticsInAppRatings { export function shouldShowPlayCoreAlertForAndroid() { if (Platform.OS === 'android') { AppticsRatingsModule.showAndroidPlayCoreAlert(); } } export function showAppStoreRatings() { AppticsRatingsModule.showAppRatings(); } // eslint-disable-next-line @typescript-eslint/no-explicit-any const eventEmitter = new NativeEventEmitter(AppticsRatingsModule as any); if (Platform.OS === 'ios') { eventEmitter.addListener('willDisplayReviewPrompt', () => { if (typeof AppticsRateUsModuleEmitter.willDisplayReviewPrompt === 'function') { AppticsRateUsModuleEmitter.willDisplayReviewPrompt(); } }); } } export const AppticsRateUsModuleEmitter = { willDisplayReviewPrompt: null as (() => void) | null, }; export const AppticsPushModuleEmitter = { onNotificationActionClick: null as | ((actionId: string, clickAction: string, payload: unknown) => void) | null, onNotificationClick: null as | ((clickAction: string, payload: unknown) => void) | null, onMessageReceived: null as ((payload: unknown) => void) | null, }; export namespace AppticsPushMessages { export function startService(): void { if (Platform.OS === 'ios') { AppticsPushModule.startService(); } } export function registerPushNotification(): void { if (Platform.OS === 'ios') { AppticsPushModule.registerPushNotification(); } else if (Platform.OS === 'android') { AppticsPushModule.notifyListenersActive(); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any const eventEmitter = new NativeEventEmitter(AppticsPushModule as any); if (Platform.OS === 'ios') { eventEmitter.addListener('onNotificationActionClick', (event) => { const { actionId, clickAction, payload } = event || {}; if (typeof AppticsPushModuleEmitter.onNotificationActionClick === 'function') { AppticsPushModuleEmitter.onNotificationActionClick(actionId, clickAction, payload); } }); eventEmitter.addListener('onNotificationClick', (event) => { const { clickAction, payload } = event || {}; if (typeof AppticsPushModuleEmitter.onNotificationClick === 'function') { AppticsPushModuleEmitter.onNotificationClick(clickAction, payload); } }); eventEmitter.addListener('onMessageReceived', (payload) => { if (typeof AppticsPushModuleEmitter.onMessageReceived === 'function') { AppticsPushModuleEmitter.onMessageReceived(payload); } }); } else if (Platform.OS === 'android') { eventEmitter.addListener('apptics_push_event', (clickEvent) => { if ('addInfo' in clickEvent) { if (typeof AppticsPushModuleEmitter.onMessageReceived === 'function') { AppticsPushModuleEmitter.onMessageReceived(clickEvent.payload); } return; } if ('actionId' in clickEvent) { if (typeof AppticsPushModuleEmitter.onNotificationActionClick === 'function') { AppticsPushModuleEmitter.onNotificationActionClick( clickEvent.actionId, clickEvent.clickAction, clickEvent.payload ); } } else if ('clickAction' in clickEvent) { if (typeof AppticsPushModuleEmitter.onNotificationClick === 'function') { AppticsPushModuleEmitter.onNotificationClick(clickEvent.clickAction, clickEvent.payload); } } }); } export function setForegroundNotificationOptions(option: APNotificationOption) { if (Platform.OS === 'ios') { AppticsPushModule.setPresentationPreference(option); } } } export enum APNotificationOption { none = 'none', banner = 'banner', sound = 'sound', all = 'all', } export enum TrackingState { UsageAndCrashTrackingWithPII = 1, UsageAndCrashTrackingWithoutPII = 4, OnlyUsageTrackingWithPII = 2, OnlyUsageTrackingWithoutPII = 5, OnlyCrashTrackingWithPII = 3, OnlyCrashTrackingWithoutPII = 6, NoTracking = -1, } export enum UpdateStats { Impression = 'impression', UpdateClick = 'download', IgnoreClick = 'ignore', RemindLaterClick = 'later', } export enum RCFetchStatus { NotYetFetched = 0, Success = 1, Failure = 2, UpToDate = 3, Throttled = 4, } export enum APLogLevel { off = 0, log = 1, debug = 2, info = 3, warning = 4, error = 5, all = 6, } export namespace AppticsDefinedEvents { export const AP_APP_LIFE_CYCLE: string = 'ap_app_life_cycle'; export const AP_APP_INSTALL: string = 'ap_app_install'; export const AP_APP_UNINSTALL: string = 'ap_app_uninstall'; export const AP_APP_UPDATE: string = 'ap_app_update'; export const AP_APP_CLEARDATA: string = 'ap_app_clear_data'; export const AP_APP_OPEN: string = 'ap_app_open'; export const AP_APP_FOREGROUND: string = 'ap_app_foreground'; export const AP_APP_BACKGROUND: string = 'ap_app_background'; export const AP_APP_TERMINATE: string = 'ap_app_terminate'; export const AP_APP_OUT_OF_MEMORY: string = 'ap_app_out_of_memory'; export const AP_APP_FIRST_OPEN: string = 'ap_app_first_open'; export const AP_APP_LAUNCHING: string = 'ap_app_launching'; export const AP_APP_RESIGN_ACTIVE: string = 'ap_app_resign_active'; export const AP_APP_WILL_CONNECT: string = 'ap_app_will_connect'; export const AP_APPLICATION: string = 'ap_application'; export const AP_DEEP_LINK_OPEN: string = 'ap_deep_link_open'; export const AP_DEEP_LINK_UPDATE: string = 'ap_deep_link_update'; export const AP_DEEP_LINK_FIRST_OPEN: string = 'ap_deep_link_first_open'; export const AP_IN_APP_PURCHASE: string = 'ap_in_app_purchase'; export const AP_NOTIFICATION_AUTHORIZATION_STATUS: string = 'ap_notification_authorization_status'; export const AP_NOTIFICATION_RECEIVE: string = 'ap_notification_receive'; export const AP_NOTIFICATION_OPEN: string = 'ap_notification_open'; export const AP_NOTIFICATION_DISMISS: string = 'ap_notification_dismiss'; export const AP_NOTIFICATION_FOREGROUND: string = 'ap_notification_foreground'; export const AP_SEARCH: string = 'ap_search'; export const AP_SHARE: string = 'ap_share'; export const AP_BATTERY_LOW: string = 'ap_battery_low'; export const AP_BATTERY_FULL: string = 'ap_battery_full'; export const AP_LOW_POWER_MODE_ON: string = 'ap_low_power_mode_on'; export const AP_LOW_POWER_MODE_OFF: string = 'ap_low_power_mode_off'; export const AP_DYNAMIC_LINK_OPEN: string = 'ap_dynamic_link_open'; export const AP_DYNAMIC_LINK_UPDATE: string = 'ap_dynamic_link_update'; export const AP_USER_LIFE_CYCLE: string = 'ap_user_life_cycle'; export const AP_USER_SIGNUP: string = 'ap_user_signup'; export const AP_USER_LOGIN: string = 'ap_user_login'; export const AP_USER_LOGOUT: string = 'ap_user_logout'; export const AP_OS: string = 'ap_os'; export const AP_OS_UNSUPPORTED: string = 'ap_os_unsupported'; export const AP_OS_UPDATE: string = 'ap_os_update'; export const AP_OTHERS: string = 'ap_others'; export const AP_NETWORK_REACHABILITY_CHANGE: string = 'ap_network_reachability_change'; export const AP_NETWORK_BANDWIDTH_CHANGE: string = 'ap_network_bandwidth_change'; export const AP_SWITCH_THEME_LIGHT: string = 'ap_switch_theme_light'; export const AP_SWITCH_THEME_DARK: string = 'ap_switch_theme_dark'; export const AP_SWITCH_THEME_CUSTOM: string = 'ap_switch_theme_custom'; export const AP_SWITCH_ORIENTATION_LANDSCAPE: string = 'ap_switch_orientation_landscape'; export const AP_SWITCH_ORIENTATION_PORTRAIT: string = 'ap_switch_orientation_portrait'; } interface AppticsDefinedUserProperties { first_name?: string; last_name?: string; company_name?: string; contact_number?: string; email_address?: string; country?: string; region?: string; city?: string; geo_location?: string; gender?: string; plan_type?: string; timezone?: string; language?: string; date_of_birth?: number; } export type AppticsCustomUserProperties = { [key: string]: string | number | boolean; }; export type AppticsUserProperty = AppticsDefinedUserProperties & AppticsCustomUserProperties; let _devTestingEnabled = false; export namespace Apptics { /** * Call this in debug builds to bypass __DEV__ guards on crash tracking * and remote logging so they can be tested without a release build. * Has no effect in release builds. */ export function enableDevTesting() { _devTestingEnabled = true; } export function init(enableAutomaticScreenTracking: boolean = true) { if (Platform.OS === 'android') { AppticsReactModule.initWithScreenTrackingStatus(enableAutomaticScreenTracking); } else if (Platform.OS === 'ios') { AppticsReactModule.init(enableAutomaticScreenTracking); } } export function disable() { if (Platform.OS === 'ios') { Apptics.setTrackingState(TrackingState.NoTracking); } } export function setCrashCustomProperty(properties: AppticsProperties) { AppticsReactModule.setCustomProperties(properties); } export function setTrackingState(state: TrackingState) { if (Platform.OS === 'android') { AppticsReactModule.setTrackingStatus(state); } else if (Platform.OS === 'ios') { // iOS uses separate boolean methods for each tracking dimension // eslint-disable-next-line @typescript-eslint/no-explicit-any const m = AppticsReactModule as any; switch (state) { case TrackingState.UsageAndCrashTrackingWithPII: m.setTrackingStatus(1); m.setCrashReportStatus(true); m.setPersonalInfoTrackingStatus(true); break; case TrackingState.UsageAndCrashTrackingWithoutPII: m.setTrackingStatus(1); m.setCrashReportStatus(true); m.setPersonalInfoTrackingStatus(false); break; case TrackingState.OnlyUsageTrackingWithPII: m.setTrackingStatus(1); m.setCrashReportStatus(false); m.setPersonalInfoTrackingStatus(true); break; case TrackingState.OnlyUsageTrackingWithoutPII: m.setTrackingStatus(1); m.setCrashReportStatus(false); m.setPersonalInfoTrackingStatus(false); break; case TrackingState.OnlyCrashTrackingWithPII: m.setTrackingStatus(0); m.setCrashReportStatus(true); m.setPersonalInfoTrackingStatus(true); break; case TrackingState.OnlyCrashTrackingWithoutPII: m.setTrackingStatus(0); m.setCrashReportStatus(true); m.setPersonalInfoTrackingStatus(false); break; default: m.setTrackingStatus(0); m.setCrashReportStatus(false); m.setPersonalInfoTrackingStatus(false); break; } } } export async function getTrackingState(): Promise { const statusValue = await AppticsReactModule.getTrackingStatus(); return getTrackingStateFromValue(statusValue); } export function setUser(userId: string, properties?: AppticsUserProperty) { AppticsReactModule.setCurrentUser(userId, properties ?? null); } export function setUserWithOrgId( userId: string, orgId: string, properties?: AppticsUserProperty ) { AppticsReactModule.setUserWithOrgId(userId, orgId, properties ?? null); } export function isUserLoggedIn(): Promise { return AppticsReactModule.isUserLoggedIn(); } export function openPrivacySettings() { AppticsReactModule.openSettings(); } export function addEvent( eventName: string, eventGroup: string, properties: AppticsProperties ) { AppticsReactModule.addEvent(eventName, eventGroup, properties); } export function screenAttached(screenName: string) { if (Platform.OS === 'android') { AppticsReactModule.trackScreenAttached(screenName); } else if (Platform.OS === 'ios') { AppticsReactModule.trackViewEnter(screenName); } } export function screenDetached(screenName: string) { if (Platform.OS === 'android') { AppticsReactModule.trackScreenDetached(screenName); } else if (Platform.OS === 'ios') { AppticsReactModule.trackViewExit(screenName); } } export function showLastSessionCrashedPopup() { if (Platform.OS === 'android') { AppticsReactModule.showLastSessionCrashedPopup(); } else if (Platform.OS === 'ios' && __DEV__) { console.warn('Apptics showLastSessionCrashedPopup method only works on Android.'); } } export function presentPrivacyReviewPopup() { AppticsReactModule.showPrivacyReviewPopup(); } export function initCrashTracker() { if (Platform.OS === 'ios') { AppticsReactModule.activateCrashListener(); } if (__DEV__ && !_devTestingEnabled) { return; } const defaultHandler = ErrorUtils.getGlobalHandler(); ErrorUtils.setGlobalHandler((error, isFatal) => { const jsStackTrace = parseErrorStackLib(error.stack); const issueName = `${error.name} - ${error.message}`; const firstLine = jsStackTrace[0]; const fileName = firstLine?.file.split('/').pop(); const uniqueId = `${fileName}@${firstLine?.methodName}@${firstLine?.lineNumber?.toString()}:${firstLine?.column}`; let stackTrace = ''; jsStackTrace?.forEach((value) => { stackTrace += `\n${value?.methodName}@${value?.lineNumber?.toString()}:${value?.column}`; }); if (isFatal) { if (Platform.OS === 'android') { AppticsReactModule.sendJSException(issueName, stackTrace, undefined, undefined); } else if (Platform.OS === 'ios') { AppticsReactModule.sendJSException(error.name, error.message, stackTrace, uniqueId); } } else { if (Platform.OS === 'android') { AppticsReactModule.sendNonFatalJsException(issueName, stackTrace, undefined, undefined); } else if (Platform.OS === 'ios') { AppticsReactModule.sendNonFatalJsException( error.name, error.message, stackTrace, uniqueId ); } } defaultHandler(error, isFatal); }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function reportError(error: any) { if (__DEV__ && !_devTestingEnabled) { return; } const issueName = `${error.name} - ${error.message}`; const jsStackTrace = parseErrorStackLib(error.stack); const firstLine = jsStackTrace[0]; const fileName = firstLine?.file.split('/').pop(); const uniqueId = `${fileName}@${firstLine?.methodName}@${firstLine?.lineNumber?.toString()}:${firstLine?.column}`; let stackTrace = ''; jsStackTrace?.forEach((value) => { stackTrace += `\n${value?.methodName}@${value?.lineNumber?.toString()}:${value?.column}`; }); if (Platform.OS === 'android') { AppticsReactModule.sendNonFatalJsException(issueName, stackTrace, undefined, undefined); } else if (Platform.OS === 'ios') { AppticsReactModule.sendNonFatalJsException(error.name, error.message, stackTrace, uniqueId); } } function getTrackingStateFromValue(value: number): TrackingState { switch (value) { case TrackingState.UsageAndCrashTrackingWithPII: return TrackingState.UsageAndCrashTrackingWithPII; case TrackingState.UsageAndCrashTrackingWithoutPII: return TrackingState.UsageAndCrashTrackingWithoutPII; case TrackingState.OnlyCrashTrackingWithPII: return TrackingState.OnlyCrashTrackingWithPII; case TrackingState.OnlyCrashTrackingWithoutPII: return TrackingState.OnlyCrashTrackingWithoutPII; case TrackingState.OnlyUsageTrackingWithPII: return TrackingState.OnlyUsageTrackingWithPII; case TrackingState.OnlyUsageTrackingWithoutPII: return TrackingState.OnlyUsageTrackingWithoutPII; default: return TrackingState.NoTracking; } } export function flush(): void { AppticsReactModule.flush(); } } export namespace AppticsAppUpdate { export function showVersionAlertPopup() { AppticsAppUpdateModule.showNewVersionAlert(); } export async function checkForUpdate(): Promise { return AppticsAppUpdateModule.checkForUpdate(); } export function sendUpdateStat(updateId: String, stat: UpdateStats) { AppticsAppUpdateModule.sendUpdatesEngagementStats(updateId as string, stat); } export function disableUpdatePopupIfNotInstalledFromPlayStore(status: boolean) { if (Platform.OS === 'android') { AppticsAppUpdateModule.disableUpdateIfNotInstalledFromPlayStore(status); } else if (Platform.OS === 'ios' && __DEV__) { console.warn('Apptics disableUpdateIfNotInstalledFromPlayStore method only works on Android.'); } } } export namespace AppticsRemoteConfig { export async function getStringValue( key: string, coldFetch: boolean, fallbackWithOfflineValue: boolean ): Promise { return AppticsRemoteControlModule.fetchValue(key, coldFetch, fallbackWithOfflineValue); } export function setCustomCondition(conditionKey: string, conditionValue: string) { AppticsRemoteControlModule.setCustomConditionValue(conditionKey, conditionValue); } } export namespace AppticsFeedback { export function writeLog(logType: LogType, logMessage: string) { AppticsFeedbackModule.addLog(logMessage, logType); } export function addLogFile(filePath: String) { AppticsFeedbackModule.addLogFile(filePath as string); } export function addDiagnosticsInfo(header: string, key: string, value: string) { AppticsFeedbackModule.addDiagnosticsInfo(header, key, value); } export function resetLogsAndDiagnostics() { AppticsFeedbackModule.resetLogsAndDiagnostics(); } export function openFeedback() { AppticsFeedbackModule.openFeedback(); } export function reportBug() { AppticsFeedbackModule.reportBug(); } export function enableShakeForFeedback() { AppticsFeedbackModule.enableShakeForFeedback(); } export function disableShakeForFeedback() { AppticsFeedbackModule.disableShakeForFeedback(); } export function enableAnonymousAlert() { AppticsFeedbackModule.enableAnonymousAlert(); } export function disableAnonymousAlert() { AppticsFeedbackModule.disableAnonymousAlert(); } export function sendFeedback( feedback: string, includeLogs: boolean, includeDiagnostics: boolean, guestMailId: string | null, forceToAnonymous: boolean, attachments: [string] | null ) { AppticsFeedbackModule.sendFeedback( feedback, includeLogs, includeDiagnostics, guestMailId, forceToAnonymous, attachments ); } } export namespace APLogger { function logInfo(type: string, ...msgs: unknown[]) { try { throw new Error(); } catch (e: unknown) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const jsStackTrace = parseErrorStackLib((e as Error).stack as any); const firstLine = jsStackTrace[2]; let formatted_string = ''; if (Array.isArray(msgs)) { const _msgs = msgs[0] as unknown[]; for (let i = 0; i < _msgs.length; ++i) { formatted_string += stringifyMsg(_msgs[i]) + ' '; } } else { formatted_string += stringifyMsg(msgs); } formatted_string = formatted_string.trim(); if (__DEV__ && !_devTestingEnabled) { const prefix = `${firstLine?.methodName}@${firstLine?.lineNumber.toString()}:${firstLine?.column?.toString()}`; if (type === 'debug') { console.debug(prefix, formatted_string); } else if (type === 'info') { console.info(prefix, formatted_string); } else if (type === 'warn') { console.warn(prefix, formatted_string); } else if (type === 'error') { console.error(prefix, formatted_string); } else { console.log(prefix, formatted_string); } return; } else { AppticsRemoteLoggerModule.logWithFileName( firstLine?.lineNumber?.toString() ?? '', firstLine?.column?.toString() ?? '', firstLine?.methodName ?? '', type, formatted_string ); } } } function stringifyMsg(msg: unknown): string { if (typeof msg === 'string') { return msg; } else if (typeof msg === 'function') { return `[function ${(msg as { name: string }).name}()] `; } else if (msg && typeof msg === 'object' && 'stack' in msg && 'message' in msg) { return (msg as Error).message + ' '; } else { try { return '' + JSON.stringify(msg) + ''; } catch { return 'Undefined Message'; } } } export function enable() { AppticsRemoteLoggerModule.enableLogger(); } export function disable() { AppticsRemoteLoggerModule.disableLogger(); } export function isEnabled(): Promise { return AppticsRemoteLoggerModule.isLoggerEnabled(); } export function log(...msgs: unknown[]) { logInfo('log', msgs); } export function debug(...msgs: unknown[]) { logInfo('debug', msgs); } export function info(...msgs: unknown[]) { logInfo('info', msgs); } export function warn(...msgs: unknown[]) { logInfo('warn', msgs); } export function error(...msgs: unknown[]) { logInfo('error', msgs); } } export enum LogType { Debug = 'debug', Info = 'info', Warn = 'warn', Error = 'error', }