posthog-react-native 4.79.0 → 4.79.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,7 +12,10 @@ export interface PostHogOptions extends PostHogCoreOptions {
12
12
  * @default 'file'
13
13
  */
14
14
  persistence?: 'memory' | 'file';
15
- /** Allows you to provide your own implementation of the common information about your App or a function to modify the default App properties generated */
15
+ /**
16
+ * Allows you to provide your own implementation of the common information about your App or a function to modify the default App properties generated.
17
+ * An object replaces the default App properties except `$react_native_version`, which is kept unless the object sets it (set it to `undefined` to remove it).
18
+ */
16
19
  customAppProperties?: PostHogCustomAppProperties | ((properties: PostHogCustomAppProperties) => PostHogCustomAppProperties);
17
20
  /**
18
21
  * Allows you to provide a custom asynchronous storage such as async-storage, expo-file-system or a synchronous storage such as mmkv.
@@ -1,2 +1,2 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.PostHog=void 0;Object.defineProperty(exports,"PostHogPersistedProperty",{enumerable:true,get:function get(){return _core.PostHogPersistedProperty;}});var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _reactNative=require("react-native");var _core=require("@posthog/core");var _storage=require("./storage");var _surveyProgress=require("./surveys/survey-progress");var _logsDefaults=require("./logs-defaults");var _version=require("./version");var _nativeDeps=require("./native-deps");var _utils=require("./utils");var _wixNavigation=require("./frameworks/wix-navigation");var _OptionalPlugin=require("./optional/OptionalPlugin");var _errorTracking=require("./error-tracking");var _exceptionContext=require("./error-tracking/exception-context");function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}function _callSuper(t,o,e){return o=(0,_getPrototypeOf2["default"])(o),(0,_possibleConstructorReturn2["default"])(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],(0,_getPrototypeOf2["default"])(t).constructor):o.apply(t,e));}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t;})();}function _superPropGet(t,o,e,r){var p=(0,_get2["default"])((0,_getPrototypeOf2["default"])(1&r?t.prototype:t),o,e);return 2&r&&"function"==typeof p?function(t){return p.apply(e,t);}:p;}function mapAppStateForLogs(state){if(state==='background'){return'background';}if(!state||state==='unknown'){return undefined;}return'foreground';}var NATIVE_CALL_TIMEOUT_MS=10000;var MANUAL_RECORDING_START_RETRY_DELAYS_MS=[1000,2000,4000,8000,16000];var PostHog=exports.PostHog=function(_PostHogCore){function PostHog(apiKey,options){var _this;(0,_classCallCheck2["default"])(this,PostHog);var _a;var _b,_c,_d,_e,_f;var normalizedApiKey=typeof apiKey==='string'?apiKey.trim():'';if(!normalizedApiKey){console.error("You must pass your PostHog project's api key. The client will be disabled.");}_this=_callSuper(this,PostHog,[normalizedApiKey,options]);_this._appProperties={};_this._sessionReplayNativeInitialized=false;_this._nativeErrorTrackingInitialized=false;_this._androidNdkCrashesUnsupportedWarned=false;_this._pushNativeInitialized=false;_this._fatalJsCaptureNativeInitialized=false;_this._pushNativeUnsupported=false;_this._sessionReplayMacOSWarned=false;_this._sessionReplayEvalChain=Promise.resolve();_this._nativeChain=Promise.resolve();_this._sessionReplayEventTriggers=[];_this._eventsStoragePreloadSucceeded=true;_this._surveysReadyPromise=null;_this._surveysReady=false;_this._requestHeaders={};_this._surveysReadyResolve=null;_this._isInitialized=false;_this._persistence=(_b=options===null||options===void 0?void 0:options.persistence)!==null&&_b!==void 0?_b:'file';_this._disableSurveys=(_c=options===null||options===void 0?void 0:options.disableSurveys)!==null&&_c!==void 0?_c:false;_this._errorTracking=new _errorTracking.ErrorTracking(_this,options===null||options===void 0?void 0:options.errorTracking,_this._logger,{captureFatalException:function captureFatalException(error,hint,eventUuid,timestamp,prepareNativeCapture){return _this._captureFatalAndChooseOwner(eventUuid,prepareNativeCapture,function(){return _this.captureExceptionInternal(error,{$exception_level:'fatal'},hint,{uuid:eventUuid,timestamp:timestamp});});},waitForJSPersist:function(){var _waitForJSPersist=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(){return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=1;return _this._initPromise;case 1:return _context.abrupt("return",_this._eventsStorage.waitForPersistSuccess());case 2:case"end":return _context.stop();}},_callee);}));function waitForJSPersist(){return _waitForJSPersist.apply(this,arguments);}return waitForJSPersist;}(),getPersistenceMode:function getPersistenceMode(){return _this._persistence||'file';},waitForStorageReady:function(){var _waitForStorageReady=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(){return _regenerator["default"].wrap(function(_context2){while(1)switch(_context2.prev=_context2.next){case 0:_context2.next=1;return _this._initPromise;case 1:return _context2.abrupt("return",_this._eventsStoragePreloadSucceeded);case 2:case"end":return _context2.stop();}},_callee2);}));function waitForStorageReady(){return _waitForStorageReady.apply(this,arguments);}return waitForStorageReady;}(),isNativeCaptureReady:function isNativeCaptureReady(){return _this._isNativePluginInitialized();}});_this._setDefaultPersonProperties=(_d=options===null||options===void 0?void 0:options.setDefaultPersonProperties)!==null&&_d!==void 0?_d:true;_this._overrideDisplayLanguage=((_a=options===null||options===void 0?void 0:options.overrideDisplayLanguage)===null||_a===void 0?void 0:_a.trim())||null;_this._requestHeaders=(_e=options===null||options===void 0?void 0:options.requestHeaders)!==null&&_e!==void 0?_e:{};_this._appProperties=typeof(options===null||options===void 0?void 0:options.customAppProperties)==='function'?options.customAppProperties((0,_nativeDeps.getAppProperties)()):(options===null||options===void 0?void 0:options.customAppProperties)||(0,_nativeDeps.getAppProperties)();var storagePromise;var theStorage;if(_this._persistence==='file'){theStorage=(_f=options===null||options===void 0?void 0:options.customStorage)!==null&&_f!==void 0?_f:(0,_nativeDeps.buildOptimisticAsyncStorage)();}if(theStorage){_this._eventsStorage=(0,_storage.createEventsStorage)(theStorage);_this._logsStorage=(0,_storage.createLogsStorage)(theStorage);var preloads=[];if(_this._eventsStorage.preloadPromise){void _this._eventsStorage.preloadPromise["catch"](function(){_this._eventsStoragePreloadSucceeded=false;});preloads.push(['events',_this._eventsStorage.preloadPromise]);}if(_this._logsStorage.preloadPromise){preloads.push(['logs',_this._logsStorage.preloadPromise]);}if(preloads.length>0){storagePromise=(0,_core.allSettled)(preloads.map(function(_ref){var _ref2=(0,_slicedToArray2["default"])(_ref,2),p=_ref2[1];return p;})).then(function(results){results.forEach(function(r,i){if(r.status==='rejected'){_this._logger.error("PostHog ".concat(preloads[i][0]," storage preload failed:"),r.reason);}});});}}else{_this._eventsStorage=(0,_storage.createEventsMemoryStorage)();_this._logsStorage=(0,_storage.createLogsMemoryStorage)();}_this._currentAppState=mapAppStateForLogs(_reactNative.AppState.currentState);_this._resolvedLogsConfig=(0,_logsDefaults.resolveLogsConfig)(options===null||options===void 0?void 0:options.logs);_this._logs=new _core.PostHogLogs(_this,_this._resolvedLogsConfig,_this._logger,function(){var _a;var flags=_this.getFeatureFlags();var flagKeys=flags?Object.keys(flags):undefined;return{distinctId:_this.getDistinctId()||undefined,sessionId:_this.getSessionId()||undefined,screenName:((_a=_this.sessionProps)===null||_a===void 0?void 0:_a.$screen_name)||undefined,appState:_this._currentAppState,activeFeatureFlags:flagKeys&&flagKeys.length>0?flagKeys:undefined};},function(fn){return _this.wrap(fn);},function(){return _this._logsStorage.waitForPersist();});_reactNative.AppState.addEventListener('change',function(state){if(state==='unknown'){return;}var mapped=mapAppStateForLogs(state);if(mapped){_this._currentAppState=mapped;}void _this.flush()["catch"](function(){var _ref3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(err){return _regenerator["default"].wrap(function(_context3){while(1)switch(_context3.prev=_context3.next){case 0:_context3.next=1;return(0,_core.logFlushError)(err);case 1:case"end":return _context3.stop();}},_callee3);}));return function(_x3){return _ref3.apply(this,arguments);};}());var isBackgrounding=mapped==='background';var logsFlushPromise=isBackgrounding?_this._logs.flushWithTimeout(_this._resolvedLogsConfig.backgroundFlushBudgetMs):_this._logs.flush();void logsFlushPromise["catch"](function(){var _ref4=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(err){return _regenerator["default"].wrap(function(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=1;return(0,_core.logFlushError)(err);case 1:case"end":return _context4.stop();}},_callee4);}));return function(_x4){return _ref4.apply(this,arguments);};}());void _this._eventsStorage.waitForPersist();void _this._logsStorage.waitForPersist();if(state==='active'){_this.getSessionId();}});var initAfterStorage=function initAfterStorage(){var enablePersistSessionIdAcrossRestart=options===null||options===void 0?void 0:options.enablePersistSessionIdAcrossRestart;if(!enablePersistSessionIdAcrossRestart){_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionId,null);_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionLastTimestamp,null);_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionStartTimestamp,null);}_this.setupBootstrap(options);if(!_this.getPersistedProperty(_core.PostHogPersistedProperty.DeviceId)){var anonId=_this.getAnonymousId();if(anonId){_this.setPersistedProperty(_core.PostHogPersistedProperty.DeviceId,anonId);}}if(_this._setDefaultPersonProperties){_this._setDefaultPersonPropertiesForFlags(false);}_this._isInitialized=true;if(_this.isDisabled){return;}var cachedRemoteConfig=_this.getPersistedProperty(_core.PostHogPersistedProperty.RemoteConfig);if(cachedRemoteConfig){_this._errorTracking.onRemoteConfig(cachedRemoteConfig.errorTracking);}_this.reloadRemoteConfigAsync().then(function(response){if(response){_this._errorTracking.onRemoteConfig(response.errorTracking);_this._handleSurveysFromRemoteConfig(response);}})["catch"](function(error){_this._logger.error('Error loading remote config:',error);})["finally"](function(){_this._notifySurveysReady();});if((options===null||options===void 0?void 0:options.captureAppLifecycleEvents)!==false){void _this.captureAppLifecycleEvents();}void _this.persistAppVersion();void _this.startSessionReplay(options,cachedRemoteConfig!==null&&cachedRemoteConfig!==void 0?cachedRemoteConfig:undefined);_this.onFeatureFlags(function(){var _a;if(_this._isEnableSessionReplay()||((_a=_this._manualRecordingStartRequest)===null||_a===void 0?void 0:_a.pending)){void _this._evaluateAndStartSessionReplay();}});if((options===null||options===void 0?void 0:options.addTracingHeaders)&&options.addTracingHeaders.length>0){(0,_core.patchFetchForTracingHeaders)(_this,options.addTracingHeaders);}};if(storagePromise){_this._initPromise=storagePromise.then(initAfterStorage);}else{_this._initPromise=Promise.resolve();initAfterStorage();}return _this;}(0,_inherits2["default"])(PostHog,_PostHogCore);return(0,_createClass2["default"])(PostHog,[{key:"ready",value:(function(){var _ready=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee5(){return _regenerator["default"].wrap(function(_context5){while(1)switch(_context5.prev=_context5.next){case 0:_context5.next=1;return this._initPromise;case 1:case"end":return _context5.stop();}},_callee5,this);}));function ready(){return _ready.apply(this,arguments);}return ready;}())},{key:"onRemoteConfig",value:function onRemoteConfig(response){this._errorTracking.onRemoteConfig(response.errorTracking);}},{key:"_storageForKey",value:function _storageForKey(key){return key===_core.PostHogPersistedProperty.LogsQueue?this._logsStorage:this._eventsStorage;}},{key:"getPersistedProperty",value:function getPersistedProperty(key){return this._storageForKey(key).getItem(key);}},{key:"setPersistedProperty",value:function setPersistedProperty(key,value){var storage=this._storageForKey(key);if(key===_core.PostHogPersistedProperty.SurveysInProgress&&value===null){var otherProjects=(0,_surveyProgress.getOtherProjectSurveyProgress)(this);otherProjects.length?storage.setItem(key,otherProjects):storage.removeItem(key);this._events.emit('surveysReset',undefined);}else{value!==null?storage.setItem(key,value):storage.removeItem(key);}if(key===_core.PostHogPersistedProperty.PersonProperties){this._events.emit('personProperties',value);}}},{key:"flushStorage",value:(function(){var _flushStorage=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee6(){return _regenerator["default"].wrap(function(_context6){while(1)switch(_context6.prev=_context6.next){case 0:_context6.next=1;return this._eventsStorage.waitForPersist();case 1:case"end":return _context6.stop();}},_callee6,this);}));function flushStorage(){return _flushStorage.apply(this,arguments);}return flushStorage;}())},{key:"_shutdown",value:(function(){var _shutdown2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee7(){var shutdownTimeoutMs,start,remainingMs,logsBudgetMs,_remainingMs,drain,_args7=arguments;return _regenerator["default"].wrap(function(_context7){while(1)switch(_context7.prev=_context7.next){case 0:shutdownTimeoutMs=_args7.length>0&&_args7[0]!==undefined?_args7[0]:30000;this._cancelManualRecordingStart();start=Date.now();_context7.prev=1;remainingMs=Math.max(0,shutdownTimeoutMs-(Date.now()-start));logsBudgetMs=Math.min(remainingMs,this._resolvedLogsConfig.terminationFlushBudgetMs);_context7.next=2;return Promise.all([this._logs.shutdown(logsBudgetMs),_superPropGet(PostHog,"_shutdown",this,3)([remainingMs])]);case 2:_context7.prev=2;this._errorTracking.shutdown();_remainingMs=Math.max(0,shutdownTimeoutMs-(Date.now()-start));drain=Promise.all([this._eventsStorage.waitForPersist(),this._logsStorage.waitForPersist()]);_context7.next=3;return(0,_core.raceWithTimeout)(drain,_remainingMs);case 3:return _context7.finish(2);case 4:case"end":return _context7.stop();}},_callee7,this,[[1,,2,4]]);}));function _shutdown(){return _shutdown2.apply(this,arguments);}return _shutdown;}())},{key:"fetch",value:function(_fetch){function fetch(_x,_x2){return _fetch.apply(this,arguments);}fetch.toString=function(){return _fetch.toString();};return fetch;}(function(url,options){return fetch(url,options);})},{key:"getLibraryId",value:function getLibraryId(){return'posthog-react-native';}},{key:"getLibraryVersion",value:function getLibraryVersion(){return _version.version;}},{key:"getCustomUserAgent",value:function getCustomUserAgent(){if(_reactNative.Platform.OS==='web'){return'';}return"".concat(this.getLibraryId(),"/").concat(this.getLibraryVersion());}},{key:"getCustomHeaders",value:function getCustomHeaders(){return _objectSpread(_objectSpread({},_superPropGet(PostHog,"getCustomHeaders",this,3)([])),this._requestHeaders);}},{key:"getCommonEventProperties",value:function getCommonEventProperties(){var _Dimensions$get=_reactNative.Dimensions.get(_reactNative.Platform.OS==='ios'?'window':'screen'),width=_Dimensions$get.width,height=_Dimensions$get.height;return _objectSpread(_objectSpread(_objectSpread({},_superPropGet(PostHog,"getCommonEventProperties",this,3)([])),this._appProperties),{},{$screen_height:height,$screen_width:width});}},{key:"getSurveyDisplayLanguageOverride",value:function getSurveyDisplayLanguageOverride(){return this._overrideDisplayLanguage;}},{key:"register",value:function register(properties){return _superPropGet(PostHog,"register",this,3)([properties]);}},{key:"unregister",value:function unregister(property){return _superPropGet(PostHog,"unregister",this,3)([property]);}},{key:"reset",value:function reset(propertiesToKeep){var _this2=this;var effectivePropertiesToKeep=propertiesToKeep!==null&&propertiesToKeep!==void 0?propertiesToKeep:[_core.PostHogPersistedProperty.InstalledAppBuild,_core.PostHogPersistedProperty.InstalledAppVersion,_core.PostHogPersistedProperty.DeviceId];this._cancelManualRecordingStart();_superPropGet(PostHog,"reset",this,3)([[_core.PostHogPersistedProperty.RemoteConfig,_core.PostHogPersistedProperty.SessionReplay,_core.PostHogPersistedProperty.Surveys,_core.PostHogPersistedProperty.PushRegistered].concat((0,_toConsumableArray2["default"])(effectivePropertiesToKeep))]);if(this._setDefaultPersonProperties){this._setDefaultPersonPropertiesForFlags(false);}if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.reset){void this._enqueueNative('reset',function(plugin){var _a;return(_a=plugin.reset)===null||_a===void 0?void 0:_a.call(plugin,String(_this2.getDistinctId()),String(_this2.getAnonymousId()));},this.getPersistedProperty(_core.PostHogPersistedProperty.PushRegistered)===true);}this._propagateNativeOptOut();void this._eventsStorage.waitForPersist();}},{key:"_setDefaultPersonPropertiesForFlags",value:function _setDefaultPersonPropertiesForFlags(){var _this3=this;var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var defaultProps={};var relevantKeys=['$app_version','$app_build','$app_namespace','$os_name','$os_version','$device_type'];relevantKeys.forEach(function(key){var value=_this3._appProperties[key];if(value!==null&&value!==undefined){defaultProps[key]=value;}});var commonProps=this.getCommonEventProperties();if(commonProps.$lib){defaultProps.$lib=commonProps.$lib;}if(commonProps.$lib_version){defaultProps.$lib_version=commonProps.$lib_version;}if(Object.keys(defaultProps).length>0){this.setPersonPropertiesForFlags(defaultProps,reloadFeatureFlags);}}},{key:"flush",value:function flush(){return _superPropGet(PostHog,"flush",this,3)([]);}},{key:"captureLog",value:function captureLog(options){this._logs.captureLog(options);}},{key:"flushLogs",value:function flushLogs(){return this._logs.flush();}},{key:"logger",get:function get(){var _this4=this;if(!this._captureLogger){this._captureLogger={trace:function trace(body,attributes){return _this4.captureLog({body:body,level:'trace',attributes:attributes});},debug:function debug(body,attributes){return _this4.captureLog({body:body,level:'debug',attributes:attributes});},info:function info(body,attributes){return _this4.captureLog({body:body,level:'info',attributes:attributes});},warn:function warn(body,attributes){return _this4.captureLog({body:body,level:'warn',attributes:attributes});},error:function error(body,attributes){return _this4.captureLog({body:body,level:'error',attributes:attributes});},fatal:function fatal(body,attributes){return _this4.captureLog({body:body,level:'fatal',attributes:attributes});}};}return this._captureLogger;}},{key:"optIn",value:function optIn(){var result=_superPropGet(PostHog,"optIn",this,3)([]);void this._eventsStorage.waitForPersist();this._propagateNativeOptOut();return result;}},{key:"optOut",value:function optOut(){var _this5=this;this._cancelManualRecordingStart();var coreOptOut=_superPropGet(PostHog,"optOut",this,3)([]);var persistOptOut=function persistOptOut(){_this5.setPersistedProperty(_core.PostHogPersistedProperty.SurveysInProgress,null);return _this5._eventsStorage.waitForPersist();};var result=Promise.all([coreOptOut,this._isInitialized?persistOptOut():this._initPromise.then(persistOptOut)]).then(function(){return undefined;});if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.unregisterPushNotificationToken){void this.unregisterPushNotificationToken();}this._propagateNativeOptOut();return result;}},{key:"_propagateNativeOptOut",value:function _propagateNativeOptOut(){var _this6=this;if(!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.setOptOut)){return;}void this._enqueueNative('setOptOut',function(plugin){var _a;return(_a=plugin.setOptOut)===null||_a===void 0?void 0:_a.call(plugin,_this6.optedOut);});if(this._isPushNativeEnabled(this._sessionReplayOptions)){void this._ensureNativeInitialized();}}},{key:"isFeatureEnabled",value:function isFeatureEnabled(key,options){return _superPropGet(PostHog,"isFeatureEnabled",this,3)([key,options]);}},{key:"getFeatureFlag",value:function getFeatureFlag(key,options){return _superPropGet(PostHog,"getFeatureFlag",this,3)([key,options]);}},{key:"getFeatureFlagPayload",value:function getFeatureFlagPayload(key){return _superPropGet(PostHog,"getFeatureFlagPayload",this,3)([key]);}},{key:"reloadFeatureFlags",value:function reloadFeatureFlags(){_superPropGet(PostHog,"reloadFeatureFlags",this,3)([]);}},{key:"reloadFeatureFlagsAsync",value:function reloadFeatureFlagsAsync(){return _superPropGet(PostHog,"reloadFeatureFlagsAsync",this,3)([]);}},{key:"updateFlags",value:function updateFlags(flags,payloads,options){_superPropGet(PostHog,"updateFlags",this,3)([flags,payloads,options]);}},{key:"group",value:function group(groupType,groupKey,properties){_superPropGet(PostHog,"group",this,3)([groupType,groupKey,properties]);if(properties&&Object.keys(properties).length>0){var propsToCache={};Object.keys(properties).forEach(function(key){var value=properties[key];if(value!==null&&value!==undefined){propsToCache[key]=value;}});if(Object.keys(propsToCache).length>0){this.setGroupPropertiesForFlags((0,_defineProperty2["default"])({},groupType,propsToCache));}}}},{key:"alias",value:function alias(_alias){_superPropGet(PostHog,"alias",this,3)([_alias]);}},{key:"getDistinctId",value:function getDistinctId(){return _superPropGet(PostHog,"getDistinctId",this,3)([]);}},{key:"getDeviceId",value:function getDeviceId(){var deviceId=this.getPersistedProperty(_core.PostHogPersistedProperty.DeviceId);if(!deviceId){var anonId=this.getAnonymousId();if(anonId){this.setPersistedProperty(_core.PostHogPersistedProperty.DeviceId,anonId);return anonId;}return'';}return deviceId;}},{key:"setPersonPropertiesForFlags",value:function setPersonPropertiesForFlags(properties){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"setPersonPropertiesForFlags",this,3)([properties,reloadFeatureFlags]);}},{key:"resetPersonPropertiesForFlags",value:function resetPersonPropertiesForFlags(){var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;_superPropGet(PostHog,"resetPersonPropertiesForFlags",this,3)([]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"setGroupPropertiesForFlags",value:function setGroupPropertiesForFlags(properties){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"setGroupPropertiesForFlags",this,3)([properties]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"resetGroupPropertiesForFlags",value:function resetGroupPropertiesForFlags(){var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;_superPropGet(PostHog,"resetGroupPropertiesForFlags",this,3)([]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"screen",value:(function(){var _screen=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee8(name,properties,options){return _regenerator["default"].wrap(function(_context8){while(1)switch(_context8.prev=_context8.next){case 0:if(this._isInitialized){_context8.next=1;break;}_context8.next=1;return this._initPromise;case 1:this.registerForSession({$screen_name:name});return _context8.abrupt("return",this.capture('$screen',_objectSpread(_objectSpread({},properties),{},{$screen_name:name}),options));case 2:case"end":return _context8.stop();}},_callee8,this);}));function screen(_x5,_x6,_x7){return _screen.apply(this,arguments);}return screen;}())},{key:"_isEnableSessionReplay",value:function _isEnableSessionReplay(){var _a;return!this.isDisabled&&!(0,_utils.isMacOS)()&&((_a=this._enableSessionReplay)!==null&&_a!==void 0?_a:false);}},{key:"_resetSessionId",value:function _resetSessionId(reactNativeSessionReplay,sessionId){if(reactNativeSessionReplay){reactNativeSessionReplay.endSession();reactNativeSessionReplay.startSession(sessionId);}}},{key:"getSessionId",value:function getSessionId(){var sessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);if(!this._isEnableSessionReplay()&&!this._isNativePluginInitialized()){return sessionId;}if(sessionId.length>0&&this._currentSessionId&&sessionId!==this._currentSessionId){if(_OptionalPlugin.OptionalReactNativePlugin){try{this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));this._logger.info("sessionId rotated from ".concat(this._currentSessionId," to ").concat(sessionId,"."));}catch(e){this._logger.error("Failed to rotate sessionId: ".concat(e,"."));}}this._currentSessionId=sessionId;if(this._sessionReplayEventTriggers.length>0){void this._evaluateAndStartSessionReplay();}}else{this._logger.info("sessionId not rotated, sessionId ".concat(sessionId," and currentSessionId ").concat(this._currentSessionId,"."));}return sessionId;}},{key:"resetSessionId",value:function resetSessionId(){_superPropGet(PostHog,"resetSessionId",this,3)([]);if((this._isEnableSessionReplay()||this._isNativePluginInitialized())&&_OptionalPlugin.OptionalReactNativePlugin){try{_OptionalPlugin.OptionalReactNativePlugin.endSession();this._logger.info("Native PostHog session ended.");}catch(e){this._logger.error("Native PostHog session failed to end: ".concat(e,"."));}}}},{key:"startSessionRecording",value:(function(){var _startSessionRecording2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee0(){var _this7=this;var resumeCurrent,request,_args0=arguments;return _regenerator["default"].wrap(function(_context0){while(1)switch(_context0.prev=_context0.next){case 0:resumeCurrent=_args0.length>0&&_args0[0]!==undefined?_args0[0]:true;this._cancelManualRecordingStart();request={pending:false,retryCount:0};this._manualRecordingStartRequest=request;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee9(){return _regenerator["default"].wrap(function(_context9){while(1)switch(_context9.prev=_context9.next){case 0:_context9.next=1;return _this7._attemptManualRecordingStart(request,resumeCurrent);case 1:case"end":return _context9.stop();}},_callee9);})));_context0.next=1;return this._sessionReplayEvalChain;case 1:case"end":return _context0.stop();}},_callee0,this);}));function startSessionRecording(){return _startSessionRecording2.apply(this,arguments);}return startSessionRecording;}())},{key:"_cancelManualRecordingStart",value:function _cancelManualRecordingStart(){var _a;clearTimeout((_a=this._manualRecordingStartRequest)===null||_a===void 0?void 0:_a.timer);this._manualRecordingStartRequest=undefined;}},{key:"_attemptManualRecordingStart",value:function(){var _attemptManualRecordingStart2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee1(request,resumeCurrent){var started;return _regenerator["default"].wrap(function(_context1){while(1)switch(_context1.prev=_context1.next){case 0:if(!(this._manualRecordingStartRequest!==request)){_context1.next=1;break;}return _context1.abrupt("return",false);case 1:if(!(this.isDisabled||this.optedOut)){_context1.next=2;break;}this._cancelManualRecordingStart();return _context1.abrupt("return",false);case 2:_context1.next=3;return this._startSessionRecording(resumeCurrent);case 3:started=_context1.sent;if(!(this._manualRecordingStartRequest!==request)){_context1.next=5;break;}if(!started){_context1.next=4;break;}_context1.next=4;return this._stopSessionRecording();case 4:return _context1.abrupt("return",false);case 5:if(started){this._cancelManualRecordingStart();}else{request.pending=true;this._scheduleManualRecordingStartRetry(request);}return _context1.abrupt("return",started);case 6:case"end":return _context1.stop();}},_callee1,this);}));function _attemptManualRecordingStart(_x8,_x9){return _attemptManualRecordingStart2.apply(this,arguments);}return _attemptManualRecordingStart;}()},{key:"_scheduleManualRecordingStartRetry",value:function _scheduleManualRecordingStartRetry(request){var _this8=this;var delay=MANUAL_RECORDING_START_RETRY_DELAYS_MS[request.retryCount];if(request.timer!==undefined||delay===undefined||!this._sessionReplayNativeInitialized||!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.startRecording)){return;}request.retryCount++;request.timer=(0,_core.safeSetTimeout)(function(){request.timer=undefined;_this8._sessionReplayEvalChain=_this8._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee10(){return _regenerator["default"].wrap(function(_context10){while(1)switch(_context10.prev=_context10.next){case 0:_context10.next=1;return _this8._attemptManualRecordingStart(request,true);case 1:case"end":return _context10.stop();}},_callee10);})));},delay);}},{key:"_startSessionRecording",value:function(){var _startSessionRecording3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee11(resumeCurrent){var _this9=this;var initialized,newSessionId,started,_t;return _regenerator["default"].wrap(function(_context11){while(1)switch(_context11.prev=_context11.next){case 0:_context11.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context11.next=2;break;}return _context11.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context11.next=3;break;}return _context11.abrupt("return",false);case 3:_context11.prev=3;if(_OptionalPlugin.OptionalReactNativePlugin.startRecording){_context11.next=4;break;}this._logger.warn('startRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');return _context11.abrupt("return",false);case 4:if(this._sessionReplayNativeInitialized){_context11.next=6;break;}this._logger.info('Native session replay SDK not initialized, initializing now...');_context11.next=5;return this.initializeNativePlugin(this._sessionReplayOptions,undefined,true);case 5:initialized=_context11.sent;if(initialized){_context11.next=6;break;}this._logger.error('Failed to initialize native session replay SDK.');return _context11.abrupt("return",false);case 6:if(!resumeCurrent){_superPropGet(PostHog,"resetSessionId",this,3)([]);newSessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(newSessionId));this._currentSessionId=newSessionId;}_context11.next=7;return _OptionalPlugin.OptionalReactNativePlugin.startRecording(resumeCurrent);case 7:_context11.next=8;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled()["catch"](function(e){_this9._logger.warn("Failed to confirm the session recording started: ".concat(e));return true;});case 8:started=_context11.sent;if(started){_context11.next=9;break;}this._logger.warn('The native SDK refused to start session recording, usually because its remote config is not loaded yet. '+'PostHog retries on the next feature flags load.');return _context11.abrupt("return",false);case 9:this._logger.info("Session recording ".concat(resumeCurrent?'resumed':'started',"."));return _context11.abrupt("return",true);case 10:_context11.prev=10;_t=_context11["catch"](3);this._logger.error("Failed to start session recording: ".concat(_t));return _context11.abrupt("return",false);case 11:case"end":return _context11.stop();}},_callee11,this,[[3,10]]);}));function _startSessionRecording(_x0){return _startSessionRecording3.apply(this,arguments);}return _startSessionRecording;}()},{key:"stopSessionRecording",value:(function(){var _stopSessionRecording2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee13(){var _this0=this;return _regenerator["default"].wrap(function(_context13){while(1)switch(_context13.prev=_context13.next){case 0:this._cancelManualRecordingStart();this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee12(){return _regenerator["default"].wrap(function(_context12){while(1)switch(_context12.prev=_context12.next){case 0:_context12.next=1;return _this0._stopSessionRecording();case 1:case"end":return _context12.stop();}},_callee12);})));_context13.next=1;return this._sessionReplayEvalChain;case 1:case"end":return _context13.stop();}},_callee13,this);}));function stopSessionRecording(){return _stopSessionRecording2.apply(this,arguments);}return stopSessionRecording;}())},{key:"_stopSessionRecording",value:function(){var _stopSessionRecording3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee14(){var _t2;return _regenerator["default"].wrap(function(_context14){while(1)switch(_context14.prev=_context14.next){case 0:_context14.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context14.next=2;break;}return _context14.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context14.next=3;break;}return _context14.abrupt("return",false);case 3:_context14.prev=3;if(_OptionalPlugin.OptionalReactNativePlugin.stopRecording){_context14.next=4;break;}this._logger.warn('stopRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');return _context14.abrupt("return",false);case 4:_context14.next=5;return _OptionalPlugin.OptionalReactNativePlugin.stopRecording();case 5:this._logger.info('Session recording stopped.');return _context14.abrupt("return",true);case 6:_context14.prev=6;_t2=_context14["catch"](3);this._logger.error("Failed to stop session recording: ".concat(_t2));return _context14.abrupt("return",false);case 7:case"end":return _context14.stop();}},_callee14,this,[[3,6]]);}));function _stopSessionRecording(){return _stopSessionRecording3.apply(this,arguments);}return _stopSessionRecording;}()},{key:"isSessionReplayActive",value:(function(){var _isSessionReplayActive=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee15(){var _t3;return _regenerator["default"].wrap(function(_context15){while(1)switch(_context15.prev=_context15.next){case 0:_context15.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context15.next=2;break;}return _context15.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context15.next=3;break;}return _context15.abrupt("return",false);case 3:_context15.prev=3;_context15.next=4;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled();case 4:return _context15.abrupt("return",_context15.sent);case 5:_context15.prev=5;_t3=_context15["catch"](3);this._logger.error("Failed to check session replay status: ".concat(_t3));return _context15.abrupt("return",false);case 6:case"end":return _context15.stop();}},_callee15,this,[[3,5]]);}));function isSessionReplayActive(){return _isSessionReplayActive.apply(this,arguments);}return isSessionReplayActive;}())},{key:"identify",value:function identify(distinctId,properties,options){var _this1=this;var previousDistinctId=this.getDistinctId();var userProps=(properties===null||properties===void 0?void 0:properties.$set)||properties;var userPropsOnce=properties===null||properties===void 0?void 0:properties.$set_once;_superPropGet(PostHog,"identify",this,3)([distinctId,properties,options]);var propsToCache={};if(userProps&&(0,_typeof2["default"])(userProps)==='object'&&!Array.isArray(userProps)){Object.entries(userProps).forEach(function(_ref8){var _ref9=(0,_slicedToArray2["default"])(_ref8,2),key=_ref9[0],value=_ref9[1];if(value!==null&&value!==undefined){propsToCache[key]=value;}});}var propsOnceToCache={};if(userPropsOnce&&(0,_typeof2["default"])(userPropsOnce)==='object'&&!Array.isArray(userPropsOnce)){Object.entries(userPropsOnce).forEach(function(_ref0){var _ref1=(0,_slicedToArray2["default"])(_ref0,2),key=_ref1[0],value=_ref1[1];if(value!==null&&value!==undefined){propsOnceToCache[key]=value;}});}if(Object.keys(propsToCache).length>0||Object.keys(propsOnceToCache).length>0){this.setPersonPropertiesForFlags(_objectSpread({$set:propsToCache},Object.keys(propsOnceToCache).length>0?{$set_once:propsOnceToCache}:{}),false);}if(_OptionalPlugin.OptionalReactNativePlugin){void this._enqueueNative('identify',function(plugin){var nativeDistinctId=String(_this1.getDistinctId()||previousDistinctId);var anonymousId=String(_this1.getAnonymousId());var identified=plugin.identify(nativeDistinctId,anonymousId);_this1._logger.info("Native PostHog identified with distinctId ".concat(nativeDistinctId," and anonymousId ").concat(anonymousId,"."));return identified;});}void this._eventsStorage.waitForPersist();}},{key:"captureException",value:function captureException(error){var additionalProperties=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var hint=arguments.length>2?arguments[2]:undefined;var _a;try{var result=this.captureExceptionInternal(error,additionalProperties,hint);if(((_a=result===null||result===void 0?void 0:result.additionalProperties)===null||_a===void 0?void 0:_a.$exception_level)==='fatal'){void this._eventsStorage.waitForPersist();void this._logsStorage.waitForPersist();}}catch(e){this._logger.error('Error while capturing $exception:',e);}}},{key:"captureExceptionInternal",value:function captureExceptionInternal(error){var additionalProperties=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var hint=arguments.length>2?arguments[2]:undefined;var options=arguments.length>3?arguments[3]:undefined;var _a,_b;var resolvedHint=hint!==null&&hint!==void 0?hint:{mechanism:{handled:true,type:'generic'},syntheticException:new Error('Synthetic Error')};var merged=_objectSpread(_objectSpread({},(0,_exceptionContext.getExceptionContext)()),additionalProperties);var finalAdditional=this._errorTracking.attachExceptionSteps(merged);var captureOptions=_objectSpread(_objectSpread({},options||{}),{},{_originatedFromCaptureException:true});this.capture('$exception',_objectSpread(_objectSpread({},this.buildExceptionProperties(error,resolvedHint)),finalAdditional),captureOptions);var eventUuid=(_a=captureOptions.uuid)!==null&&_a!==void 0?_a:'';var timestamp=((_b=captureOptions.timestamp)!==null&&_b!==void 0?_b:new Date()).toISOString();return{eventUuid:eventUuid,timestamp:timestamp,additionalProperties:finalAdditional};}},{key:"buildExceptionProperties",value:function buildExceptionProperties(error,hint){try{var builder=this.getErrorPropertiesBuilder();var exceptionProperties=builder.buildFromUnknown(error,hint);return exceptionProperties;}catch(e){this._logger.error('Error while building exception properties:',e);return{};}}},{key:"addExceptionStep",value:function addExceptionStep(message,properties){this._errorTracking.addExceptionStep(message,properties);}},{key:"createErrorPropertiesBuilder",value:function createErrorPropertiesBuilder(){return new _core.ErrorTracking.ErrorPropertiesBuilder([new _core.ErrorTracking.PromiseRejectionEventCoercer(),new _core.ErrorTracking.ErrorCoercer(),new _core.ErrorTracking.ErrorEventCoercer(),new _core.ErrorTracking.ObjectCoercer(),new _core.ErrorTracking.StringCoercer(),new _core.ErrorTracking.PrimitiveCoercer()],_core.ErrorTracking.createStackParser((0,_utils.isHermes)()?'hermes':'web:javascript',_core.ErrorTracking.chromeStackLineParser,_core.ErrorTracking.geckoStackLineParser));}},{key:"initReactNativeNavigation",value:function initReactNativeNavigation(options){return(0,_wixNavigation.withReactNativeNavigation)(this,options);}},{key:"createPersonProfile",value:function createPersonProfile(){_superPropGet(PostHog,"createPersonProfile",this,3)([]);}},{key:"setPersonProperties",value:function setPersonProperties(userPropertiesToSet,userPropertiesToSetOnce){var reloadFeatureFlags=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;_superPropGet(PostHog,"setPersonProperties",this,3)([userPropertiesToSet,userPropertiesToSetOnce,reloadFeatureFlags]);}},{key:"unsetPersonProperties",value:function unsetPersonProperties(propertyNames){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"unsetPersonProperties",this,3)([propertyNames,reloadFeatureFlags]);}},{key:"getSurveys",value:function(){var _getSurveys=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee16(){var surveys;return _regenerator["default"].wrap(function(_context16){while(1)switch(_context16.prev=_context16.next){case 0:if(!(this._disableSurveys===true)){_context16.next=1;break;}this._logger.info('Loading surveys is disabled.');this._cacheSurveys(null,'disabled in config');return _context16.abrupt("return",[]);case 1:surveys=this.getPersistedProperty(_core.PostHogPersistedProperty.Surveys);if(!(surveys&&surveys.length>0)){_context16.next=2;break;}this._logger.info('Surveys fetched from storage: ',JSON.stringify(surveys));return _context16.abrupt("return",surveys);case 2:this._logger.info('No surveys found in storage');return _context16.abrupt("return",[]);case 3:case"end":return _context16.stop();}},_callee16,this);}));function getSurveys(){return _getSurveys.apply(this,arguments);}return getSurveys;}()},{key:"_onSurveysReady",value:function _onSurveysReady(){var _this10=this;if(this._surveysReady){return Promise.resolve();}if(!this._surveysReadyPromise){this._surveysReadyPromise=new Promise(function(resolve){_this10._surveysReadyResolve=resolve;});}return this._surveysReadyPromise;}},{key:"_cacheSurveys",value:function _cacheSurveys(surveys,source){this.setPersistedProperty(_core.PostHogPersistedProperty.Surveys,surveys);if(surveys&&surveys.length>0){this._logger.info("Surveys cached from ".concat(source,":"),JSON.stringify(surveys));}else if(surveys===null){this._logger.info("Surveys cleared (".concat(source,")"));}else{this._logger.info("No surveys to cache from ".concat(source,")"));}}},{key:"_notifySurveysReady",value:function _notifySurveysReady(){this._surveysReady=true;if(this._surveysReadyResolve){this._surveysReadyResolve();this._surveysReadyResolve=null;this._surveysReadyPromise=null;}}},{key:"_handleSurveysFromRemoteConfig",value:function _handleSurveysFromRemoteConfig(response){if(this._disableSurveys===true){this._logger.info('Loading surveys skipped, disabled.');this._cacheSurveys(null,'remote config (disabled)');return;}var surveys=response.surveys;if(Array.isArray(surveys)){this._cacheSurveys(surveys,'remote config');}else{this._cacheSurveys(null,'remote config');}}},{key:"registerPushNotificationToken",value:(function(){var _registerPushNotificationToken=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee17(deviceToken,options){var _this11=this;return _regenerator["default"].wrap(function(_context17){while(1)switch(_context17.prev=_context17.next){case 0:return _context17.abrupt("return",this._callPushPlugin('registerPushNotificationToken',{allowMacOS:false,requireInit:true,noop:'token not registered'},function(plugin){var _a;var _b;_this11.setPersistedProperty(_core.PostHogPersistedProperty.PushRegistered,true);return(_a=plugin.registerPushNotificationToken)===null||_a===void 0?void 0:_a.call(plugin,deviceToken,(_b=options===null||options===void 0?void 0:options.appId)!==null&&_b!==void 0?_b:null);}));case 1:case"end":return _context17.stop();}},_callee17,this);}));function registerPushNotificationToken(_x1,_x10){return _registerPushNotificationToken.apply(this,arguments);}return registerPushNotificationToken;}())},{key:"unregisterPushNotificationToken",value:(function(){var _unregisterPushNotificationToken=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee18(){var _this12=this;return _regenerator["default"].wrap(function(_context18){while(1)switch(_context18.prev=_context18.next){case 0:return _context18.abrupt("return",this._callPushPlugin('unregisterPushNotificationToken',{allowMacOS:false,allowWhenOptedOut:true,requireInit:this.getPersistedProperty(_core.PostHogPersistedProperty.PushRegistered)===true,noop:'nothing to unregister'},function(plugin){var _a;_this12.setPersistedProperty(_core.PostHogPersistedProperty.PushRegistered,null);return(_a=plugin.unregisterPushNotificationToken)===null||_a===void 0?void 0:_a.call(plugin);}));case 1:case"end":return _context18.stop();}},_callee18,this);}));function unregisterPushNotificationToken(){return _unregisterPushNotificationToken.apply(this,arguments);}return unregisterPushNotificationToken;}())},{key:"capturePushNotificationOpened",value:(function(){var _capturePushNotificationOpened=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee19(options){var properties,_i,_arr,key;return _regenerator["default"].wrap(function(_context19){while(1)switch(_context19.prev=_context19.next){case 0:properties={};for(_i=0,_arr=['title','subtitle','body','payload','action'];_i<_arr.length;_i++){key=_arr[_i];if(options[key]!==undefined){properties[key]=options[key];}}return _context19.abrupt("return",this._callPushPlugin('capturePushNotificationOpened',{allowMacOS:true,requireInit:true,noop:'event not captured'},function(plugin){var _a;return(_a=plugin.capturePushNotificationOpened)===null||_a===void 0?void 0:_a.call(plugin,properties);}));case 1:case"end":return _context19.stop();}},_callee19,this);}));function capturePushNotificationOpened(_x11){return _capturePushNotificationOpened.apply(this,arguments);}return capturePushNotificationOpened;}())},{key:"_callPushPlugin",value:function(){var _callPushPlugin2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee20(method,behavior,invoke){var _this13=this;return _regenerator["default"].wrap(function(_context20){while(1)switch(_context20.prev=_context20.next){case 0:if(!this.isDisabled){_context20.next=1;break;}return _context20.abrupt("return");case 1:if(!(this.optedOut&&!behavior.allowWhenOptedOut)){_context20.next=2;break;}this._logger.warn("".concat(method," skipped: the user is opted out; ").concat(behavior.noop,"."));return _context20.abrupt("return");case 2:if(!((0,_utils.isWeb)()||!behavior.allowMacOS&&(0,_utils.isMacOS)())){_context20.next=3;break;}this._logger.warn("".concat(method," is not supported on ").concat((0,_utils.isWeb)()?'web':'macOS',"; ").concat(behavior.noop,"."));return _context20.abrupt("return");case 3:if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin[method]){_context20.next=4;break;}this._logger.warn("".concat(method," requires @posthog/react-native-plugin; install or update it."));return _context20.abrupt("return");case 4:return _context20.abrupt("return",this._enqueueNative(method,function(plugin){if(_this13.optedOut&&!behavior.allowWhenOptedOut){_this13._logger.warn("".concat(method," skipped: the user is opted out; ").concat(behavior.noop,"."));return;}return invoke(plugin);},behavior.requireInit));case 5:case"end":return _context20.stop();}},_callee20,this);}));function _callPushPlugin(_x12,_x13,_x14){return _callPushPlugin2.apply(this,arguments);}return _callPushPlugin;}()},{key:"_enqueueNative",value:function _enqueueNative(label,run){var _this14=this;var requireInit=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var next=this._nativeChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee21(){return _regenerator["default"].wrap(function(_context21){while(1)switch(_context21.prev=_context21.next){case 0:if(!(_this14.isDisabled||(0,_utils.isWeb)()||!_OptionalPlugin.OptionalReactNativePlugin)){_context21.next=1;break;}return _context21.abrupt("return");case 1:_context21.next=2;return _this14._initPromise["catch"](function(){});case 2:_context21.next=3;return _this14._sessionReplayEvalChain["catch"](function(){});case 3:if(_this14._isNativePluginInitialized()){_context21.next=6;break;}if(requireInit){_context21.next=4;break;}return _context21.abrupt("return");case 4:_context21.next=5;return _this14._ensureNativeInitialized();case 5:if(_this14._isNativePluginInitialized()){_context21.next=6;break;}_this14._logger.warn("".concat(label," skipped: the native plugin is not initialized."));return _context21.abrupt("return");case 6:_context21.next=7;return(0,_core.raceWithTimeout)(Promise.resolve(run(_OptionalPlugin.OptionalReactNativePlugin)),NATIVE_CALL_TIMEOUT_MS,function(){return _this14._logger.warn("Native PostHog ".concat(label," timed out after ").concat(NATIVE_CALL_TIMEOUT_MS,"ms; continuing."));});case 7:case"end":return _context21.stop();}},_callee21);})))["catch"](function(e){return _this14._logger.warn("Native PostHog ".concat(label," failed: ").concat(e,"."));});this._nativeChain=next;return next;}},{key:"_ensureNativeInitialized",value:function _ensureNativeInitialized(){var _this15=this;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee22(){return _regenerator["default"].wrap(function(_context22){while(1)switch(_context22.prev=_context22.next){case 0:if(_this15._isNativePluginInitialized()){_context22.next=1;break;}_context22.next=1;return _this15.initializeNativePlugin(_this15._sessionReplayOptions,undefined,false,true);case 1:case"end":return _context22.stop();}},_callee22);})));return this._sessionReplayEvalChain;}},{key:"_pluginVersionAtLeast",value:function _pluginVersionAtLeast(major,minor){var version=_OptionalPlugin.OptionalReactNativePluginVersion===null||_OptionalPlugin.OptionalReactNativePluginVersion===void 0?void 0:_OptionalPlugin.OptionalReactNativePluginVersion.match(/^(\d+)\.(\d+)\.\d+(?:\+[\w.-]+)?$/);if(!version){return false;}var _ref12=[Number(version[1]),Number(version[2])],installedMajor=_ref12[0],installedMinor=_ref12[1];return installedMajor>major||installedMajor===major&&installedMinor>=minor;}},{key:"_nativeErrorAutocapture",value:function _nativeErrorAutocapture(options){var _a;var autocapture=(_a=options===null||options===void 0?void 0:options.errorTracking)===null||_a===void 0?void 0:_a.autocapture;if(this.isDisabled||(0,_typeof2["default"])(autocapture)!=='object'){return{nativeCrashes:false,androidNdkCrashes:false};}var androidNdkCrashes=_reactNative.Platform.OS==='android'&&autocapture.androidNdkCrashes===true;if(androidNdkCrashes&&!this._pluginVersionAtLeast(2,12)){if(!this._androidNdkCrashesUnsupportedWarned){this._androidNdkCrashesUnsupportedWarned=true;this._logger.warn("errorTracking.autocapture.androidNdkCrashes requires @posthog/react-native-plugin 2.12.0 or later "+"(installed: ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',"); ignoring."));}androidNdkCrashes=false;}return{nativeCrashes:autocapture.nativeCrashes===true,androidNdkCrashes:androidNdkCrashes};}},{key:"_isAutocaptureNativeErrors",value:function _isAutocaptureNativeErrors(options){var _this$_nativeErrorAut=this._nativeErrorAutocapture(options),nativeCrashes=_this$_nativeErrorAut.nativeCrashes,androidNdkCrashes=_this$_nativeErrorAut.androidNdkCrashes;return nativeCrashes||androidNdkCrashes;}},{key:"_isFatalJsCaptureNativeEnabled",value:function _isFatalJsCaptureNativeEnabled(){if(this.isDisabled||this.optedOut||(0,_utils.isWeb)()||this._persistence==='memory'){return false;}return this._errorTracking.isUncaughtExceptionAutocaptureEnabled();}},{key:"_isNativePluginInitialized",value:function _isNativePluginInitialized(){return this._sessionReplayNativeInitialized||this._nativeErrorTrackingInitialized||this._pushNativeInitialized||this._fatalJsCaptureNativeInitialized;}},{key:"_isPushNativeEnabled",value:function _isPushNativeEnabled(options){var force=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(this.isDisabled||this.optedOut||(0,_utils.isWeb)()||this._pushNativeUnsupported){return false;}return force||(options===null||options===void 0?void 0:options.capturePushNotificationSubscriptions)!==false||(options===null||options===void 0?void 0:options.capturePushNotificationOpened)!==false||!!(options===null||options===void 0?void 0:options.pushIdentityProvider);}},{key:"initializeSessionReplayNative",value:(function(){var _initializeSessionReplayNative=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee23(options,cachedRemoteConfig){return _regenerator["default"].wrap(function(_context23){while(1)switch(_context23.prev=_context23.next){case 0:return _context23.abrupt("return",this.initializeNativePlugin(options,cachedRemoteConfig,true));case 1:case"end":return _context23.stop();}},_callee23,this);}));function initializeSessionReplayNative(_x15,_x16){return _initializeSessionReplayNative.apply(this,arguments);}return initializeSessionReplayNative;}())},{key:"initializeNativePlugin",value:function(){var _initializeNativePlugin=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee24(options,cachedRemoteConfig){var enableSessionReplay,forcePush,_a,_b,_c,_d,_e,_f,_g,_h,_j,nativeErrorAutocapture,enableNativeErrorTracking,enablePush,enableFatalJsCapture,sessionId,defaultThrottleDelayMs,_ref13,_ref13$maskAllTextInp,maskAllTextInputs,_ref13$maskAllImages,maskAllImages,_ref13$maskAllSandbox,maskAllSandboxedViews,_ref13$captureTouches,captureTouches,_ref13$captureLog,localCaptureLog,_ref13$captureNetwork,localCaptureNetworkTelemetry,_ref13$verifyScreensh,verifyScreenshotMaskAlignment,screenshotScale,screenshotCompressionQuality,screenshotColorMode,_ref13$screenshotMode,screenshotModeBackgroundCapture,localSampleRate,_ref13$iOSdebouncerDe,iOSdebouncerDelayMs,_ref13$androidDebounc,androidDebouncerDelayMs,throttleDelayMs,remoteConsoleLogEnabled,remoteNetworkTimingEnabled,remoteSampleRateRaw,captureLog,captureNetworkTelemetry,localSampleRateValid,remoteSampleRateValid,sampleRate,source,sdkReplayConfig,sessionReplay,cachedSessionReplayConfig,pushOnlyInit,sdkOptions,loggableSdkOptions,wasSessionReplayEnabled,pushIdentityProviderEnabled,pluginConfig,_args24=arguments,_t4,_t5;return _regenerator["default"].wrap(function(_context24){while(1)switch(_context24.prev=_context24.next){case 0:enableSessionReplay=_args24.length>2&&_args24[2]!==undefined?_args24[2]:this._isEnableSessionReplay();forcePush=_args24.length>3&&_args24[3]!==undefined?_args24[3]:false;nativeErrorAutocapture=this._nativeErrorAutocapture(options);enableNativeErrorTracking=nativeErrorAutocapture.nativeCrashes||nativeErrorAutocapture.androidNdkCrashes;enablePush=this._isPushNativeEnabled(options,forcePush);enableFatalJsCapture=this._isFatalJsCaptureNativeEnabled();if(enableSessionReplay&&(0,_utils.isMacOS)()){if(!this._sessionReplayMacOSWarned){this._sessionReplayMacOSWarned=true;this._logger.warn('Session replay is not supported on macOS; ignoring.');}enableSessionReplay=false;}if(!(!enableSessionReplay&&!enableNativeErrorTracking&&!enablePush&&!enableFatalJsCapture)){_context24.next=1;break;}return _context24.abrupt("return",true);case 1:if(_OptionalPlugin.OptionalReactNativePlugin){_context24.next=2;break;}if(enableSessionReplay||enableNativeErrorTracking){this._logger.warn(enableSessionReplay?'Session replay enabled but not installed.':'Native error tracking enabled but not installed.');}this._pushNativeUnsupported=true;return _context24.abrupt("return",false);case 2:if(!((!enableSessionReplay||this._sessionReplayNativeInitialized)&&(!enableNativeErrorTracking||this._nativeErrorTrackingInitialized)&&(!enablePush||this._pushNativeInitialized)&&(!enableFatalJsCapture||this._fatalJsCaptureNativeInitialized))){_context24.next=3;break;}return _context24.abrupt("return",true);case 3:if(!(this._isNativePluginInitialized()&&enableSessionReplay&&!this._sessionReplayNativeInitialized)){_context24.next=5;break;}this._sessionReplayNativeInitialized=true;_context24.next=4;return(_a=_OptionalPlugin.OptionalReactNativePlugin.startRecording)===null||_a===void 0?void 0:_a.call(_OptionalPlugin.OptionalReactNativePlugin,true);case 4:return _context24.abrupt("return",true);case 5:sessionId=this.getSessionId();if(!(sessionId.length===0)){_context24.next=6;break;}this._logger.warn("Native PostHog plugin enabled but no sessionId found.");return _context24.abrupt("return",false);case 6:defaultThrottleDelayMs=1000;_ref13=(_d=options===null||options===void 0?void 0:options.sessionReplayConfig)!==null&&_d!==void 0?_d:{},_ref13$maskAllTextInp=_ref13.maskAllTextInputs,maskAllTextInputs=_ref13$maskAllTextInp===void 0?true:_ref13$maskAllTextInp,_ref13$maskAllImages=_ref13.maskAllImages,maskAllImages=_ref13$maskAllImages===void 0?true:_ref13$maskAllImages,_ref13$maskAllSandbox=_ref13.maskAllSandboxedViews,maskAllSandboxedViews=_ref13$maskAllSandbox===void 0?true:_ref13$maskAllSandbox,_ref13$captureTouches=_ref13.captureTouches,captureTouches=_ref13$captureTouches===void 0?true:_ref13$captureTouches,_ref13$captureLog=_ref13.captureLog,localCaptureLog=_ref13$captureLog===void 0?true:_ref13$captureLog,_ref13$captureNetwork=_ref13.captureNetworkTelemetry,localCaptureNetworkTelemetry=_ref13$captureNetwork===void 0?true:_ref13$captureNetwork,_ref13$verifyScreensh=_ref13.verifyScreenshotMaskAlignment,verifyScreenshotMaskAlignment=_ref13$verifyScreensh===void 0?false:_ref13$verifyScreensh,screenshotScale=_ref13.screenshotScale,screenshotCompressionQuality=_ref13.screenshotCompressionQuality,screenshotColorMode=_ref13.screenshotColorMode,_ref13$screenshotMode=_ref13.screenshotModeBackgroundCapture,screenshotModeBackgroundCapture=_ref13$screenshotMode===void 0?false:_ref13$screenshotMode,localSampleRate=_ref13.sampleRate,_ref13$iOSdebouncerDe=_ref13.iOSdebouncerDelayMs,iOSdebouncerDelayMs=_ref13$iOSdebouncerDe===void 0?defaultThrottleDelayMs:_ref13$iOSdebouncerDe,_ref13$androidDebounc=_ref13.androidDebouncerDelayMs,androidDebouncerDelayMs=_ref13$androidDebounc===void 0?defaultThrottleDelayMs:_ref13$androidDebounc;if(captureTouches===false&&!(0,_utils.isMacOS)()){if(!this._pluginVersionAtLeast(2,9)){this._logger.warn("sessionReplayConfig.captureTouches: false requires @posthog/react-native-plugin 2.9.0 or later. "+"The installed plugin (version ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',") may still record touch coordinates. ")+"Upgrade the plugin and rebuild your app before relying on this setting.");}}throttleDelayMs=(_e=(_b=options===null||options===void 0?void 0:options.sessionReplayConfig)===null||_b===void 0?void 0:_b.throttleDelayMs)!==null&&_e!==void 0?_e:defaultThrottleDelayMs;if(throttleDelayMs===defaultThrottleDelayMs&&(iOSdebouncerDelayMs!==defaultThrottleDelayMs||androidDebouncerDelayMs!==defaultThrottleDelayMs)){throttleDelayMs=Math.max(iOSdebouncerDelayMs,androidDebouncerDelayMs);}remoteConsoleLogEnabled=(0,_utils.getRemoteConfigBool)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.sessionRecording,'consoleLogRecordingEnabled',true);remoteNetworkTimingEnabled=(0,_utils.getRemoteConfigBool)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.capturePerformance,'network_timing',true);remoteSampleRateRaw=(0,_utils.getRemoteConfigNumber)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.sessionRecording,'sampleRate');captureLog=localCaptureLog&&remoteConsoleLogEnabled;captureNetworkTelemetry=localCaptureNetworkTelemetry&&remoteNetworkTimingEnabled;localSampleRateValid=localSampleRate===undefined?undefined:(0,_utils.isValidSampleRate)(localSampleRate)?localSampleRate:undefined;remoteSampleRateValid=remoteSampleRateRaw===undefined?undefined:(0,_utils.isValidSampleRate)(remoteSampleRateRaw)?remoteSampleRateRaw:undefined;sampleRate=localSampleRateValid!==null&&localSampleRateValid!==void 0?localSampleRateValid:remoteSampleRateValid;if(localCaptureLog&&!remoteConsoleLogEnabled){this._logger.info('captureLog disabled by remote config (consoleLogRecordingEnabled=false).');}if(localCaptureNetworkTelemetry&&!remoteNetworkTimingEnabled){this._logger.info('captureNetworkTelemetry disabled by remote config (capturePerformance.network_timing=false).');}if(localSampleRate!==undefined&&localSampleRateValid===undefined){this._logger.warn("Ignoring invalid sessionReplayConfig.sampleRate '".concat(localSampleRate,"'. Expected a number between 0 and 1."));}if(remoteSampleRateRaw!==undefined&&remoteSampleRateValid===undefined){this._logger.warn("Ignoring invalid remote config sessionRecording.sampleRate '".concat(remoteSampleRateRaw,"'. Expected a number between 0 and 1."));}if(localSampleRateValid!==undefined&&remoteSampleRateValid!==undefined){this._logger.warn("Local sessionReplayConfig.sampleRate (".concat(localSampleRateValid,") overrides the remote sampleRate ")+"(".concat(remoteSampleRateValid,"). The project setting is ignored while the local option is set. ")+"Remove sessionReplayConfig.sampleRate to follow the project setting.");}else if(typeof sampleRate==='number'){source=localSampleRateValid!==undefined?'local config':'remote config';this._logger.info("sampleRate set from ".concat(source," (").concat(sampleRate,")."));}else if(cachedRemoteConfig===undefined){this._logger.warn('Session replay starts with no sampleRate because no remote config is cached yet. '+'Any project sample rate applies from the next launch.');}sdkReplayConfig=_objectSpread(_objectSpread(_objectSpread(_objectSpread({maskAllTextInputs:maskAllTextInputs,maskAllImages:maskAllImages,maskAllSandboxedViews:maskAllSandboxedViews,captureTouches:captureTouches,captureLog:captureLog,captureNetworkTelemetry:captureNetworkTelemetry,verifyScreenshotMaskAlignment:verifyScreenshotMaskAlignment},Number.isFinite(screenshotScale)?{screenshotScale:screenshotScale}:{}),Number.isFinite(screenshotCompressionQuality)?{screenshotCompressionQuality:screenshotCompressionQuality}:{}),screenshotColorMode!==undefined?{screenshotColorMode:screenshotColorMode}:{}),{},{screenshotModeBackgroundCapture:screenshotModeBackgroundCapture,sampleRate:sampleRate,iOSdebouncerDelayMs:iOSdebouncerDelayMs,androidDebouncerDelayMs:androidDebouncerDelayMs,throttleDelayMs:throttleDelayMs});this._logger.info("Native PostHog plugin (version ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',") replay config: ").concat(JSON.stringify(sdkReplayConfig)));sessionReplay=(_f=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_f!==void 0?_f:{};cachedSessionReplayConfig=(_g=sessionReplay)!==null&&_g!==void 0?_g:{};this._logger.info("Session replay session recording from flags cached config: ".concat(JSON.stringify(cachedSessionReplayConfig)));pushOnlyInit=(enablePush||enableFatalJsCapture)&&!enableSessionReplay&&!enableNativeErrorTracking;sdkOptions={apiKey:this.apiKey,host:this.host,debug:this.isDebug,distinctId:this.getDistinctId(),anonymousId:this.getAnonymousId(),sdkVersion:this.getLibraryVersion(),flushAt:this.flushAt,optOut:this.optedOut,preloadFeatureFlags:!pushOnlyInit,requestHeaders:this._requestHeaders};loggableSdkOptions=_objectSpread(_objectSpread({},sdkOptions),{},{requestHeaders:Object.keys(this._requestHeaders)});this._logger.info("Native PostHog plugin sdk options: ".concat(JSON.stringify(loggableSdkOptions)));_context24.prev=7;if(!enableSessionReplay){_context24.next=9;break;}_context24.next=8;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled()["catch"](function(){return false;});case 8:_t4=_context24.sent;_context24.next=10;break;case 9:_t4=false;case 10:wasSessionReplayEnabled=_t4;if(!_OptionalPlugin.OptionalReactNativePlugin.setup){_context24.next=13;break;}pushIdentityProviderEnabled=false;if(options===null||options===void 0?void 0:options.pushIdentityProvider){if(_OptionalPlugin.OptionalReactNativePlugin.setPushIdentityProvider){_OptionalPlugin.OptionalReactNativePlugin.setPushIdentityProvider(options.pushIdentityProvider);pushIdentityProviderEnabled=true;}else{this._logger.warn('pushIdentityProvider requires a newer @posthog/react-native-plugin; push subscriptions will be sent unauthenticated.');}}pluginConfig=_objectSpread({sessionReplay:{enabled:enableSessionReplay,sdkReplayConfig:sdkReplayConfig,decideReplayConfig:cachedSessionReplayConfig},errorTracking:{nativeAutocapture:nativeErrorAutocapture.nativeCrashes,androidNdkCrashes:nativeErrorAutocapture.androidNdkCrashes,exceptionSteps:this._errorTracking.getNativePluginExceptionStepsConfig()},push:{capturePushNotificationSubscriptions:(_h=options===null||options===void 0?void 0:options.capturePushNotificationSubscriptions)!==null&&_h!==void 0?_h:true,capturePushNotificationOpened:(_j=options===null||options===void 0?void 0:options.capturePushNotificationOpened)!==null&&_j!==void 0?_j:true,pushIdentityProviderEnabled:pushIdentityProviderEnabled}},(options===null||options===void 0?void 0:options.rageClickConfig)&&{rageClick:options.rageClickConfig});_context24.next=11;return _OptionalPlugin.OptionalReactNativePlugin.setup(String(sessionId),sdkOptions,pluginConfig);case 11:_context24.next=12;return(_c=_OptionalPlugin.OptionalReactNativePlugin.setOptOut)===null||_c===void 0?void 0:_c.call(_OptionalPlugin.OptionalReactNativePlugin,this.optedOut);case 12:if(wasSessionReplayEnabled){this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));}_context24.next=18;break;case 13:if(enableNativeErrorTracking){this._logger.warn('Native error tracking is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');enableNativeErrorTracking=false;}if(enablePush){this._logger.warn('Push notifications require @posthog/react-native-plugin; the legacy session-replay plugin does not support them.');}enablePush=false;this._pushNativeUnsupported=true;if(enableSessionReplay){_context24.next=14;break;}return _context24.abrupt("return",false);case 14:_context24.next=15;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled();case 15:if(_context24.sent){_context24.next=17;break;}_context24.next=16;return _OptionalPlugin.OptionalReactNativePlugin.start(String(sessionId),sdkOptions,sdkReplayConfig,cachedSessionReplayConfig);case 16:_context24.next=18;break;case 17:this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));case 18:this._currentSessionId=sessionId;if(enableSessionReplay){this._sessionReplayNativeInitialized=true;this._logger.info("Session replay started with sessionId ".concat(sessionId,"."));}if(enableNativeErrorTracking){this._nativeErrorTrackingInitialized=true;this._errorTracking.onNativeErrorTrackingReady();this._logger.info('Native error tracking started.');}if(enablePush){this._pushNativeInitialized=true;this._logger.info('Push notification native support started.');}if(enableFatalJsCapture){this._fatalJsCaptureNativeInitialized=true;this._logger.info('Native durable capture for fatal JavaScript exceptions started.');}return _context24.abrupt("return",true);case 19:_context24.prev=19;_t5=_context24["catch"](7);this._logger.error("Native PostHog plugin failed to start: ".concat(_t5,"."));return _context24.abrupt("return",false);case 20:case"end":return _context24.stop();}},_callee24,this,[[7,19]]);}));function initializeNativePlugin(_x17,_x18){return _initializeNativePlugin.apply(this,arguments);}return initializeNativePlugin;}()},{key:"startSessionReplay",value:function(){var _startSessionReplay=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee25(options,cachedRemoteConfig){return _regenerator["default"].wrap(function(_context25){while(1)switch(_context25.prev=_context25.next){case 0:this._enableSessionReplay=options===null||options===void 0?void 0:options.enableSessionReplay;this._sessionReplayOptions=options;_context25.next=1;return this._evaluateAndStartSessionReplay(cachedRemoteConfig);case 1:case"end":return _context25.stop();}},_callee25,this);}));function startSessionReplay(_x19,_x20){return _startSessionReplay.apply(this,arguments);}return startSessionReplay;}()},{key:"_evaluateAndStartSessionReplay",value:function _evaluateAndStartSessionReplay(cachedRemoteConfig){var _this16=this;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then(function(){return _this16._evaluateAndStartSessionReplayInternal(cachedRemoteConfig);});return this._sessionReplayEvalChain;}},{key:"_evaluateAndStartSessionReplayInternal",value:function(){var _evaluateAndStartSessionReplayInternal2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee26(cachedRemoteConfig){var _a,_b,_c,_d,options,enableNativeErrorTracking,enablePush,enableFatalJsCapture,remoteConfig,request,sessionReplay,featureFlags,cachedFeatureFlags,cachedSessionReplayConfig,recordingActive,linkedFlag,value,flag,variant,_value,eventTriggers,activated,_t6;return _regenerator["default"].wrap(function(_context26){while(1)switch(_context26.prev=_context26.next){case 0:options=this._sessionReplayOptions;enableNativeErrorTracking=this._isAutocaptureNativeErrors(options);enablePush=this._isPushNativeEnabled(options);enableFatalJsCapture=this._isFatalJsCaptureNativeEnabled();remoteConfig=cachedRemoteConfig!==null&&cachedRemoteConfig!==void 0?cachedRemoteConfig:this.getPersistedProperty(_core.PostHogPersistedProperty.RemoteConfig);if(this._isEnableSessionReplay()){_context26.next=3;break;}this._logger.info('Session replay is not enabled.');this._sessionReplayEventTriggers=[];if(!(enableNativeErrorTracking||enablePush||enableFatalJsCapture)){_context26.next=1;break;}_context26.next=1;return this.initializeNativePlugin(options,remoteConfig,false);case 1:request=this._manualRecordingStartRequest;if(!(request===null||request===void 0?void 0:request.pending)){_context26.next=2;break;}_context26.next=2;return this._attemptManualRecordingStart(request,true);case 2:return _context26.abrupt("return");case 3:sessionReplay=(_a=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_a!==void 0?_a:{};featureFlags=(_b=this.getKnownFeatureFlags())!==null&&_b!==void 0?_b:{};cachedFeatureFlags=(_c=featureFlags)!==null&&_c!==void 0?_c:{};cachedSessionReplayConfig=(_d=sessionReplay)!==null&&_d!==void 0?_d:{};this._logger.info('Session replay feature flags from flags cached config:',JSON.stringify(cachedFeatureFlags));recordingActive=true;linkedFlag=cachedSessionReplayConfig['linkedFlag'];if(typeof linkedFlag==='string'){value=cachedFeatureFlags[linkedFlag];if(typeof value==='boolean'){recordingActive=value;}else if(typeof value==='string'){recordingActive=true;}else{recordingActive=false;}this._logger.info("Session replay '".concat(linkedFlag,"' linked flag value: '").concat(value,"'"));}else if(linkedFlag&&(0,_typeof2["default"])(linkedFlag)==='object'){flag=linkedFlag['flag'];variant=linkedFlag['variant'];if(flag&&variant){_value=cachedFeatureFlags[flag];recordingActive=_value===variant;this._logger.info("Session replay '".concat(flag,"' linked flag variant '").concat(variant,"' and value '").concat(_value,"'"));}else{this._logger.info("Session replay '".concat(flag,"' linked flag variant: '").concat(variant,"' does not exist/quota limited."));recordingActive=false;}}else{this._logger.info("Session replay has no cached linkedFlag.");}eventTriggers=this._parseEventTriggers(cachedSessionReplayConfig['eventTriggers']);this._sessionReplayEventTriggers=eventTriggers;if(eventTriggers.length>0){activated=this._isEventTriggerActivatedForSession(_superPropGet(PostHog,"getSessionId",this,3)([]));if(!activated){recordingActive=false;}this._logger.info("Session replay event triggers configured (".concat(eventTriggers.length,"); activated: ").concat(activated,"."));}if(!recordingActive){_context26.next=9;break;}if(!(this._sessionReplayRecordingActive===true)){_context26.next=4;break;}return _context26.abrupt("return");case 4:if(!this._sessionReplayNativeInitialized){_context26.next=6;break;}_context26.next=5;return this._startSessionRecording(true);case 5:_t6=_context26.sent;_context26.next=8;break;case 6:_context26.next=7;return this.initializeNativePlugin(options,remoteConfig,true);case 7:_t6=_context26.sent;case 8:this._sessionReplayRecordingActive=_t6;_context26.next=13;break;case 9:this._logger.info('Session replay disabled.');if(!(this._sessionReplayRecordingActive===true)){_context26.next=11;break;}_context26.next=10;return this._stopSessionRecording();case 10:this._sessionReplayRecordingActive=!_context26.sent;_context26.next=12;break;case 11:this._sessionReplayRecordingActive=false;case 12:if(!(enableNativeErrorTracking||enablePush)){_context26.next=13;break;}_context26.next=13;return this.initializeNativePlugin(options,remoteConfig,false);case 13:case"end":return _context26.stop();}},_callee26,this);}));function _evaluateAndStartSessionReplayInternal(_x21){return _evaluateAndStartSessionReplayInternal2.apply(this,arguments);}return _evaluateAndStartSessionReplayInternal;}()},{key:"processBeforeEnqueue",value:function processBeforeEnqueue(message){var observation=this._fatalCaptureObservation;var isObservedFatal=observation!==undefined&&message.uuid===observation.eventUuid&&message.event==='$exception';var processed=_superPropGet(PostHog,"processBeforeEnqueue",this,3)([message]);var suppress=false;if(isObservedFatal&&processed&&observation){try{observation.nativeCapture=observation.prepareNativeCapture(processed);}catch(e){this._logger.warn("Fatal exception payload could not be prepared for native capture: ".concat(e));observation.nativeCapture=undefined;}suppress=observation.nativeCapture!==undefined;observation.queued=!suppress;}try{this._maybeActivateEventTrigger(processed===null||processed===void 0?void 0:processed['event']);}catch(e){this._logger.error("Session replay event trigger check failed: ".concat(e,"."));}return suppress?null:processed;}},{key:"_captureFatalAndChooseOwner",value:function _captureFatalAndChooseOwner(eventUuid,prepareNativeCapture,capture){var observation={eventUuid:eventUuid,prepareNativeCapture:prepareNativeCapture,queued:false};var previousObservation=this._fatalCaptureObservation;this._fatalCaptureObservation=observation;try{capture();}finally{this._fatalCaptureObservation=previousObservation;}return{queued:observation.queued,nativeCapture:observation.nativeCapture};}},{key:"_maybeActivateEventTrigger",value:function _maybeActivateEventTrigger(eventName){if(this._sessionReplayEventTriggers.length===0||typeof eventName!=='string'){return;}if(!this._sessionReplayEventTriggers.includes(eventName)){return;}var sessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);if(!sessionId){return;}if(this._isEventTriggerActivatedForSession(sessionId)&&this._sessionReplayRecordingActive===true){return;}if(!this._isEventTriggerActivatedForSession(sessionId)){this.setPersistedProperty(_core.PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession,sessionId);this._logger.info("Session replay event trigger '".concat(eventName,"' activated for session ").concat(sessionId,"."));}void this._evaluateAndStartSessionReplay();}},{key:"_parseEventTriggers",value:function _parseEventTriggers(value){if(!Array.isArray(value)){return[];}return value.filter(function(entry){return typeof entry==='string';});}},{key:"_isEventTriggerActivatedForSession",value:function _isEventTriggerActivatedForSession(sessionId){return this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession)===sessionId;}},{key:"captureAppLifecycleEvents",value:function(){var _captureAppLifecycleEvents=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee27(){var _this17=this;var _a,appBuild,appVersion,isMemoryPersistence,properties,prevAppBuild,prevAppVersion,initialUrl,_t7,_t8,_t9;return _regenerator["default"].wrap(function(_context27){while(1)switch(_context27.prev=_context27.next){case 0:appBuild=this._appProperties.$app_build;appVersion=this._appProperties.$app_version;isMemoryPersistence=this._persistence==='memory';properties={};if(!isMemoryPersistence){prevAppBuild=this.getPersistedProperty(_core.PostHogPersistedProperty.InstalledAppBuild);prevAppVersion=this.getPersistedProperty(_core.PostHogPersistedProperty.InstalledAppVersion);if(!appBuild||!appVersion){this._logger.warn('PostHog could not track installation/update/open, as the build and version were not set. '+'This can happen if some dependencies are not installed correctly, or if you have provided'+'customAppProperties but not included $app_build or $app_version.');}if(appBuild){if(!prevAppBuild){this.capture('Application Installed',properties);}else if(prevAppBuild!==appBuild){this.capture('Application Updated',_objectSpread(_objectSpread(_objectSpread({},(0,_core.maybeAdd)('previous_version',prevAppVersion)),(0,_core.maybeAdd)('previous_build',prevAppBuild)),properties));}}}else{this._logger.warn('PostHog was initialised with persistence set to "memory", capturing native app events (Application Installed and Application Updated) is not supported.');}_context27.next=1;return _reactNative.Linking.getInitialURL();case 1:_t8=_a=_context27.sent;_t7=_t8!==null;if(!_t7){_context27.next=2;break;}_t7=_a!==void 0;case 2:if(!_t7){_context27.next=3;break;}_t9=_a;_context27.next=4;break;case 3:_t9=undefined;case 4:initialUrl=_t9;this.capture('Application Opened',_objectSpread(_objectSpread({},properties),(0,_core.maybeAdd)('url',initialUrl)));_reactNative.AppState.addEventListener('change',function(state){if(state==='active'){_this17.capture('Application Became Active');}else if(state==='background'){_this17.capture('Application Backgrounded');}});case 5:case"end":return _context27.stop();}},_callee27,this);}));function captureAppLifecycleEvents(){return _captureAppLifecycleEvents.apply(this,arguments);}return captureAppLifecycleEvents;}()},{key:"persistAppVersion",value:function(){var _persistAppVersion=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee28(){var appBuild,appVersion;return _regenerator["default"].wrap(function(_context28){while(1)switch(_context28.prev=_context28.next){case 0:appBuild=this._appProperties.$app_build;appVersion=this._appProperties.$app_version;this.setPersistedProperty(_core.PostHogPersistedProperty.InstalledAppBuild,appBuild);this.setPersistedProperty(_core.PostHogPersistedProperty.InstalledAppVersion,appVersion);case 1:case"end":return _context28.stop();}},_callee28,this);}));function persistAppVersion(){return _persistAppVersion.apply(this,arguments);}return persistAppVersion;}()}]);}(_core.PostHogCore);
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.PostHog=void 0;Object.defineProperty(exports,"PostHogPersistedProperty",{enumerable:true,get:function get(){return _core.PostHogPersistedProperty;}});var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _reactNative=require("react-native");var _core=require("@posthog/core");var _storage=require("./storage");var _surveyProgress=require("./surveys/survey-progress");var _logsDefaults=require("./logs-defaults");var _version=require("./version");var _nativeDeps=require("./native-deps");var _utils=require("./utils");var _wixNavigation=require("./frameworks/wix-navigation");var _OptionalPlugin=require("./optional/OptionalPlugin");var _errorTracking=require("./error-tracking");var _exceptionContext=require("./error-tracking/exception-context");function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}function _callSuper(t,o,e){return o=(0,_getPrototypeOf2["default"])(o),(0,_possibleConstructorReturn2["default"])(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],(0,_getPrototypeOf2["default"])(t).constructor):o.apply(t,e));}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t;})();}function _superPropGet(t,o,e,r){var p=(0,_get2["default"])((0,_getPrototypeOf2["default"])(1&r?t.prototype:t),o,e);return 2&r&&"function"==typeof p?function(t){return p.apply(e,t);}:p;}function mapAppStateForLogs(state){if(state==='background'){return'background';}if(!state||state==='unknown'){return undefined;}return'foreground';}var NATIVE_CALL_TIMEOUT_MS=10000;var MANUAL_RECORDING_START_RETRY_DELAYS_MS=[1000,2000,4000,8000,16000];var PostHog=exports.PostHog=function(_PostHogCore){function PostHog(apiKey,options){var _this;(0,_classCallCheck2["default"])(this,PostHog);var _a;var _b,_c,_d,_e,_f;var normalizedApiKey=typeof apiKey==='string'?apiKey.trim():'';if(!normalizedApiKey){console.error("You must pass your PostHog project's api key. The client will be disabled.");}_this=_callSuper(this,PostHog,[normalizedApiKey,options]);_this._appProperties={};_this._sessionReplayNativeInitialized=false;_this._nativeErrorTrackingInitialized=false;_this._androidNdkCrashesUnsupportedWarned=false;_this._pushNativeInitialized=false;_this._fatalJsCaptureNativeInitialized=false;_this._pushNativeUnsupported=false;_this._sessionReplayMacOSWarned=false;_this._sessionReplayEvalChain=Promise.resolve();_this._nativeChain=Promise.resolve();_this._sessionReplayEventTriggers=[];_this._eventsStoragePreloadSucceeded=true;_this._surveysReadyPromise=null;_this._surveysReady=false;_this._requestHeaders={};_this._surveysReadyResolve=null;_this._isInitialized=false;_this._persistence=(_b=options===null||options===void 0?void 0:options.persistence)!==null&&_b!==void 0?_b:'file';_this._disableSurveys=(_c=options===null||options===void 0?void 0:options.disableSurveys)!==null&&_c!==void 0?_c:false;_this._errorTracking=new _errorTracking.ErrorTracking(_this,options===null||options===void 0?void 0:options.errorTracking,_this._logger,{captureFatalException:function captureFatalException(error,hint,eventUuid,timestamp,prepareNativeCapture){return _this._captureFatalAndChooseOwner(eventUuid,prepareNativeCapture,function(){return _this.captureExceptionInternal(error,{$exception_level:'fatal'},hint,{uuid:eventUuid,timestamp:timestamp});});},waitForJSPersist:function(){var _waitForJSPersist=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(){return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=1;return _this._initPromise;case 1:return _context.abrupt("return",_this._eventsStorage.waitForPersistSuccess());case 2:case"end":return _context.stop();}},_callee);}));function waitForJSPersist(){return _waitForJSPersist.apply(this,arguments);}return waitForJSPersist;}(),getPersistenceMode:function getPersistenceMode(){return _this._persistence||'file';},waitForStorageReady:function(){var _waitForStorageReady=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(){return _regenerator["default"].wrap(function(_context2){while(1)switch(_context2.prev=_context2.next){case 0:_context2.next=1;return _this._initPromise;case 1:return _context2.abrupt("return",_this._eventsStoragePreloadSucceeded);case 2:case"end":return _context2.stop();}},_callee2);}));function waitForStorageReady(){return _waitForStorageReady.apply(this,arguments);}return waitForStorageReady;}(),isNativeCaptureReady:function isNativeCaptureReady(){return _this._isNativePluginInitialized();}});_this._setDefaultPersonProperties=(_d=options===null||options===void 0?void 0:options.setDefaultPersonProperties)!==null&&_d!==void 0?_d:true;_this._overrideDisplayLanguage=((_a=options===null||options===void 0?void 0:options.overrideDisplayLanguage)===null||_a===void 0?void 0:_a.trim())||null;_this._requestHeaders=(_e=options===null||options===void 0?void 0:options.requestHeaders)!==null&&_e!==void 0?_e:{};if(typeof(options===null||options===void 0?void 0:options.customAppProperties)==='function'){_this._appProperties=options.customAppProperties((0,_nativeDeps.getAppProperties)());}else if(options===null||options===void 0?void 0:options.customAppProperties){var reactNativeVersion=(0,_utils.getReactNativeVersion)();_this._appProperties=_objectSpread(_objectSpread({},reactNativeVersion?{$react_native_version:reactNativeVersion}:{}),options.customAppProperties);}else{_this._appProperties=(0,_nativeDeps.getAppProperties)();}var storagePromise;var theStorage;if(_this._persistence==='file'){theStorage=(_f=options===null||options===void 0?void 0:options.customStorage)!==null&&_f!==void 0?_f:(0,_nativeDeps.buildOptimisticAsyncStorage)();}if(theStorage){_this._eventsStorage=(0,_storage.createEventsStorage)(theStorage);_this._logsStorage=(0,_storage.createLogsStorage)(theStorage);var preloads=[];if(_this._eventsStorage.preloadPromise){void _this._eventsStorage.preloadPromise["catch"](function(){_this._eventsStoragePreloadSucceeded=false;});preloads.push(['events',_this._eventsStorage.preloadPromise]);}if(_this._logsStorage.preloadPromise){preloads.push(['logs',_this._logsStorage.preloadPromise]);}if(preloads.length>0){storagePromise=(0,_core.allSettled)(preloads.map(function(_ref){var _ref2=(0,_slicedToArray2["default"])(_ref,2),p=_ref2[1];return p;})).then(function(results){results.forEach(function(r,i){if(r.status==='rejected'){_this._logger.error("PostHog ".concat(preloads[i][0]," storage preload failed:"),r.reason);}});});}}else{_this._eventsStorage=(0,_storage.createEventsMemoryStorage)();_this._logsStorage=(0,_storage.createLogsMemoryStorage)();}_this._currentAppState=mapAppStateForLogs(_reactNative.AppState.currentState);_this._resolvedLogsConfig=(0,_logsDefaults.resolveLogsConfig)(options===null||options===void 0?void 0:options.logs);_this._logs=new _core.PostHogLogs(_this,_this._resolvedLogsConfig,_this._logger,function(){var _a;var flags=_this.getFeatureFlags();var flagKeys=flags?Object.keys(flags):undefined;return{distinctId:_this.getDistinctId()||undefined,sessionId:_this.getSessionId()||undefined,screenName:((_a=_this.sessionProps)===null||_a===void 0?void 0:_a.$screen_name)||undefined,appState:_this._currentAppState,activeFeatureFlags:flagKeys&&flagKeys.length>0?flagKeys:undefined};},function(fn){return _this.wrap(fn);},function(){return _this._logsStorage.waitForPersist();});_reactNative.AppState.addEventListener('change',function(state){if(state==='unknown'){return;}var mapped=mapAppStateForLogs(state);if(mapped){_this._currentAppState=mapped;}void _this.flush()["catch"](function(){var _ref3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(err){return _regenerator["default"].wrap(function(_context3){while(1)switch(_context3.prev=_context3.next){case 0:_context3.next=1;return(0,_core.logFlushError)(err);case 1:case"end":return _context3.stop();}},_callee3);}));return function(_x3){return _ref3.apply(this,arguments);};}());var isBackgrounding=mapped==='background';var logsFlushPromise=isBackgrounding?_this._logs.flushWithTimeout(_this._resolvedLogsConfig.backgroundFlushBudgetMs):_this._logs.flush();void logsFlushPromise["catch"](function(){var _ref4=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(err){return _regenerator["default"].wrap(function(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=1;return(0,_core.logFlushError)(err);case 1:case"end":return _context4.stop();}},_callee4);}));return function(_x4){return _ref4.apply(this,arguments);};}());void _this._eventsStorage.waitForPersist();void _this._logsStorage.waitForPersist();if(state==='active'){_this.getSessionId();}});var initAfterStorage=function initAfterStorage(){var enablePersistSessionIdAcrossRestart=options===null||options===void 0?void 0:options.enablePersistSessionIdAcrossRestart;if(!enablePersistSessionIdAcrossRestart){_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionId,null);_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionLastTimestamp,null);_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionStartTimestamp,null);}_this.setupBootstrap(options);if(!_this.getPersistedProperty(_core.PostHogPersistedProperty.DeviceId)){var anonId=_this.getAnonymousId();if(anonId){_this.setPersistedProperty(_core.PostHogPersistedProperty.DeviceId,anonId);}}if(_this._setDefaultPersonProperties){_this._setDefaultPersonPropertiesForFlags(false);}_this._isInitialized=true;if(_this.isDisabled){return;}var cachedRemoteConfig=_this.getPersistedProperty(_core.PostHogPersistedProperty.RemoteConfig);if(cachedRemoteConfig){_this._errorTracking.onRemoteConfig(cachedRemoteConfig.errorTracking);}_this.reloadRemoteConfigAsync().then(function(response){if(response){_this._errorTracking.onRemoteConfig(response.errorTracking);_this._handleSurveysFromRemoteConfig(response);}})["catch"](function(error){_this._logger.error('Error loading remote config:',error);})["finally"](function(){_this._notifySurveysReady();});if((options===null||options===void 0?void 0:options.captureAppLifecycleEvents)!==false){void _this.captureAppLifecycleEvents();}void _this.persistAppVersion();void _this.startSessionReplay(options,cachedRemoteConfig!==null&&cachedRemoteConfig!==void 0?cachedRemoteConfig:undefined);_this.onFeatureFlags(function(){var _a;if(_this._isEnableSessionReplay()||((_a=_this._manualRecordingStartRequest)===null||_a===void 0?void 0:_a.pending)){void _this._evaluateAndStartSessionReplay();}});if((options===null||options===void 0?void 0:options.addTracingHeaders)&&options.addTracingHeaders.length>0){(0,_core.patchFetchForTracingHeaders)(_this,options.addTracingHeaders);}};if(storagePromise){_this._initPromise=storagePromise.then(initAfterStorage);}else{_this._initPromise=Promise.resolve();initAfterStorage();}return _this;}(0,_inherits2["default"])(PostHog,_PostHogCore);return(0,_createClass2["default"])(PostHog,[{key:"ready",value:(function(){var _ready=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee5(){return _regenerator["default"].wrap(function(_context5){while(1)switch(_context5.prev=_context5.next){case 0:_context5.next=1;return this._initPromise;case 1:case"end":return _context5.stop();}},_callee5,this);}));function ready(){return _ready.apply(this,arguments);}return ready;}())},{key:"onRemoteConfig",value:function onRemoteConfig(response){this._errorTracking.onRemoteConfig(response.errorTracking);}},{key:"_storageForKey",value:function _storageForKey(key){return key===_core.PostHogPersistedProperty.LogsQueue?this._logsStorage:this._eventsStorage;}},{key:"getPersistedProperty",value:function getPersistedProperty(key){return this._storageForKey(key).getItem(key);}},{key:"setPersistedProperty",value:function setPersistedProperty(key,value){var storage=this._storageForKey(key);if(key===_core.PostHogPersistedProperty.SurveysInProgress&&value===null){var otherProjects=(0,_surveyProgress.getOtherProjectSurveyProgress)(this);otherProjects.length?storage.setItem(key,otherProjects):storage.removeItem(key);this._events.emit('surveysReset',undefined);}else{value!==null?storage.setItem(key,value):storage.removeItem(key);}if(key===_core.PostHogPersistedProperty.PersonProperties){this._events.emit('personProperties',value);}}},{key:"flushStorage",value:(function(){var _flushStorage=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee6(){return _regenerator["default"].wrap(function(_context6){while(1)switch(_context6.prev=_context6.next){case 0:_context6.next=1;return this._eventsStorage.waitForPersist();case 1:case"end":return _context6.stop();}},_callee6,this);}));function flushStorage(){return _flushStorage.apply(this,arguments);}return flushStorage;}())},{key:"_shutdown",value:(function(){var _shutdown2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee7(){var shutdownTimeoutMs,start,remainingMs,logsBudgetMs,_remainingMs,drain,_args7=arguments;return _regenerator["default"].wrap(function(_context7){while(1)switch(_context7.prev=_context7.next){case 0:shutdownTimeoutMs=_args7.length>0&&_args7[0]!==undefined?_args7[0]:30000;this._cancelManualRecordingStart();start=Date.now();_context7.prev=1;remainingMs=Math.max(0,shutdownTimeoutMs-(Date.now()-start));logsBudgetMs=Math.min(remainingMs,this._resolvedLogsConfig.terminationFlushBudgetMs);_context7.next=2;return Promise.all([this._logs.shutdown(logsBudgetMs),_superPropGet(PostHog,"_shutdown",this,3)([remainingMs])]);case 2:_context7.prev=2;this._errorTracking.shutdown();_remainingMs=Math.max(0,shutdownTimeoutMs-(Date.now()-start));drain=Promise.all([this._eventsStorage.waitForPersist(),this._logsStorage.waitForPersist()]);_context7.next=3;return(0,_core.raceWithTimeout)(drain,_remainingMs);case 3:return _context7.finish(2);case 4:case"end":return _context7.stop();}},_callee7,this,[[1,,2,4]]);}));function _shutdown(){return _shutdown2.apply(this,arguments);}return _shutdown;}())},{key:"fetch",value:function(_fetch){function fetch(_x,_x2){return _fetch.apply(this,arguments);}fetch.toString=function(){return _fetch.toString();};return fetch;}(function(url,options){return fetch(url,options);})},{key:"getLibraryId",value:function getLibraryId(){return'posthog-react-native';}},{key:"getLibraryVersion",value:function getLibraryVersion(){return _version.version;}},{key:"getCustomUserAgent",value:function getCustomUserAgent(){if(_reactNative.Platform.OS==='web'){return'';}return"".concat(this.getLibraryId(),"/").concat(this.getLibraryVersion());}},{key:"getCustomHeaders",value:function getCustomHeaders(){return _objectSpread(_objectSpread({},_superPropGet(PostHog,"getCustomHeaders",this,3)([])),this._requestHeaders);}},{key:"getCommonEventProperties",value:function getCommonEventProperties(){var _Dimensions$get=_reactNative.Dimensions.get(_reactNative.Platform.OS==='ios'?'window':'screen'),width=_Dimensions$get.width,height=_Dimensions$get.height;return _objectSpread(_objectSpread(_objectSpread({},_superPropGet(PostHog,"getCommonEventProperties",this,3)([])),this._appProperties),{},{$screen_height:height,$screen_width:width});}},{key:"getSurveyDisplayLanguageOverride",value:function getSurveyDisplayLanguageOverride(){return this._overrideDisplayLanguage;}},{key:"register",value:function register(properties){return _superPropGet(PostHog,"register",this,3)([properties]);}},{key:"unregister",value:function unregister(property){return _superPropGet(PostHog,"unregister",this,3)([property]);}},{key:"reset",value:function reset(propertiesToKeep){var _this2=this;var effectivePropertiesToKeep=propertiesToKeep!==null&&propertiesToKeep!==void 0?propertiesToKeep:[_core.PostHogPersistedProperty.InstalledAppBuild,_core.PostHogPersistedProperty.InstalledAppVersion,_core.PostHogPersistedProperty.DeviceId];this._cancelManualRecordingStart();_superPropGet(PostHog,"reset",this,3)([[_core.PostHogPersistedProperty.RemoteConfig,_core.PostHogPersistedProperty.SessionReplay,_core.PostHogPersistedProperty.Surveys,_core.PostHogPersistedProperty.PushRegistered].concat((0,_toConsumableArray2["default"])(effectivePropertiesToKeep))]);if(this._setDefaultPersonProperties){this._setDefaultPersonPropertiesForFlags(false);}if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.reset){void this._enqueueNative('reset',function(plugin){var _a;return(_a=plugin.reset)===null||_a===void 0?void 0:_a.call(plugin,String(_this2.getDistinctId()),String(_this2.getAnonymousId()));},this.getPersistedProperty(_core.PostHogPersistedProperty.PushRegistered)===true);}this._propagateNativeOptOut();void this._eventsStorage.waitForPersist();}},{key:"_setDefaultPersonPropertiesForFlags",value:function _setDefaultPersonPropertiesForFlags(){var _this3=this;var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var defaultProps={};var relevantKeys=['$app_version','$app_build','$app_namespace','$os_name','$os_version','$device_type'];relevantKeys.forEach(function(key){var value=_this3._appProperties[key];if(value!==null&&value!==undefined){defaultProps[key]=value;}});var commonProps=this.getCommonEventProperties();if(commonProps.$lib){defaultProps.$lib=commonProps.$lib;}if(commonProps.$lib_version){defaultProps.$lib_version=commonProps.$lib_version;}if(Object.keys(defaultProps).length>0){this.setPersonPropertiesForFlags(defaultProps,reloadFeatureFlags);}}},{key:"flush",value:function flush(){return _superPropGet(PostHog,"flush",this,3)([]);}},{key:"captureLog",value:function captureLog(options){this._logs.captureLog(options);}},{key:"flushLogs",value:function flushLogs(){return this._logs.flush();}},{key:"logger",get:function get(){var _this4=this;if(!this._captureLogger){this._captureLogger={trace:function trace(body,attributes){return _this4.captureLog({body:body,level:'trace',attributes:attributes});},debug:function debug(body,attributes){return _this4.captureLog({body:body,level:'debug',attributes:attributes});},info:function info(body,attributes){return _this4.captureLog({body:body,level:'info',attributes:attributes});},warn:function warn(body,attributes){return _this4.captureLog({body:body,level:'warn',attributes:attributes});},error:function error(body,attributes){return _this4.captureLog({body:body,level:'error',attributes:attributes});},fatal:function fatal(body,attributes){return _this4.captureLog({body:body,level:'fatal',attributes:attributes});}};}return this._captureLogger;}},{key:"optIn",value:function optIn(){var result=_superPropGet(PostHog,"optIn",this,3)([]);void this._eventsStorage.waitForPersist();this._propagateNativeOptOut();return result;}},{key:"optOut",value:function optOut(){var _this5=this;this._cancelManualRecordingStart();var coreOptOut=_superPropGet(PostHog,"optOut",this,3)([]);var persistOptOut=function persistOptOut(){_this5.setPersistedProperty(_core.PostHogPersistedProperty.SurveysInProgress,null);return _this5._eventsStorage.waitForPersist();};var result=Promise.all([coreOptOut,this._isInitialized?persistOptOut():this._initPromise.then(persistOptOut)]).then(function(){return undefined;});if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.unregisterPushNotificationToken){void this.unregisterPushNotificationToken();}this._propagateNativeOptOut();return result;}},{key:"_propagateNativeOptOut",value:function _propagateNativeOptOut(){var _this6=this;if(!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.setOptOut)){return;}void this._enqueueNative('setOptOut',function(plugin){var _a;return(_a=plugin.setOptOut)===null||_a===void 0?void 0:_a.call(plugin,_this6.optedOut);});if(this._isPushNativeEnabled(this._sessionReplayOptions)){void this._ensureNativeInitialized();}}},{key:"isFeatureEnabled",value:function isFeatureEnabled(key,options){return _superPropGet(PostHog,"isFeatureEnabled",this,3)([key,options]);}},{key:"getFeatureFlag",value:function getFeatureFlag(key,options){return _superPropGet(PostHog,"getFeatureFlag",this,3)([key,options]);}},{key:"getFeatureFlagPayload",value:function getFeatureFlagPayload(key){return _superPropGet(PostHog,"getFeatureFlagPayload",this,3)([key]);}},{key:"reloadFeatureFlags",value:function reloadFeatureFlags(){_superPropGet(PostHog,"reloadFeatureFlags",this,3)([]);}},{key:"reloadFeatureFlagsAsync",value:function reloadFeatureFlagsAsync(){return _superPropGet(PostHog,"reloadFeatureFlagsAsync",this,3)([]);}},{key:"updateFlags",value:function updateFlags(flags,payloads,options){_superPropGet(PostHog,"updateFlags",this,3)([flags,payloads,options]);}},{key:"group",value:function group(groupType,groupKey,properties){_superPropGet(PostHog,"group",this,3)([groupType,groupKey,properties]);if(properties&&Object.keys(properties).length>0){var propsToCache={};Object.keys(properties).forEach(function(key){var value=properties[key];if(value!==null&&value!==undefined){propsToCache[key]=value;}});if(Object.keys(propsToCache).length>0){this.setGroupPropertiesForFlags((0,_defineProperty2["default"])({},groupType,propsToCache));}}}},{key:"alias",value:function alias(_alias){_superPropGet(PostHog,"alias",this,3)([_alias]);}},{key:"getDistinctId",value:function getDistinctId(){return _superPropGet(PostHog,"getDistinctId",this,3)([]);}},{key:"getDeviceId",value:function getDeviceId(){var deviceId=this.getPersistedProperty(_core.PostHogPersistedProperty.DeviceId);if(!deviceId){var anonId=this.getAnonymousId();if(anonId){this.setPersistedProperty(_core.PostHogPersistedProperty.DeviceId,anonId);return anonId;}return'';}return deviceId;}},{key:"setPersonPropertiesForFlags",value:function setPersonPropertiesForFlags(properties){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"setPersonPropertiesForFlags",this,3)([properties,reloadFeatureFlags]);}},{key:"resetPersonPropertiesForFlags",value:function resetPersonPropertiesForFlags(){var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;_superPropGet(PostHog,"resetPersonPropertiesForFlags",this,3)([]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"setGroupPropertiesForFlags",value:function setGroupPropertiesForFlags(properties){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"setGroupPropertiesForFlags",this,3)([properties]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"resetGroupPropertiesForFlags",value:function resetGroupPropertiesForFlags(){var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;_superPropGet(PostHog,"resetGroupPropertiesForFlags",this,3)([]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"screen",value:(function(){var _screen=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee8(name,properties,options){return _regenerator["default"].wrap(function(_context8){while(1)switch(_context8.prev=_context8.next){case 0:if(this._isInitialized){_context8.next=1;break;}_context8.next=1;return this._initPromise;case 1:this.registerForSession({$screen_name:name});return _context8.abrupt("return",this.capture('$screen',_objectSpread(_objectSpread({},properties),{},{$screen_name:name}),options));case 2:case"end":return _context8.stop();}},_callee8,this);}));function screen(_x5,_x6,_x7){return _screen.apply(this,arguments);}return screen;}())},{key:"_isEnableSessionReplay",value:function _isEnableSessionReplay(){var _a;return!this.isDisabled&&!(0,_utils.isMacOS)()&&((_a=this._enableSessionReplay)!==null&&_a!==void 0?_a:false);}},{key:"_resetSessionId",value:function _resetSessionId(reactNativeSessionReplay,sessionId){if(reactNativeSessionReplay){reactNativeSessionReplay.endSession();reactNativeSessionReplay.startSession(sessionId);}}},{key:"getSessionId",value:function getSessionId(){var sessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);if(!this._isEnableSessionReplay()&&!this._isNativePluginInitialized()){return sessionId;}if(sessionId.length>0&&this._currentSessionId&&sessionId!==this._currentSessionId){if(_OptionalPlugin.OptionalReactNativePlugin){try{this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));this._logger.info("sessionId rotated from ".concat(this._currentSessionId," to ").concat(sessionId,"."));}catch(e){this._logger.error("Failed to rotate sessionId: ".concat(e,"."));}}this._currentSessionId=sessionId;if(this._sessionReplayEventTriggers.length>0){void this._evaluateAndStartSessionReplay();}}else{this._logger.info("sessionId not rotated, sessionId ".concat(sessionId," and currentSessionId ").concat(this._currentSessionId,"."));}return sessionId;}},{key:"resetSessionId",value:function resetSessionId(){_superPropGet(PostHog,"resetSessionId",this,3)([]);if((this._isEnableSessionReplay()||this._isNativePluginInitialized())&&_OptionalPlugin.OptionalReactNativePlugin){try{_OptionalPlugin.OptionalReactNativePlugin.endSession();this._logger.info("Native PostHog session ended.");}catch(e){this._logger.error("Native PostHog session failed to end: ".concat(e,"."));}}}},{key:"startSessionRecording",value:(function(){var _startSessionRecording2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee0(){var _this7=this;var resumeCurrent,request,_args0=arguments;return _regenerator["default"].wrap(function(_context0){while(1)switch(_context0.prev=_context0.next){case 0:resumeCurrent=_args0.length>0&&_args0[0]!==undefined?_args0[0]:true;this._cancelManualRecordingStart();request={pending:false,retryCount:0};this._manualRecordingStartRequest=request;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee9(){return _regenerator["default"].wrap(function(_context9){while(1)switch(_context9.prev=_context9.next){case 0:_context9.next=1;return _this7._attemptManualRecordingStart(request,resumeCurrent);case 1:case"end":return _context9.stop();}},_callee9);})));_context0.next=1;return this._sessionReplayEvalChain;case 1:case"end":return _context0.stop();}},_callee0,this);}));function startSessionRecording(){return _startSessionRecording2.apply(this,arguments);}return startSessionRecording;}())},{key:"_cancelManualRecordingStart",value:function _cancelManualRecordingStart(){var _a;clearTimeout((_a=this._manualRecordingStartRequest)===null||_a===void 0?void 0:_a.timer);this._manualRecordingStartRequest=undefined;}},{key:"_attemptManualRecordingStart",value:function(){var _attemptManualRecordingStart2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee1(request,resumeCurrent){var started;return _regenerator["default"].wrap(function(_context1){while(1)switch(_context1.prev=_context1.next){case 0:if(!(this._manualRecordingStartRequest!==request)){_context1.next=1;break;}return _context1.abrupt("return",false);case 1:if(!(this.isDisabled||this.optedOut)){_context1.next=2;break;}this._cancelManualRecordingStart();return _context1.abrupt("return",false);case 2:_context1.next=3;return this._startSessionRecording(resumeCurrent);case 3:started=_context1.sent;if(!(this._manualRecordingStartRequest!==request)){_context1.next=5;break;}if(!started){_context1.next=4;break;}_context1.next=4;return this._stopSessionRecording();case 4:return _context1.abrupt("return",false);case 5:if(started){this._cancelManualRecordingStart();}else{request.pending=true;this._scheduleManualRecordingStartRetry(request);}return _context1.abrupt("return",started);case 6:case"end":return _context1.stop();}},_callee1,this);}));function _attemptManualRecordingStart(_x8,_x9){return _attemptManualRecordingStart2.apply(this,arguments);}return _attemptManualRecordingStart;}()},{key:"_scheduleManualRecordingStartRetry",value:function _scheduleManualRecordingStartRetry(request){var _this8=this;var delay=MANUAL_RECORDING_START_RETRY_DELAYS_MS[request.retryCount];if(request.timer!==undefined||delay===undefined||!this._sessionReplayNativeInitialized||!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.startRecording)){return;}request.retryCount++;request.timer=(0,_core.safeSetTimeout)(function(){request.timer=undefined;_this8._sessionReplayEvalChain=_this8._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee10(){return _regenerator["default"].wrap(function(_context10){while(1)switch(_context10.prev=_context10.next){case 0:_context10.next=1;return _this8._attemptManualRecordingStart(request,true);case 1:case"end":return _context10.stop();}},_callee10);})));},delay);}},{key:"_startSessionRecording",value:function(){var _startSessionRecording3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee11(resumeCurrent){var _this9=this;var initialized,newSessionId,started,_t;return _regenerator["default"].wrap(function(_context11){while(1)switch(_context11.prev=_context11.next){case 0:_context11.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context11.next=2;break;}return _context11.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context11.next=3;break;}return _context11.abrupt("return",false);case 3:_context11.prev=3;if(_OptionalPlugin.OptionalReactNativePlugin.startRecording){_context11.next=4;break;}this._logger.warn('startRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');return _context11.abrupt("return",false);case 4:if(this._sessionReplayNativeInitialized){_context11.next=6;break;}this._logger.info('Native session replay SDK not initialized, initializing now...');_context11.next=5;return this.initializeNativePlugin(this._sessionReplayOptions,undefined,true);case 5:initialized=_context11.sent;if(initialized){_context11.next=6;break;}this._logger.error('Failed to initialize native session replay SDK.');return _context11.abrupt("return",false);case 6:if(!resumeCurrent){_superPropGet(PostHog,"resetSessionId",this,3)([]);newSessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(newSessionId));this._currentSessionId=newSessionId;}_context11.next=7;return _OptionalPlugin.OptionalReactNativePlugin.startRecording(resumeCurrent);case 7:_context11.next=8;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled()["catch"](function(e){_this9._logger.warn("Failed to confirm the session recording started: ".concat(e));return true;});case 8:started=_context11.sent;if(started){_context11.next=9;break;}this._logger.warn('The native SDK refused to start session recording, usually because its remote config is not loaded yet. '+'PostHog retries on the next feature flags load.');return _context11.abrupt("return",false);case 9:this._logger.info("Session recording ".concat(resumeCurrent?'resumed':'started',"."));return _context11.abrupt("return",true);case 10:_context11.prev=10;_t=_context11["catch"](3);this._logger.error("Failed to start session recording: ".concat(_t));return _context11.abrupt("return",false);case 11:case"end":return _context11.stop();}},_callee11,this,[[3,10]]);}));function _startSessionRecording(_x0){return _startSessionRecording3.apply(this,arguments);}return _startSessionRecording;}()},{key:"stopSessionRecording",value:(function(){var _stopSessionRecording2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee13(){var _this0=this;return _regenerator["default"].wrap(function(_context13){while(1)switch(_context13.prev=_context13.next){case 0:this._cancelManualRecordingStart();this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee12(){return _regenerator["default"].wrap(function(_context12){while(1)switch(_context12.prev=_context12.next){case 0:_context12.next=1;return _this0._stopSessionRecording();case 1:case"end":return _context12.stop();}},_callee12);})));_context13.next=1;return this._sessionReplayEvalChain;case 1:case"end":return _context13.stop();}},_callee13,this);}));function stopSessionRecording(){return _stopSessionRecording2.apply(this,arguments);}return stopSessionRecording;}())},{key:"_stopSessionRecording",value:function(){var _stopSessionRecording3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee14(){var _t2;return _regenerator["default"].wrap(function(_context14){while(1)switch(_context14.prev=_context14.next){case 0:_context14.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context14.next=2;break;}return _context14.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context14.next=3;break;}return _context14.abrupt("return",false);case 3:_context14.prev=3;if(_OptionalPlugin.OptionalReactNativePlugin.stopRecording){_context14.next=4;break;}this._logger.warn('stopRecording is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');return _context14.abrupt("return",false);case 4:_context14.next=5;return _OptionalPlugin.OptionalReactNativePlugin.stopRecording();case 5:this._logger.info('Session recording stopped.');return _context14.abrupt("return",true);case 6:_context14.prev=6;_t2=_context14["catch"](3);this._logger.error("Failed to stop session recording: ".concat(_t2));return _context14.abrupt("return",false);case 7:case"end":return _context14.stop();}},_callee14,this,[[3,6]]);}));function _stopSessionRecording(){return _stopSessionRecording3.apply(this,arguments);}return _stopSessionRecording;}()},{key:"isSessionReplayActive",value:(function(){var _isSessionReplayActive=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee15(){var _t3;return _regenerator["default"].wrap(function(_context15){while(1)switch(_context15.prev=_context15.next){case 0:_context15.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context15.next=2;break;}return _context15.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context15.next=3;break;}return _context15.abrupt("return",false);case 3:_context15.prev=3;_context15.next=4;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled();case 4:return _context15.abrupt("return",_context15.sent);case 5:_context15.prev=5;_t3=_context15["catch"](3);this._logger.error("Failed to check session replay status: ".concat(_t3));return _context15.abrupt("return",false);case 6:case"end":return _context15.stop();}},_callee15,this,[[3,5]]);}));function isSessionReplayActive(){return _isSessionReplayActive.apply(this,arguments);}return isSessionReplayActive;}())},{key:"identify",value:function identify(distinctId,properties,options){var _this1=this;var previousDistinctId=this.getDistinctId();var userProps=(properties===null||properties===void 0?void 0:properties.$set)||properties;var userPropsOnce=properties===null||properties===void 0?void 0:properties.$set_once;_superPropGet(PostHog,"identify",this,3)([distinctId,properties,options]);var propsToCache={};if(userProps&&(0,_typeof2["default"])(userProps)==='object'&&!Array.isArray(userProps)){Object.entries(userProps).forEach(function(_ref8){var _ref9=(0,_slicedToArray2["default"])(_ref8,2),key=_ref9[0],value=_ref9[1];if(value!==null&&value!==undefined){propsToCache[key]=value;}});}var propsOnceToCache={};if(userPropsOnce&&(0,_typeof2["default"])(userPropsOnce)==='object'&&!Array.isArray(userPropsOnce)){Object.entries(userPropsOnce).forEach(function(_ref0){var _ref1=(0,_slicedToArray2["default"])(_ref0,2),key=_ref1[0],value=_ref1[1];if(value!==null&&value!==undefined){propsOnceToCache[key]=value;}});}if(Object.keys(propsToCache).length>0||Object.keys(propsOnceToCache).length>0){this.setPersonPropertiesForFlags(_objectSpread({$set:propsToCache},Object.keys(propsOnceToCache).length>0?{$set_once:propsOnceToCache}:{}),false);}if(_OptionalPlugin.OptionalReactNativePlugin){void this._enqueueNative('identify',function(plugin){var nativeDistinctId=String(_this1.getDistinctId()||previousDistinctId);var anonymousId=String(_this1.getAnonymousId());var identified=plugin.identify(nativeDistinctId,anonymousId);_this1._logger.info("Native PostHog identified with distinctId ".concat(nativeDistinctId," and anonymousId ").concat(anonymousId,"."));return identified;});}void this._eventsStorage.waitForPersist();}},{key:"captureException",value:function captureException(error){var additionalProperties=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var hint=arguments.length>2?arguments[2]:undefined;var _a;try{var result=this.captureExceptionInternal(error,additionalProperties,hint);if(((_a=result===null||result===void 0?void 0:result.additionalProperties)===null||_a===void 0?void 0:_a.$exception_level)==='fatal'){void this._eventsStorage.waitForPersist();void this._logsStorage.waitForPersist();}}catch(e){this._logger.error('Error while capturing $exception:',e);}}},{key:"captureExceptionInternal",value:function captureExceptionInternal(error){var additionalProperties=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var hint=arguments.length>2?arguments[2]:undefined;var options=arguments.length>3?arguments[3]:undefined;var _a,_b;var resolvedHint=hint!==null&&hint!==void 0?hint:{mechanism:{handled:true,type:'generic'},syntheticException:new Error('Synthetic Error')};var merged=_objectSpread(_objectSpread({},(0,_exceptionContext.getExceptionContext)()),additionalProperties);var finalAdditional=this._errorTracking.attachExceptionSteps(merged);var captureOptions=_objectSpread(_objectSpread({},options||{}),{},{_originatedFromCaptureException:true});this.capture('$exception',_objectSpread(_objectSpread({},this.buildExceptionProperties(error,resolvedHint)),finalAdditional),captureOptions);var eventUuid=(_a=captureOptions.uuid)!==null&&_a!==void 0?_a:'';var timestamp=((_b=captureOptions.timestamp)!==null&&_b!==void 0?_b:new Date()).toISOString();return{eventUuid:eventUuid,timestamp:timestamp,additionalProperties:finalAdditional};}},{key:"buildExceptionProperties",value:function buildExceptionProperties(error,hint){try{var builder=this.getErrorPropertiesBuilder();var exceptionProperties=builder.buildFromUnknown(error,hint);return exceptionProperties;}catch(e){this._logger.error('Error while building exception properties:',e);return{};}}},{key:"addExceptionStep",value:function addExceptionStep(message,properties){this._errorTracking.addExceptionStep(message,properties);}},{key:"createErrorPropertiesBuilder",value:function createErrorPropertiesBuilder(){return new _core.ErrorTracking.ErrorPropertiesBuilder([new _core.ErrorTracking.PromiseRejectionEventCoercer(),new _core.ErrorTracking.ErrorCoercer(),new _core.ErrorTracking.ErrorEventCoercer(),new _core.ErrorTracking.ObjectCoercer(),new _core.ErrorTracking.StringCoercer(),new _core.ErrorTracking.PrimitiveCoercer()],_core.ErrorTracking.createStackParser((0,_utils.isHermes)()?'hermes':'web:javascript',_core.ErrorTracking.chromeStackLineParser,_core.ErrorTracking.geckoStackLineParser));}},{key:"initReactNativeNavigation",value:function initReactNativeNavigation(options){return(0,_wixNavigation.withReactNativeNavigation)(this,options);}},{key:"createPersonProfile",value:function createPersonProfile(){_superPropGet(PostHog,"createPersonProfile",this,3)([]);}},{key:"setPersonProperties",value:function setPersonProperties(userPropertiesToSet,userPropertiesToSetOnce){var reloadFeatureFlags=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;_superPropGet(PostHog,"setPersonProperties",this,3)([userPropertiesToSet,userPropertiesToSetOnce,reloadFeatureFlags]);}},{key:"unsetPersonProperties",value:function unsetPersonProperties(propertyNames){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"unsetPersonProperties",this,3)([propertyNames,reloadFeatureFlags]);}},{key:"getSurveys",value:function(){var _getSurveys=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee16(){var surveys;return _regenerator["default"].wrap(function(_context16){while(1)switch(_context16.prev=_context16.next){case 0:if(!(this._disableSurveys===true)){_context16.next=1;break;}this._logger.info('Loading surveys is disabled.');this._cacheSurveys(null,'disabled in config');return _context16.abrupt("return",[]);case 1:surveys=this.getPersistedProperty(_core.PostHogPersistedProperty.Surveys);if(!(surveys&&surveys.length>0)){_context16.next=2;break;}this._logger.info('Surveys fetched from storage: ',JSON.stringify(surveys));return _context16.abrupt("return",surveys);case 2:this._logger.info('No surveys found in storage');return _context16.abrupt("return",[]);case 3:case"end":return _context16.stop();}},_callee16,this);}));function getSurveys(){return _getSurveys.apply(this,arguments);}return getSurveys;}()},{key:"_onSurveysReady",value:function _onSurveysReady(){var _this10=this;if(this._surveysReady){return Promise.resolve();}if(!this._surveysReadyPromise){this._surveysReadyPromise=new Promise(function(resolve){_this10._surveysReadyResolve=resolve;});}return this._surveysReadyPromise;}},{key:"_cacheSurveys",value:function _cacheSurveys(surveys,source){this.setPersistedProperty(_core.PostHogPersistedProperty.Surveys,surveys);if(surveys&&surveys.length>0){this._logger.info("Surveys cached from ".concat(source,":"),JSON.stringify(surveys));}else if(surveys===null){this._logger.info("Surveys cleared (".concat(source,")"));}else{this._logger.info("No surveys to cache from ".concat(source,")"));}}},{key:"_notifySurveysReady",value:function _notifySurveysReady(){this._surveysReady=true;if(this._surveysReadyResolve){this._surveysReadyResolve();this._surveysReadyResolve=null;this._surveysReadyPromise=null;}}},{key:"_handleSurveysFromRemoteConfig",value:function _handleSurveysFromRemoteConfig(response){if(this._disableSurveys===true){this._logger.info('Loading surveys skipped, disabled.');this._cacheSurveys(null,'remote config (disabled)');return;}var surveys=response.surveys;if(Array.isArray(surveys)){this._cacheSurveys(surveys,'remote config');}else{this._cacheSurveys(null,'remote config');}}},{key:"registerPushNotificationToken",value:(function(){var _registerPushNotificationToken=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee17(deviceToken,options){var _this11=this;return _regenerator["default"].wrap(function(_context17){while(1)switch(_context17.prev=_context17.next){case 0:return _context17.abrupt("return",this._callPushPlugin('registerPushNotificationToken',{allowMacOS:false,requireInit:true,noop:'token not registered'},function(plugin){var _a;var _b;_this11.setPersistedProperty(_core.PostHogPersistedProperty.PushRegistered,true);return(_a=plugin.registerPushNotificationToken)===null||_a===void 0?void 0:_a.call(plugin,deviceToken,(_b=options===null||options===void 0?void 0:options.appId)!==null&&_b!==void 0?_b:null);}));case 1:case"end":return _context17.stop();}},_callee17,this);}));function registerPushNotificationToken(_x1,_x10){return _registerPushNotificationToken.apply(this,arguments);}return registerPushNotificationToken;}())},{key:"unregisterPushNotificationToken",value:(function(){var _unregisterPushNotificationToken=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee18(){var _this12=this;return _regenerator["default"].wrap(function(_context18){while(1)switch(_context18.prev=_context18.next){case 0:return _context18.abrupt("return",this._callPushPlugin('unregisterPushNotificationToken',{allowMacOS:false,allowWhenOptedOut:true,requireInit:this.getPersistedProperty(_core.PostHogPersistedProperty.PushRegistered)===true,noop:'nothing to unregister'},function(plugin){var _a;_this12.setPersistedProperty(_core.PostHogPersistedProperty.PushRegistered,null);return(_a=plugin.unregisterPushNotificationToken)===null||_a===void 0?void 0:_a.call(plugin);}));case 1:case"end":return _context18.stop();}},_callee18,this);}));function unregisterPushNotificationToken(){return _unregisterPushNotificationToken.apply(this,arguments);}return unregisterPushNotificationToken;}())},{key:"capturePushNotificationOpened",value:(function(){var _capturePushNotificationOpened=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee19(options){var properties,_i,_arr,key;return _regenerator["default"].wrap(function(_context19){while(1)switch(_context19.prev=_context19.next){case 0:properties={};for(_i=0,_arr=['title','subtitle','body','payload','action'];_i<_arr.length;_i++){key=_arr[_i];if(options[key]!==undefined){properties[key]=options[key];}}return _context19.abrupt("return",this._callPushPlugin('capturePushNotificationOpened',{allowMacOS:true,requireInit:true,noop:'event not captured'},function(plugin){var _a;return(_a=plugin.capturePushNotificationOpened)===null||_a===void 0?void 0:_a.call(plugin,properties);}));case 1:case"end":return _context19.stop();}},_callee19,this);}));function capturePushNotificationOpened(_x11){return _capturePushNotificationOpened.apply(this,arguments);}return capturePushNotificationOpened;}())},{key:"_callPushPlugin",value:function(){var _callPushPlugin2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee20(method,behavior,invoke){var _this13=this;return _regenerator["default"].wrap(function(_context20){while(1)switch(_context20.prev=_context20.next){case 0:if(!this.isDisabled){_context20.next=1;break;}return _context20.abrupt("return");case 1:if(!(this.optedOut&&!behavior.allowWhenOptedOut)){_context20.next=2;break;}this._logger.warn("".concat(method," skipped: the user is opted out; ").concat(behavior.noop,"."));return _context20.abrupt("return");case 2:if(!((0,_utils.isWeb)()||!behavior.allowMacOS&&(0,_utils.isMacOS)())){_context20.next=3;break;}this._logger.warn("".concat(method," is not supported on ").concat((0,_utils.isWeb)()?'web':'macOS',"; ").concat(behavior.noop,"."));return _context20.abrupt("return");case 3:if(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin[method]){_context20.next=4;break;}this._logger.warn("".concat(method," requires @posthog/react-native-plugin; install or update it."));return _context20.abrupt("return");case 4:return _context20.abrupt("return",this._enqueueNative(method,function(plugin){if(_this13.optedOut&&!behavior.allowWhenOptedOut){_this13._logger.warn("".concat(method," skipped: the user is opted out; ").concat(behavior.noop,"."));return;}return invoke(plugin);},behavior.requireInit));case 5:case"end":return _context20.stop();}},_callee20,this);}));function _callPushPlugin(_x12,_x13,_x14){return _callPushPlugin2.apply(this,arguments);}return _callPushPlugin;}()},{key:"_enqueueNative",value:function _enqueueNative(label,run){var _this14=this;var requireInit=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var next=this._nativeChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee21(){return _regenerator["default"].wrap(function(_context21){while(1)switch(_context21.prev=_context21.next){case 0:if(!(_this14.isDisabled||(0,_utils.isWeb)()||!_OptionalPlugin.OptionalReactNativePlugin)){_context21.next=1;break;}return _context21.abrupt("return");case 1:_context21.next=2;return _this14._initPromise["catch"](function(){});case 2:_context21.next=3;return _this14._sessionReplayEvalChain["catch"](function(){});case 3:if(_this14._isNativePluginInitialized()){_context21.next=6;break;}if(requireInit){_context21.next=4;break;}return _context21.abrupt("return");case 4:_context21.next=5;return _this14._ensureNativeInitialized();case 5:if(_this14._isNativePluginInitialized()){_context21.next=6;break;}_this14._logger.warn("".concat(label," skipped: the native plugin is not initialized."));return _context21.abrupt("return");case 6:_context21.next=7;return(0,_core.raceWithTimeout)(Promise.resolve(run(_OptionalPlugin.OptionalReactNativePlugin)),NATIVE_CALL_TIMEOUT_MS,function(){return _this14._logger.warn("Native PostHog ".concat(label," timed out after ").concat(NATIVE_CALL_TIMEOUT_MS,"ms; continuing."));});case 7:case"end":return _context21.stop();}},_callee21);})))["catch"](function(e){return _this14._logger.warn("Native PostHog ".concat(label," failed: ").concat(e,"."));});this._nativeChain=next;return next;}},{key:"_ensureNativeInitialized",value:function _ensureNativeInitialized(){var _this15=this;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then((0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee22(){return _regenerator["default"].wrap(function(_context22){while(1)switch(_context22.prev=_context22.next){case 0:if(_this15._isNativePluginInitialized()){_context22.next=1;break;}_context22.next=1;return _this15.initializeNativePlugin(_this15._sessionReplayOptions,undefined,false,true);case 1:case"end":return _context22.stop();}},_callee22);})));return this._sessionReplayEvalChain;}},{key:"_pluginVersionAtLeast",value:function _pluginVersionAtLeast(major,minor){var version=_OptionalPlugin.OptionalReactNativePluginVersion===null||_OptionalPlugin.OptionalReactNativePluginVersion===void 0?void 0:_OptionalPlugin.OptionalReactNativePluginVersion.match(/^(\d+)\.(\d+)\.\d+(?:\+[\w.-]+)?$/);if(!version){return false;}var _ref12=[Number(version[1]),Number(version[2])],installedMajor=_ref12[0],installedMinor=_ref12[1];return installedMajor>major||installedMajor===major&&installedMinor>=minor;}},{key:"_nativeErrorAutocapture",value:function _nativeErrorAutocapture(options){var _a;var autocapture=(_a=options===null||options===void 0?void 0:options.errorTracking)===null||_a===void 0?void 0:_a.autocapture;if(this.isDisabled||(0,_typeof2["default"])(autocapture)!=='object'){return{nativeCrashes:false,androidNdkCrashes:false};}var androidNdkCrashes=_reactNative.Platform.OS==='android'&&autocapture.androidNdkCrashes===true;if(androidNdkCrashes&&!this._pluginVersionAtLeast(2,12)){if(!this._androidNdkCrashesUnsupportedWarned){this._androidNdkCrashesUnsupportedWarned=true;this._logger.warn("errorTracking.autocapture.androidNdkCrashes requires @posthog/react-native-plugin 2.12.0 or later "+"(installed: ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',"); ignoring."));}androidNdkCrashes=false;}return{nativeCrashes:autocapture.nativeCrashes===true,androidNdkCrashes:androidNdkCrashes};}},{key:"_isAutocaptureNativeErrors",value:function _isAutocaptureNativeErrors(options){var _this$_nativeErrorAut=this._nativeErrorAutocapture(options),nativeCrashes=_this$_nativeErrorAut.nativeCrashes,androidNdkCrashes=_this$_nativeErrorAut.androidNdkCrashes;return nativeCrashes||androidNdkCrashes;}},{key:"_isFatalJsCaptureNativeEnabled",value:function _isFatalJsCaptureNativeEnabled(){if(this.isDisabled||this.optedOut||(0,_utils.isWeb)()||this._persistence==='memory'){return false;}return this._errorTracking.isUncaughtExceptionAutocaptureEnabled();}},{key:"_isNativePluginInitialized",value:function _isNativePluginInitialized(){return this._sessionReplayNativeInitialized||this._nativeErrorTrackingInitialized||this._pushNativeInitialized||this._fatalJsCaptureNativeInitialized;}},{key:"_isPushNativeEnabled",value:function _isPushNativeEnabled(options){var force=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(this.isDisabled||this.optedOut||(0,_utils.isWeb)()||this._pushNativeUnsupported){return false;}return force||(options===null||options===void 0?void 0:options.capturePushNotificationSubscriptions)!==false||(options===null||options===void 0?void 0:options.capturePushNotificationOpened)!==false||!!(options===null||options===void 0?void 0:options.pushIdentityProvider);}},{key:"initializeSessionReplayNative",value:(function(){var _initializeSessionReplayNative=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee23(options,cachedRemoteConfig){return _regenerator["default"].wrap(function(_context23){while(1)switch(_context23.prev=_context23.next){case 0:return _context23.abrupt("return",this.initializeNativePlugin(options,cachedRemoteConfig,true));case 1:case"end":return _context23.stop();}},_callee23,this);}));function initializeSessionReplayNative(_x15,_x16){return _initializeSessionReplayNative.apply(this,arguments);}return initializeSessionReplayNative;}())},{key:"initializeNativePlugin",value:function(){var _initializeNativePlugin=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee24(options,cachedRemoteConfig){var enableSessionReplay,forcePush,_a,_b,_c,_d,_e,_f,_g,_h,_j,nativeErrorAutocapture,enableNativeErrorTracking,enablePush,enableFatalJsCapture,sessionId,defaultThrottleDelayMs,_ref13,_ref13$maskAllTextInp,maskAllTextInputs,_ref13$maskAllImages,maskAllImages,_ref13$maskAllSandbox,maskAllSandboxedViews,_ref13$captureTouches,captureTouches,_ref13$captureLog,localCaptureLog,_ref13$captureNetwork,localCaptureNetworkTelemetry,_ref13$verifyScreensh,verifyScreenshotMaskAlignment,screenshotScale,screenshotCompressionQuality,screenshotColorMode,_ref13$screenshotMode,screenshotModeBackgroundCapture,localSampleRate,_ref13$iOSdebouncerDe,iOSdebouncerDelayMs,_ref13$androidDebounc,androidDebouncerDelayMs,throttleDelayMs,remoteConsoleLogEnabled,remoteNetworkTimingEnabled,remoteSampleRateRaw,captureLog,captureNetworkTelemetry,localSampleRateValid,remoteSampleRateValid,sampleRate,source,sdkReplayConfig,sessionReplay,cachedSessionReplayConfig,pushOnlyInit,sdkOptions,loggableSdkOptions,wasSessionReplayEnabled,pushIdentityProviderEnabled,pluginConfig,_args24=arguments,_t4,_t5;return _regenerator["default"].wrap(function(_context24){while(1)switch(_context24.prev=_context24.next){case 0:enableSessionReplay=_args24.length>2&&_args24[2]!==undefined?_args24[2]:this._isEnableSessionReplay();forcePush=_args24.length>3&&_args24[3]!==undefined?_args24[3]:false;nativeErrorAutocapture=this._nativeErrorAutocapture(options);enableNativeErrorTracking=nativeErrorAutocapture.nativeCrashes||nativeErrorAutocapture.androidNdkCrashes;enablePush=this._isPushNativeEnabled(options,forcePush);enableFatalJsCapture=this._isFatalJsCaptureNativeEnabled();if(enableSessionReplay&&(0,_utils.isMacOS)()){if(!this._sessionReplayMacOSWarned){this._sessionReplayMacOSWarned=true;this._logger.warn('Session replay is not supported on macOS; ignoring.');}enableSessionReplay=false;}if(!(!enableSessionReplay&&!enableNativeErrorTracking&&!enablePush&&!enableFatalJsCapture)){_context24.next=1;break;}return _context24.abrupt("return",true);case 1:if(_OptionalPlugin.OptionalReactNativePlugin){_context24.next=2;break;}if(enableSessionReplay||enableNativeErrorTracking){this._logger.warn(enableSessionReplay?'Session replay enabled but not installed.':'Native error tracking enabled but not installed.');}this._pushNativeUnsupported=true;return _context24.abrupt("return",false);case 2:if(!((!enableSessionReplay||this._sessionReplayNativeInitialized)&&(!enableNativeErrorTracking||this._nativeErrorTrackingInitialized)&&(!enablePush||this._pushNativeInitialized)&&(!enableFatalJsCapture||this._fatalJsCaptureNativeInitialized))){_context24.next=3;break;}return _context24.abrupt("return",true);case 3:if(!(this._isNativePluginInitialized()&&enableSessionReplay&&!this._sessionReplayNativeInitialized)){_context24.next=5;break;}this._sessionReplayNativeInitialized=true;_context24.next=4;return(_a=_OptionalPlugin.OptionalReactNativePlugin.startRecording)===null||_a===void 0?void 0:_a.call(_OptionalPlugin.OptionalReactNativePlugin,true);case 4:return _context24.abrupt("return",true);case 5:sessionId=this.getSessionId();if(!(sessionId.length===0)){_context24.next=6;break;}this._logger.warn("Native PostHog plugin enabled but no sessionId found.");return _context24.abrupt("return",false);case 6:defaultThrottleDelayMs=1000;_ref13=(_d=options===null||options===void 0?void 0:options.sessionReplayConfig)!==null&&_d!==void 0?_d:{},_ref13$maskAllTextInp=_ref13.maskAllTextInputs,maskAllTextInputs=_ref13$maskAllTextInp===void 0?true:_ref13$maskAllTextInp,_ref13$maskAllImages=_ref13.maskAllImages,maskAllImages=_ref13$maskAllImages===void 0?true:_ref13$maskAllImages,_ref13$maskAllSandbox=_ref13.maskAllSandboxedViews,maskAllSandboxedViews=_ref13$maskAllSandbox===void 0?true:_ref13$maskAllSandbox,_ref13$captureTouches=_ref13.captureTouches,captureTouches=_ref13$captureTouches===void 0?true:_ref13$captureTouches,_ref13$captureLog=_ref13.captureLog,localCaptureLog=_ref13$captureLog===void 0?true:_ref13$captureLog,_ref13$captureNetwork=_ref13.captureNetworkTelemetry,localCaptureNetworkTelemetry=_ref13$captureNetwork===void 0?true:_ref13$captureNetwork,_ref13$verifyScreensh=_ref13.verifyScreenshotMaskAlignment,verifyScreenshotMaskAlignment=_ref13$verifyScreensh===void 0?false:_ref13$verifyScreensh,screenshotScale=_ref13.screenshotScale,screenshotCompressionQuality=_ref13.screenshotCompressionQuality,screenshotColorMode=_ref13.screenshotColorMode,_ref13$screenshotMode=_ref13.screenshotModeBackgroundCapture,screenshotModeBackgroundCapture=_ref13$screenshotMode===void 0?false:_ref13$screenshotMode,localSampleRate=_ref13.sampleRate,_ref13$iOSdebouncerDe=_ref13.iOSdebouncerDelayMs,iOSdebouncerDelayMs=_ref13$iOSdebouncerDe===void 0?defaultThrottleDelayMs:_ref13$iOSdebouncerDe,_ref13$androidDebounc=_ref13.androidDebouncerDelayMs,androidDebouncerDelayMs=_ref13$androidDebounc===void 0?defaultThrottleDelayMs:_ref13$androidDebounc;if(captureTouches===false&&!(0,_utils.isMacOS)()){if(!this._pluginVersionAtLeast(2,9)){this._logger.warn("sessionReplayConfig.captureTouches: false requires @posthog/react-native-plugin 2.9.0 or later. "+"The installed plugin (version ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',") may still record touch coordinates. ")+"Upgrade the plugin and rebuild your app before relying on this setting.");}}throttleDelayMs=(_e=(_b=options===null||options===void 0?void 0:options.sessionReplayConfig)===null||_b===void 0?void 0:_b.throttleDelayMs)!==null&&_e!==void 0?_e:defaultThrottleDelayMs;if(throttleDelayMs===defaultThrottleDelayMs&&(iOSdebouncerDelayMs!==defaultThrottleDelayMs||androidDebouncerDelayMs!==defaultThrottleDelayMs)){throttleDelayMs=Math.max(iOSdebouncerDelayMs,androidDebouncerDelayMs);}remoteConsoleLogEnabled=(0,_utils.getRemoteConfigBool)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.sessionRecording,'consoleLogRecordingEnabled',true);remoteNetworkTimingEnabled=(0,_utils.getRemoteConfigBool)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.capturePerformance,'network_timing',true);remoteSampleRateRaw=(0,_utils.getRemoteConfigNumber)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.sessionRecording,'sampleRate');captureLog=localCaptureLog&&remoteConsoleLogEnabled;captureNetworkTelemetry=localCaptureNetworkTelemetry&&remoteNetworkTimingEnabled;localSampleRateValid=localSampleRate===undefined?undefined:(0,_utils.isValidSampleRate)(localSampleRate)?localSampleRate:undefined;remoteSampleRateValid=remoteSampleRateRaw===undefined?undefined:(0,_utils.isValidSampleRate)(remoteSampleRateRaw)?remoteSampleRateRaw:undefined;sampleRate=localSampleRateValid!==null&&localSampleRateValid!==void 0?localSampleRateValid:remoteSampleRateValid;if(localCaptureLog&&!remoteConsoleLogEnabled){this._logger.info('captureLog disabled by remote config (consoleLogRecordingEnabled=false).');}if(localCaptureNetworkTelemetry&&!remoteNetworkTimingEnabled){this._logger.info('captureNetworkTelemetry disabled by remote config (capturePerformance.network_timing=false).');}if(localSampleRate!==undefined&&localSampleRateValid===undefined){this._logger.warn("Ignoring invalid sessionReplayConfig.sampleRate '".concat(localSampleRate,"'. Expected a number between 0 and 1."));}if(remoteSampleRateRaw!==undefined&&remoteSampleRateValid===undefined){this._logger.warn("Ignoring invalid remote config sessionRecording.sampleRate '".concat(remoteSampleRateRaw,"'. Expected a number between 0 and 1."));}if(localSampleRateValid!==undefined&&remoteSampleRateValid!==undefined){this._logger.warn("Local sessionReplayConfig.sampleRate (".concat(localSampleRateValid,") overrides the remote sampleRate ")+"(".concat(remoteSampleRateValid,"). The project setting is ignored while the local option is set. ")+"Remove sessionReplayConfig.sampleRate to follow the project setting.");}else if(typeof sampleRate==='number'){source=localSampleRateValid!==undefined?'local config':'remote config';this._logger.info("sampleRate set from ".concat(source," (").concat(sampleRate,")."));}else if(cachedRemoteConfig===undefined){this._logger.warn('Session replay starts with no sampleRate because no remote config is cached yet. '+'Any project sample rate applies from the next launch.');}sdkReplayConfig=_objectSpread(_objectSpread(_objectSpread(_objectSpread({maskAllTextInputs:maskAllTextInputs,maskAllImages:maskAllImages,maskAllSandboxedViews:maskAllSandboxedViews,captureTouches:captureTouches,captureLog:captureLog,captureNetworkTelemetry:captureNetworkTelemetry,verifyScreenshotMaskAlignment:verifyScreenshotMaskAlignment},Number.isFinite(screenshotScale)?{screenshotScale:screenshotScale}:{}),Number.isFinite(screenshotCompressionQuality)?{screenshotCompressionQuality:screenshotCompressionQuality}:{}),screenshotColorMode!==undefined?{screenshotColorMode:screenshotColorMode}:{}),{},{screenshotModeBackgroundCapture:screenshotModeBackgroundCapture,sampleRate:sampleRate,iOSdebouncerDelayMs:iOSdebouncerDelayMs,androidDebouncerDelayMs:androidDebouncerDelayMs,throttleDelayMs:throttleDelayMs});this._logger.info("Native PostHog plugin (version ".concat(_OptionalPlugin.OptionalReactNativePluginVersion!==null&&_OptionalPlugin.OptionalReactNativePluginVersion!==void 0?_OptionalPlugin.OptionalReactNativePluginVersion:'unknown',") replay config: ").concat(JSON.stringify(sdkReplayConfig)));sessionReplay=(_f=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_f!==void 0?_f:{};cachedSessionReplayConfig=(_g=sessionReplay)!==null&&_g!==void 0?_g:{};this._logger.info("Session replay session recording from flags cached config: ".concat(JSON.stringify(cachedSessionReplayConfig)));pushOnlyInit=(enablePush||enableFatalJsCapture)&&!enableSessionReplay&&!enableNativeErrorTracking;sdkOptions={apiKey:this.apiKey,host:this.host,debug:this.isDebug,distinctId:this.getDistinctId(),anonymousId:this.getAnonymousId(),sdkVersion:this.getLibraryVersion(),flushAt:this.flushAt,optOut:this.optedOut,preloadFeatureFlags:!pushOnlyInit,requestHeaders:this._requestHeaders};loggableSdkOptions=_objectSpread(_objectSpread({},sdkOptions),{},{requestHeaders:Object.keys(this._requestHeaders)});this._logger.info("Native PostHog plugin sdk options: ".concat(JSON.stringify(loggableSdkOptions)));_context24.prev=7;if(!enableSessionReplay){_context24.next=9;break;}_context24.next=8;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled()["catch"](function(){return false;});case 8:_t4=_context24.sent;_context24.next=10;break;case 9:_t4=false;case 10:wasSessionReplayEnabled=_t4;if(!_OptionalPlugin.OptionalReactNativePlugin.setup){_context24.next=13;break;}pushIdentityProviderEnabled=false;if(options===null||options===void 0?void 0:options.pushIdentityProvider){if(_OptionalPlugin.OptionalReactNativePlugin.setPushIdentityProvider){_OptionalPlugin.OptionalReactNativePlugin.setPushIdentityProvider(options.pushIdentityProvider);pushIdentityProviderEnabled=true;}else{this._logger.warn('pushIdentityProvider requires a newer @posthog/react-native-plugin; push subscriptions will be sent unauthenticated.');}}pluginConfig=_objectSpread({sessionReplay:{enabled:enableSessionReplay,sdkReplayConfig:sdkReplayConfig,decideReplayConfig:cachedSessionReplayConfig},errorTracking:{nativeAutocapture:nativeErrorAutocapture.nativeCrashes,androidNdkCrashes:nativeErrorAutocapture.androidNdkCrashes,exceptionSteps:this._errorTracking.getNativePluginExceptionStepsConfig()},push:{capturePushNotificationSubscriptions:(_h=options===null||options===void 0?void 0:options.capturePushNotificationSubscriptions)!==null&&_h!==void 0?_h:true,capturePushNotificationOpened:(_j=options===null||options===void 0?void 0:options.capturePushNotificationOpened)!==null&&_j!==void 0?_j:true,pushIdentityProviderEnabled:pushIdentityProviderEnabled}},(options===null||options===void 0?void 0:options.rageClickConfig)&&{rageClick:options.rageClickConfig});_context24.next=11;return _OptionalPlugin.OptionalReactNativePlugin.setup(String(sessionId),sdkOptions,pluginConfig);case 11:_context24.next=12;return(_c=_OptionalPlugin.OptionalReactNativePlugin.setOptOut)===null||_c===void 0?void 0:_c.call(_OptionalPlugin.OptionalReactNativePlugin,this.optedOut);case 12:if(wasSessionReplayEnabled){this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));}_context24.next=18;break;case 13:if(enableNativeErrorTracking){this._logger.warn('Native error tracking is not available. Please update @posthog/react-native-plugin or posthog-react-native-session-replay.');enableNativeErrorTracking=false;}if(enablePush){this._logger.warn('Push notifications require @posthog/react-native-plugin; the legacy session-replay plugin does not support them.');}enablePush=false;this._pushNativeUnsupported=true;if(enableSessionReplay){_context24.next=14;break;}return _context24.abrupt("return",false);case 14:_context24.next=15;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled();case 15:if(_context24.sent){_context24.next=17;break;}_context24.next=16;return _OptionalPlugin.OptionalReactNativePlugin.start(String(sessionId),sdkOptions,sdkReplayConfig,cachedSessionReplayConfig);case 16:_context24.next=18;break;case 17:this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));case 18:this._currentSessionId=sessionId;if(enableSessionReplay){this._sessionReplayNativeInitialized=true;this._logger.info("Session replay started with sessionId ".concat(sessionId,"."));}if(enableNativeErrorTracking){this._nativeErrorTrackingInitialized=true;this._errorTracking.onNativeErrorTrackingReady();this._logger.info('Native error tracking started.');}if(enablePush){this._pushNativeInitialized=true;this._logger.info('Push notification native support started.');}if(enableFatalJsCapture){this._fatalJsCaptureNativeInitialized=true;this._logger.info('Native durable capture for fatal JavaScript exceptions started.');}return _context24.abrupt("return",true);case 19:_context24.prev=19;_t5=_context24["catch"](7);this._logger.error("Native PostHog plugin failed to start: ".concat(_t5,"."));return _context24.abrupt("return",false);case 20:case"end":return _context24.stop();}},_callee24,this,[[7,19]]);}));function initializeNativePlugin(_x17,_x18){return _initializeNativePlugin.apply(this,arguments);}return initializeNativePlugin;}()},{key:"startSessionReplay",value:function(){var _startSessionReplay=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee25(options,cachedRemoteConfig){return _regenerator["default"].wrap(function(_context25){while(1)switch(_context25.prev=_context25.next){case 0:this._enableSessionReplay=options===null||options===void 0?void 0:options.enableSessionReplay;this._sessionReplayOptions=options;_context25.next=1;return this._evaluateAndStartSessionReplay(cachedRemoteConfig);case 1:case"end":return _context25.stop();}},_callee25,this);}));function startSessionReplay(_x19,_x20){return _startSessionReplay.apply(this,arguments);}return startSessionReplay;}()},{key:"_evaluateAndStartSessionReplay",value:function _evaluateAndStartSessionReplay(cachedRemoteConfig){var _this16=this;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then(function(){return _this16._evaluateAndStartSessionReplayInternal(cachedRemoteConfig);});return this._sessionReplayEvalChain;}},{key:"_evaluateAndStartSessionReplayInternal",value:function(){var _evaluateAndStartSessionReplayInternal2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee26(cachedRemoteConfig){var _a,_b,_c,_d,options,enableNativeErrorTracking,enablePush,enableFatalJsCapture,remoteConfig,request,sessionReplay,featureFlags,cachedFeatureFlags,cachedSessionReplayConfig,recordingActive,linkedFlag,value,flag,variant,_value,eventTriggers,activated,_t6;return _regenerator["default"].wrap(function(_context26){while(1)switch(_context26.prev=_context26.next){case 0:options=this._sessionReplayOptions;enableNativeErrorTracking=this._isAutocaptureNativeErrors(options);enablePush=this._isPushNativeEnabled(options);enableFatalJsCapture=this._isFatalJsCaptureNativeEnabled();remoteConfig=cachedRemoteConfig!==null&&cachedRemoteConfig!==void 0?cachedRemoteConfig:this.getPersistedProperty(_core.PostHogPersistedProperty.RemoteConfig);if(this._isEnableSessionReplay()){_context26.next=3;break;}this._logger.info('Session replay is not enabled.');this._sessionReplayEventTriggers=[];if(!(enableNativeErrorTracking||enablePush||enableFatalJsCapture)){_context26.next=1;break;}_context26.next=1;return this.initializeNativePlugin(options,remoteConfig,false);case 1:request=this._manualRecordingStartRequest;if(!(request===null||request===void 0?void 0:request.pending)){_context26.next=2;break;}_context26.next=2;return this._attemptManualRecordingStart(request,true);case 2:return _context26.abrupt("return");case 3:sessionReplay=(_a=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_a!==void 0?_a:{};featureFlags=(_b=this.getKnownFeatureFlags())!==null&&_b!==void 0?_b:{};cachedFeatureFlags=(_c=featureFlags)!==null&&_c!==void 0?_c:{};cachedSessionReplayConfig=(_d=sessionReplay)!==null&&_d!==void 0?_d:{};this._logger.info('Session replay feature flags from flags cached config:',JSON.stringify(cachedFeatureFlags));recordingActive=true;linkedFlag=cachedSessionReplayConfig['linkedFlag'];if(typeof linkedFlag==='string'){value=cachedFeatureFlags[linkedFlag];if(typeof value==='boolean'){recordingActive=value;}else if(typeof value==='string'){recordingActive=true;}else{recordingActive=false;}this._logger.info("Session replay '".concat(linkedFlag,"' linked flag value: '").concat(value,"'"));}else if(linkedFlag&&(0,_typeof2["default"])(linkedFlag)==='object'){flag=linkedFlag['flag'];variant=linkedFlag['variant'];if(flag&&variant){_value=cachedFeatureFlags[flag];recordingActive=_value===variant;this._logger.info("Session replay '".concat(flag,"' linked flag variant '").concat(variant,"' and value '").concat(_value,"'"));}else{this._logger.info("Session replay '".concat(flag,"' linked flag variant: '").concat(variant,"' does not exist/quota limited."));recordingActive=false;}}else{this._logger.info("Session replay has no cached linkedFlag.");}eventTriggers=this._parseEventTriggers(cachedSessionReplayConfig['eventTriggers']);this._sessionReplayEventTriggers=eventTriggers;if(eventTriggers.length>0){activated=this._isEventTriggerActivatedForSession(_superPropGet(PostHog,"getSessionId",this,3)([]));if(!activated){recordingActive=false;}this._logger.info("Session replay event triggers configured (".concat(eventTriggers.length,"); activated: ").concat(activated,"."));}if(!recordingActive){_context26.next=9;break;}if(!(this._sessionReplayRecordingActive===true)){_context26.next=4;break;}return _context26.abrupt("return");case 4:if(!this._sessionReplayNativeInitialized){_context26.next=6;break;}_context26.next=5;return this._startSessionRecording(true);case 5:_t6=_context26.sent;_context26.next=8;break;case 6:_context26.next=7;return this.initializeNativePlugin(options,remoteConfig,true);case 7:_t6=_context26.sent;case 8:this._sessionReplayRecordingActive=_t6;_context26.next=13;break;case 9:this._logger.info('Session replay disabled.');if(!(this._sessionReplayRecordingActive===true)){_context26.next=11;break;}_context26.next=10;return this._stopSessionRecording();case 10:this._sessionReplayRecordingActive=!_context26.sent;_context26.next=12;break;case 11:this._sessionReplayRecordingActive=false;case 12:if(!(enableNativeErrorTracking||enablePush)){_context26.next=13;break;}_context26.next=13;return this.initializeNativePlugin(options,remoteConfig,false);case 13:case"end":return _context26.stop();}},_callee26,this);}));function _evaluateAndStartSessionReplayInternal(_x21){return _evaluateAndStartSessionReplayInternal2.apply(this,arguments);}return _evaluateAndStartSessionReplayInternal;}()},{key:"processBeforeEnqueue",value:function processBeforeEnqueue(message){var observation=this._fatalCaptureObservation;var isObservedFatal=observation!==undefined&&message.uuid===observation.eventUuid&&message.event==='$exception';var processed=_superPropGet(PostHog,"processBeforeEnqueue",this,3)([message]);var suppress=false;if(isObservedFatal&&processed&&observation){try{observation.nativeCapture=observation.prepareNativeCapture(processed);}catch(e){this._logger.warn("Fatal exception payload could not be prepared for native capture: ".concat(e));observation.nativeCapture=undefined;}suppress=observation.nativeCapture!==undefined;observation.queued=!suppress;}try{this._maybeActivateEventTrigger(processed===null||processed===void 0?void 0:processed['event']);}catch(e){this._logger.error("Session replay event trigger check failed: ".concat(e,"."));}return suppress?null:processed;}},{key:"_captureFatalAndChooseOwner",value:function _captureFatalAndChooseOwner(eventUuid,prepareNativeCapture,capture){var observation={eventUuid:eventUuid,prepareNativeCapture:prepareNativeCapture,queued:false};var previousObservation=this._fatalCaptureObservation;this._fatalCaptureObservation=observation;try{capture();}finally{this._fatalCaptureObservation=previousObservation;}return{queued:observation.queued,nativeCapture:observation.nativeCapture};}},{key:"_maybeActivateEventTrigger",value:function _maybeActivateEventTrigger(eventName){if(this._sessionReplayEventTriggers.length===0||typeof eventName!=='string'){return;}if(!this._sessionReplayEventTriggers.includes(eventName)){return;}var sessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);if(!sessionId){return;}if(this._isEventTriggerActivatedForSession(sessionId)&&this._sessionReplayRecordingActive===true){return;}if(!this._isEventTriggerActivatedForSession(sessionId)){this.setPersistedProperty(_core.PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession,sessionId);this._logger.info("Session replay event trigger '".concat(eventName,"' activated for session ").concat(sessionId,"."));}void this._evaluateAndStartSessionReplay();}},{key:"_parseEventTriggers",value:function _parseEventTriggers(value){if(!Array.isArray(value)){return[];}return value.filter(function(entry){return typeof entry==='string';});}},{key:"_isEventTriggerActivatedForSession",value:function _isEventTriggerActivatedForSession(sessionId){return this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession)===sessionId;}},{key:"captureAppLifecycleEvents",value:function(){var _captureAppLifecycleEvents=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee27(){var _this17=this;var _a,appBuild,appVersion,isMemoryPersistence,properties,prevAppBuild,prevAppVersion,initialUrl,_t7,_t8,_t9;return _regenerator["default"].wrap(function(_context27){while(1)switch(_context27.prev=_context27.next){case 0:appBuild=this._appProperties.$app_build;appVersion=this._appProperties.$app_version;isMemoryPersistence=this._persistence==='memory';properties={};if(!isMemoryPersistence){prevAppBuild=this.getPersistedProperty(_core.PostHogPersistedProperty.InstalledAppBuild);prevAppVersion=this.getPersistedProperty(_core.PostHogPersistedProperty.InstalledAppVersion);if(!appBuild||!appVersion){this._logger.warn('PostHog could not track installation/update/open, as the build and version were not set. '+'This can happen if some dependencies are not installed correctly, or if you have provided'+'customAppProperties but not included $app_build or $app_version.');}if(appBuild){if(!prevAppBuild){this.capture('Application Installed',properties);}else if(prevAppBuild!==appBuild){this.capture('Application Updated',_objectSpread(_objectSpread(_objectSpread({},(0,_core.maybeAdd)('previous_version',prevAppVersion)),(0,_core.maybeAdd)('previous_build',prevAppBuild)),properties));}}}else{this._logger.warn('PostHog was initialised with persistence set to "memory", capturing native app events (Application Installed and Application Updated) is not supported.');}_context27.next=1;return _reactNative.Linking.getInitialURL();case 1:_t8=_a=_context27.sent;_t7=_t8!==null;if(!_t7){_context27.next=2;break;}_t7=_a!==void 0;case 2:if(!_t7){_context27.next=3;break;}_t9=_a;_context27.next=4;break;case 3:_t9=undefined;case 4:initialUrl=_t9;this.capture('Application Opened',_objectSpread(_objectSpread({},properties),(0,_core.maybeAdd)('url',initialUrl)));_reactNative.AppState.addEventListener('change',function(state){if(state==='active'){_this17.capture('Application Became Active');}else if(state==='background'){_this17.capture('Application Backgrounded');}});case 5:case"end":return _context27.stop();}},_callee27,this);}));function captureAppLifecycleEvents(){return _captureAppLifecycleEvents.apply(this,arguments);}return captureAppLifecycleEvents;}()},{key:"persistAppVersion",value:function(){var _persistAppVersion=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee28(){var appBuild,appVersion;return _regenerator["default"].wrap(function(_context28){while(1)switch(_context28.prev=_context28.next){case 0:appBuild=this._appProperties.$app_build;appVersion=this._appProperties.$app_version;this.setPersistedProperty(_core.PostHogPersistedProperty.InstalledAppBuild,appBuild);this.setPersistedProperty(_core.PostHogPersistedProperty.InstalledAppVersion,appVersion);case 1:case"end":return _context28.stop();}},_callee28,this);}));function persistAppVersion(){return _persistAppVersion.apply(this,arguments);}return persistAppVersion;}()}]);}(_core.PostHogCore);
2
2
  //# sourceMappingURL=posthog-rn.js.map