posthog-react-native 4.82.0 → 4.84.0

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.
@@ -16,6 +16,12 @@ export interface PostHogProviderProps {
16
16
  * Your PostHog project token, which starts with `phc_`. Find it in your project settings:
17
17
  * https://us.posthog.com/settings/project-details#variables
18
18
  */
19
+ projectToken?: string;
20
+ /**
21
+ * Your PostHog project token. Ignored when `projectToken` is set.
22
+ *
23
+ * @deprecated Use `projectToken` instead. This will be removed in the next major version.
24
+ */
19
25
  apiKey?: string;
20
26
  /** An existing PostHog client instance */
21
27
  client?: PostHog;
@@ -57,7 +63,7 @@ export interface PostHogProviderProps {
57
63
  *
58
64
  * export function MyApp() {
59
65
  * return (
60
- * <PostHogProvider apiKey="<ph_project_api_key>" options={{
66
+ * <PostHogProvider projectToken="<ph_project_token>" options={{
61
67
  * host: '<ph_client_api_host>',
62
68
  * }}>
63
69
  * <MyComponent />
@@ -83,7 +89,7 @@ export interface PostHogProviderProps {
83
89
  * // Using with existing client
84
90
  * import { PostHog } from 'posthog-react-native'
85
91
  *
86
- * const posthog = new PostHog('<ph_project_api_key>', {
92
+ * const posthog = new PostHog('<ph_project_token>', {
87
93
  * host: '<ph_client_api_host>'
88
94
  * })
89
95
  *
@@ -100,4 +106,4 @@ export interface PostHogProviderProps {
100
106
  *
101
107
  * @param props - The PostHogProvider props
102
108
  */
103
- export declare const PostHogProvider: ({ children, client, options, apiKey, autocapture, style, debug, }: PostHogProviderProps) => JSX.Element | null;
109
+ export declare const PostHogProvider: ({ children, client, options, projectToken, apiKey, autocapture, style, debug, }: PostHogProviderProps) => JSX.Element | null;
@@ -1,2 +1,2 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports.PostHogProvider=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _react=_interopRequireWildcard(require("react"));var _reactNative=require("react-native");var _posthogRn=require("./posthog-rn");var _autocapture=require("./autocapture");var _useNavigationTracker=require("./hooks/useNavigationTracker");var _PostHogContext=require("./PostHogContext");var _utils=require("./utils");var _jsxRuntime=require("react/jsx-runtime");var _this=void 0,_jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/PostHogProvider.js";function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap(),n=new WeakMap();return(_interopRequireWildcard=function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,"default":e};if(null===e||"object"!=_typeof(e)&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f);}for(var _t2 in e)"default"!==_t2&&{}.hasOwnProperty.call(e,_t2)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,_t2))&&(i.get||i.set)?o(f,_t2,i):f[_t2]=e[_t2]);return f;})(e,t);}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;}var webClickListeners=new WeakMap();function PostHogNavigationHook(_ref){var options=_ref.options,client=_ref.client;(0,_useNavigationTracker.useNavigationTracker)(options===null||options===void 0?void 0:options.navigation,options===null||options===void 0?void 0:options.navigationRef,client);return null;}var PostHogProvider=exports.PostHogProvider=function PostHogProvider(_ref2){var children=_ref2.children,client=_ref2.client,options=_ref2.options,apiKey=_ref2.apiKey,autocapture=_ref2.autocapture,style=_ref2.style,_ref2$debug=_ref2.debug,debug=_ref2$debug===void 0?false:_ref2$debug;var _a;var captureAll=autocapture===true;var captureNone=autocapture===false;var posthog=(0,_react.useMemo)(function(){if(client&&apiKey){console.warn('You have provided both a client and an apiKey to PostHogProvider. The apiKey will be ignored in favour of the client.');}if(client){return client;}var parsedOptions=_objectSpread(_objectSpread({},options),{},{captureAppLifecycleEvents:(options===null||options===void 0?void 0:options.captureAppLifecycleEvents)!==undefined?options.captureAppLifecycleEvents:!captureNone});return new _posthogRn.PostHog(apiKey!==null&&apiKey!==void 0?apiKey:'',parsedOptions);},[client,apiKey]);var autocaptureOptions=(0,_react.useMemo)(function(){return autocapture&&typeof autocapture!=='boolean'?autocapture:{};},[autocapture]);var captureTouches=!captureNone&&posthog&&(captureAll||(autocaptureOptions===null||autocaptureOptions===void 0?void 0:autocaptureOptions.captureTouches));var captureScreens=!captureNone&&posthog&&(captureAll||((_a=autocaptureOptions===null||autocaptureOptions===void 0?void 0:autocaptureOptions.captureScreens)!==null&&_a!==void 0?_a:true));var phLabelProp=(autocaptureOptions===null||autocaptureOptions===void 0?void 0:autocaptureOptions.customLabelProp)||_autocapture.defaultPostHogLabelProp;(0,_react.useEffect)(function(){posthog.debug(debug);},[debug,posthog]);var onTouch=(0,_react.useCallback)(function(type,e){if(!captureTouches){return;}if(type==='end'){(0,_autocapture.autocaptureFromTouchEvent)(e,posthog,autocaptureOptions);}},[captureTouches,posthog,autocaptureOptions]);var hostRef=(0,_react.useRef)(null);var optionsRef=(0,_react.useRef)(autocaptureOptions);(0,_react.useEffect)(function(){optionsRef.current=autocaptureOptions;},[autocaptureOptions]);(0,_react.useEffect)(function(){var doc=globalThis===null||globalThis===void 0?void 0:globalThis.document;if(!(0,_utils.isWeb)()||!captureTouches||!(doc===null||doc===void 0?void 0:doc.addEventListener)){return;}var ownerNode=hostRef.current;if(!ownerNode){return;}var existing=webClickListeners.get(posthog);if(existing){existing.owners.set(ownerNode,optionsRef);}else{var owners=new Map([[ownerNode,optionsRef]]);var handler=function handler(e){var _a;var owner=(0,_autocapture.findOwningNode)(e,owners);if(!owner){return;}var options=(_a=owners.get(owner))===null||_a===void 0?void 0:_a.current;if(!options){return;}(0,_autocapture.autocaptureFromTouchEvent)({target:e.target,nativeEvent:e},posthog,options,'click');};doc.addEventListener('click',handler,true);webClickListeners.set(posthog,{owners:owners,remove:function remove(){return doc.removeEventListener('click',handler,true);}});}return function(){var entry=webClickListeners.get(posthog);if(!entry){return;}entry.owners["delete"](ownerNode);if(entry.owners.size===0){entry.remove();webClickListeners["delete"](posthog);}};},[captureTouches,posthog]);var captureProps=(0,_utils.isWeb)()?{}:{onTouchEndCapture:captureTouches?function(e){return onTouch('end',e);}:undefined};return(0,_jsxRuntime.jsx)(_reactNative.View,_objectSpread(_objectSpread(_objectSpread({ref:hostRef},(0,_defineProperty2["default"])({},phLabelProp,'PostHogProvider')),{},{style:style||{flex:1}},captureProps),{},{children:(0,_jsxRuntime.jsxs)(_PostHogContext.PostHogContext.Provider,{value:{client:posthog},children:[captureScreens&&(0,_jsxRuntime.jsx)(PostHogNavigationHook,{options:autocaptureOptions,client:posthog}),children]})}));};
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports.PostHogProvider=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _react=_interopRequireWildcard(require("react"));var _reactNative=require("react-native");var _posthogRn=require("./posthog-rn");var _autocapture=require("./autocapture");var _useNavigationTracker=require("./hooks/useNavigationTracker");var _PostHogContext=require("./PostHogContext");var _utils=require("./utils");var _jsxRuntime=require("react/jsx-runtime");var _this=void 0,_jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/PostHogProvider.js";function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap(),n=new WeakMap();return(_interopRequireWildcard=function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,"default":e};if(null===e||"object"!=_typeof(e)&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f);}for(var _t2 in e)"default"!==_t2&&{}.hasOwnProperty.call(e,_t2)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,_t2))&&(i.get||i.set)?o(f,_t2,i):f[_t2]=e[_t2]);return f;})(e,t);}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;}var webClickListeners=new WeakMap();function PostHogNavigationHook(_ref){var options=_ref.options,client=_ref.client;(0,_useNavigationTracker.useNavigationTracker)(options===null||options===void 0?void 0:options.navigation,options===null||options===void 0?void 0:options.navigationRef,client);return null;}var PostHogProvider=exports.PostHogProvider=function PostHogProvider(_ref2){var children=_ref2.children,client=_ref2.client,options=_ref2.options,projectToken=_ref2.projectToken,apiKey=_ref2.apiKey,autocapture=_ref2.autocapture,style=_ref2.style,_ref2$debug=_ref2.debug,debug=_ref2$debug===void 0?false:_ref2$debug;var _a;var captureAll=autocapture===true;var captureNone=autocapture===false;var token=projectToken!==null&&projectToken!==void 0?projectToken:apiKey;var posthog=(0,_react.useMemo)(function(){if(client&&token){console.warn('You have provided both a client and a projectToken to PostHogProvider. The projectToken will be ignored in favour of the client.');}if(client){return client;}var parsedOptions=_objectSpread(_objectSpread({},options),{},{captureAppLifecycleEvents:(options===null||options===void 0?void 0:options.captureAppLifecycleEvents)!==undefined?options.captureAppLifecycleEvents:!captureNone});return new _posthogRn.PostHog(token!==null&&token!==void 0?token:'',parsedOptions);},[client,token]);var autocaptureOptions=(0,_react.useMemo)(function(){return autocapture&&typeof autocapture!=='boolean'?autocapture:{};},[autocapture]);var captureTouches=!captureNone&&posthog&&(captureAll||(autocaptureOptions===null||autocaptureOptions===void 0?void 0:autocaptureOptions.captureTouches));var captureScreens=!captureNone&&posthog&&(captureAll||((_a=autocaptureOptions===null||autocaptureOptions===void 0?void 0:autocaptureOptions.captureScreens)!==null&&_a!==void 0?_a:true));var phLabelProp=(autocaptureOptions===null||autocaptureOptions===void 0?void 0:autocaptureOptions.customLabelProp)||_autocapture.defaultPostHogLabelProp;(0,_react.useEffect)(function(){posthog.debug(debug);},[debug,posthog]);var onTouch=(0,_react.useCallback)(function(type,e){if(!captureTouches){return;}if(type==='end'){(0,_autocapture.autocaptureFromTouchEvent)(e,posthog,autocaptureOptions);}},[captureTouches,posthog,autocaptureOptions]);var hostRef=(0,_react.useRef)(null);var optionsRef=(0,_react.useRef)(autocaptureOptions);(0,_react.useEffect)(function(){optionsRef.current=autocaptureOptions;},[autocaptureOptions]);(0,_react.useEffect)(function(){var doc=globalThis===null||globalThis===void 0?void 0:globalThis.document;if(!(0,_utils.isWeb)()||!captureTouches||!(doc===null||doc===void 0?void 0:doc.addEventListener)){return;}var ownerNode=hostRef.current;if(!ownerNode){return;}var existing=webClickListeners.get(posthog);if(existing){existing.owners.set(ownerNode,optionsRef);}else{var owners=new Map([[ownerNode,optionsRef]]);var handler=function handler(e){var _a;var owner=(0,_autocapture.findOwningNode)(e,owners);if(!owner){return;}var options=(_a=owners.get(owner))===null||_a===void 0?void 0:_a.current;if(!options){return;}(0,_autocapture.autocaptureFromTouchEvent)({target:e.target,nativeEvent:e},posthog,options,'click');};doc.addEventListener('click',handler,true);webClickListeners.set(posthog,{owners:owners,remove:function remove(){return doc.removeEventListener('click',handler,true);}});}return function(){var entry=webClickListeners.get(posthog);if(!entry){return;}entry.owners["delete"](ownerNode);if(entry.owners.size===0){entry.remove();webClickListeners["delete"](posthog);}};},[captureTouches,posthog]);var captureProps=(0,_utils.isWeb)()?{}:{onTouchEndCapture:captureTouches?function(e){return onTouch('end',e);}:undefined};return(0,_jsxRuntime.jsx)(_reactNative.View,_objectSpread(_objectSpread(_objectSpread({ref:hostRef},(0,_defineProperty2["default"])({},phLabelProp,'PostHogProvider')),{},{style:style||{flex:1}},captureProps),{},{children:(0,_jsxRuntime.jsxs)(_PostHogContext.PostHogContext.Provider,{value:{client:posthog},children:[captureScreens&&(0,_jsxRuntime.jsx)(PostHogNavigationHook,{options:autocaptureOptions,client:posthog}),children]})}));};
2
2
  //# sourceMappingURL=PostHogProvider.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"PostHogProvider.js","names":["_react","_interopRequireWildcard","require","_reactNative","_posthogRn","_autocapture","_useNavigationTracker","_PostHogContext","_utils","_jsxRuntime","_this","_jsxFileName","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","_typeof","has","get","set","_t2","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","ownKeys","keys","getOwnPropertySymbols","filter","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","webClickListeners","PostHogNavigationHook","_ref","options","client","useNavigationTracker","navigation","navigationRef","PostHogProvider","exports","_ref2","children","apiKey","autocapture","style","_ref2$debug","debug","captureAll","captureNone","posthog","useMemo","console","warn","parsedOptions","captureAppLifecycleEvents","undefined","PostHog","autocaptureOptions","captureTouches","captureScreens","_a","phLabelProp","customLabelProp","defaultPostHogLabelProp","useEffect","onTouch","useCallback","type","autocaptureFromTouchEvent","hostRef","useRef","optionsRef","current","doc","globalThis","document","isWeb","addEventListener","ownerNode","existing","owners","Map","handler","owner","findOwningNode","target","nativeEvent","remove","removeEventListener","entry","size","captureProps","onTouchEndCapture","jsx","View","ref","flex","jsxs","PostHogContext","Provider","value"],"sources":["../src/PostHogProvider.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useMemo, useRef } from 'react'\nimport { GestureResponderEvent, StyleProp, View, ViewStyle } from 'react-native'\nimport { PostHog, PostHogOptions } from './posthog-rn'\nimport { autocaptureFromTouchEvent, findOwningNode } from './autocapture'\nimport { useNavigationTracker } from './hooks/useNavigationTracker'\nimport { PostHogContext } from './PostHogContext'\nimport { PostHogAutocaptureOptions } from './types'\nimport { isWeb } from './utils'\nimport { defaultPostHogLabelProp } from './autocapture'\n\n/**\n * Props for the PostHogProvider component.\n *\n * @public\n */\nexport interface PostHogProviderProps {\n /** The child components to render within the PostHog context */\n children: React.ReactNode\n /** PostHog configuration options */\n options?: PostHogOptions\n /**\n * Your PostHog project token, which starts with `phc_`. Find it in your project settings:\n * https://us.posthog.com/settings/project-details#variables\n */\n apiKey?: string\n /** An existing PostHog client instance */\n client?: PostHog\n /**\n * Autocapture configuration - can be a boolean or detailed options.\n *\n * When not set, the default behavior is:\n * - `captureScreens`: true\n * - `captureTouches`: false\n * - `captureAppLifecycleEvents`: true\n *\n * Set to `true` to enable all autocapture features (including touches).\n * Set to `false` to disable all autocapture features.\n */\n autocapture?: boolean | PostHogAutocaptureOptions\n /**\n * Enable debug mode for additional logging\n *\n * @default false\n */\n debug?: boolean\n /** Custom styles for the provider wrapper View */\n style?: StyleProp<ViewStyle>\n}\n\n// One document click listener per client, shared across sibling providers, so one interaction\n// enqueues exactly one $autocapture event (sdk-specs autocapture). `owners` maps each mounted\n// provider's host node to its own options, so a click is scoped to the owning subtree AND\n// captured with that provider's config; its size doubles as the refcount.\ntype WebClickOwners = Map<unknown, React.MutableRefObject<PostHogAutocaptureOptions>>\nconst webClickListeners = new WeakMap<PostHog, { owners: WebClickOwners; remove: () => void }>()\n\nfunction PostHogNavigationHook({\n options,\n client,\n}: {\n options?: PostHogAutocaptureOptions\n client?: PostHog\n}): JSX.Element | null {\n useNavigationTracker(options?.navigation, options?.navigationRef, client)\n return null\n}\n\n/**\n * PostHogProvider is a React component that provides PostHog functionality to your React Native app. You can find all configuration options in the [React Native SDK docs](https://posthog.com/docs/libraries/react-native#configuration-options).\n *\n * Autocapturing navigation requires further configuration. See the [React Native SDK navigation docs](https://posthog.com/docs/libraries/react-native#capturing-screen-views)\n * for more information about autocapturing navigation.\n *\n * This is the recommended way to set up PostHog for React Native. This utilizes the Context API to pass the PostHog client around, enable autocapture.\n *\n * {@label Initialization}\n *\n * @example\n * ```jsx\n * // Add to App.(js|ts)\n * import { usePostHog, PostHogProvider } from 'posthog-react-native'\n *\n * export function MyApp() {\n * return (\n * <PostHogProvider apiKey=\"<ph_project_api_key>\" options={{\n * host: '<ph_client_api_host>',\n * }}>\n * <MyComponent />\n * </PostHogProvider>\n * )\n * }\n *\n * // And access the PostHog client via the usePostHog hook\n * import { usePostHog } from 'posthog-react-native'\n *\n * const MyComponent = () => {\n * const posthog = usePostHog()\n *\n * useEffect(() => {\n * posthog.capture(\"event_name\")\n * }, [posthog])\n * }\n *\n * ```\n *\n * @example\n * ```jsx\n * // Using with existing client\n * import { PostHog } from 'posthog-react-native'\n *\n * const posthog = new PostHog('<ph_project_api_key>', {\n * host: '<ph_client_api_host>'\n * })\n *\n * export function MyApp() {\n * return (\n * <PostHogProvider client={posthog}>\n * <MyComponent />\n * </PostHogProvider>\n * )\n * }\n * ```\n *\n * @public\n *\n * @param props - The PostHogProvider props\n */\nexport const PostHogProvider = ({\n children,\n client,\n options,\n apiKey,\n autocapture,\n style,\n debug = false,\n}: PostHogProviderProps): JSX.Element | null => {\n const captureAll = autocapture === true\n const captureNone = autocapture === false\n\n const posthog = useMemo(() => {\n if (client && apiKey) {\n console.warn(\n 'You have provided both a client and an apiKey to PostHogProvider. The apiKey will be ignored in favour of the client.'\n )\n }\n\n if (client) {\n return client\n }\n\n const parsedOptions = {\n ...options,\n captureAppLifecycleEvents:\n options?.captureAppLifecycleEvents !== undefined ? options.captureAppLifecycleEvents : !captureNone,\n }\n\n return new PostHog(apiKey ?? '', parsedOptions)\n }, [client, apiKey]) // oxlint-disable-line react/exhaustive-deps\n\n const autocaptureOptions = useMemo(\n () => (autocapture && typeof autocapture !== 'boolean' ? autocapture : {}),\n [autocapture]\n )\n\n const captureTouches = !captureNone && posthog && (captureAll || autocaptureOptions?.captureTouches)\n const captureScreens = !captureNone && posthog && (captureAll || (autocaptureOptions?.captureScreens ?? true)) // Default to true if not set\n const phLabelProp = autocaptureOptions?.customLabelProp || defaultPostHogLabelProp\n\n useEffect(() => {\n posthog.debug(debug)\n }, [debug, posthog])\n\n const onTouch = useCallback(\n (type: 'start' | 'move' | 'end', e: GestureResponderEvent) => {\n // TODO: Improve this to ensure we only capture presses and not just ends of a drag for example\n if (!captureTouches) {\n return\n }\n\n if (type === 'end') {\n autocaptureFromTouchEvent(e, posthog, autocaptureOptions)\n }\n },\n [captureTouches, posthog, autocaptureOptions]\n )\n\n // Browsers fire touchend only for touch input, so a mouse never reaches onTouchEndCapture.\n // Listen on the document in the CAPTURE phase: RNW forwards `onClick` but not `onClickCapture`,\n // and its Pressable stops propagation before any bubble-phase handler runs. Document-wide so it\n // still sees Modal; subtree scoping happens in autocapture.tsx. Read options through a ref so an\n // inline `autocapture` prop doesn't re-attach every render.\n const hostRef = useRef<unknown>(null)\n const optionsRef = useRef(autocaptureOptions)\n useEffect(() => {\n optionsRef.current = autocaptureOptions\n }, [autocaptureOptions])\n\n useEffect(() => {\n // The package targets ESNext without the DOM lib, so reach the document off the global.\n const doc = (globalThis as any)?.document\n if (!isWeb() || !captureTouches || !doc?.addEventListener) {\n return\n }\n\n const ownerNode = hostRef.current\n if (!ownerNode) {\n // Without a host node nothing can be scoped to this provider, and a null key would collide\n // with any sibling in the same state.\n return\n }\n\n const existing = webClickListeners.get(posthog)\n if (existing) {\n existing.owners.set(ownerNode, optionsRef)\n } else {\n const owners: WebClickOwners = new Map([[ownerNode, optionsRef]])\n const handler = (e: any): void => {\n const owner = findOwningNode(e, owners)\n if (!owner) {\n return\n }\n const options = owners.get(owner)?.current\n if (!options) {\n return\n }\n autocaptureFromTouchEvent({ target: e.target, nativeEvent: e }, posthog, options, 'click')\n }\n doc.addEventListener('click', handler, true)\n webClickListeners.set(posthog, {\n owners,\n remove: () => doc.removeEventListener('click', handler, true),\n })\n }\n\n return () => {\n const entry = webClickListeners.get(posthog)\n if (!entry) {\n return\n }\n entry.owners.delete(ownerNode)\n if (entry.owners.size === 0) {\n entry.remove()\n webClickListeners.delete(posthog)\n }\n }\n }, [captureTouches, posthog])\n\n const captureProps = isWeb()\n ? {}\n : { onTouchEndCapture: captureTouches ? (e: GestureResponderEvent) => onTouch('end', e) : undefined }\n\n return (\n <View\n ref={hostRef as any}\n {...{ [phLabelProp]: 'PostHogProvider' }} // Dynamically setting customLabelProp (default: ph-label)\n style={style || { flex: 1 }}\n {...captureProps}\n >\n <PostHogContext.Provider value={{ client: posthog }}>\n {captureScreens && <PostHogNavigationHook options={autocaptureOptions} client={posthog} />}\n {children}\n </PostHogContext.Provider>\n </View>\n )\n}\n"],"mappings":"2UAAA,IAAAA,MAAA,CAAAC,uBAAA,CAAAC,OAAA,WACA,IAAAC,YAAA,CAAAD,OAAA,iBACA,IAAAE,UAAA,CAAAF,OAAA,iBACA,IAAAG,YAAA,CAAAH,OAAA,kBACA,IAAAI,qBAAA,CAAAJ,OAAA,iCACA,IAAAK,eAAA,CAAAL,OAAA,qBAEA,IAAAM,MAAA,CAAAN,OAAA,YAA+B,IAAAO,WAAA,CAAAP,OAAA,0BAAAQ,KAAA,QAAAC,YAAA,kGAAAV,wBAAAW,CAAA,CAAAC,CAAA,wBAAAC,OAAA,KAAAC,CAAA,KAAAD,OAAA,GAAAE,CAAA,KAAAF,OAAA,UAAAb,uBAAA,UAAAA,wBAAAW,CAAA,CAAAC,CAAA,MAAAA,CAAA,EAAAD,CAAA,EAAAA,CAAA,CAAAK,UAAA,QAAAL,CAAA,KAAAM,CAAA,CAAAC,CAAA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SAAS,CAAC,CAC9B,GAAIW,KAAK,CAACT,MAAM,CAACU,IAAI,GAAK,CAAC,CAAE,CAC3BD,KAAK,CAACF,MAAM,EAAE,CACdzD,iBAAiB,UAAO,CAACmB,OAAO,CAAC,CACnC,CACF,CAAC,CACH,CAAC,CAAE,CAACS,cAAc,CAAET,OAAO,CAAC,CAAC,CAE7B,GAAM,CAAA0C,YAAY,CAAG,GAAAf,YAAK,GAAE,CACxB,EAAE,CACF,CAAEgB,iBAAiB,CAAElC,cAAc,CAAG,SAAC9D,CAAwB,QAAK,CAAAqE,OAAO,CAAC,KAAK,CAAErE,CAAC,CAAC,GAAG2D,SAAS,CAAE,CAEvG,MACE,GAAA9D,WAAA,CAAAoG,GAAA,EAAC1G,YAAA,CAAA2G,IAAI,CAAAvE,aAAA,CAAAA,aAAA,CAAAA,aAAA,EACHwE,GAAG,CAAE1B,OAAe,KAAA1C,gBAAA,gBACbkC,WAAW,CAAG,iBAAiB,OACtCjB,KAAK,CAAEA,KAAK,EAAI,CAAEoD,IAAI,CAAE,CAAC,CAAG,EACxBL,YAAY,MAAAlD,QAAA,CAEhB,GAAAhD,WAAA,CAAAwG,IAAA,EAAC1G,eAAA,CAAA2G,cAAc,CAACC,QAAQ,EAACC,KAAK,CAAE,CAAElE,MAAM,CAAEe,OAAO,CAAG,CAAAR,QAAA,EACjDkB,cAAc,EAAI,GAAAlE,WAAA,CAAAoG,GAAA,EAAC9D,qBAAqB,EAACE,OAAO,CAAEwB,kBAAmB,CAACvB,MAAM,CAAEe,OAAQ,EAAG,CACzFR,QAAQ,EACc,CAC3B,EAAM,CAAC,CAEX,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"PostHogProvider.js","names":["_react","_interopRequireWildcard","require","_reactNative","_posthogRn","_autocapture","_useNavigationTracker","_PostHogContext","_utils","_jsxRuntime","_this","_jsxFileName","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","_typeof","has","get","set","_t2","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","ownKeys","keys","getOwnPropertySymbols","filter","enumerable","push","apply","_objectSpread","arguments","length","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","webClickListeners","PostHogNavigationHook","_ref","options","client","useNavigationTracker","navigation","navigationRef","PostHogProvider","exports","_ref2","children","projectToken","apiKey","autocapture","style","_ref2$debug","debug","captureAll","captureNone","token","posthog","useMemo","console","warn","parsedOptions","captureAppLifecycleEvents","undefined","PostHog","autocaptureOptions","captureTouches","captureScreens","_a","phLabelProp","customLabelProp","defaultPostHogLabelProp","useEffect","onTouch","useCallback","type","autocaptureFromTouchEvent","hostRef","useRef","optionsRef","current","doc","globalThis","document","isWeb","addEventListener","ownerNode","existing","owners","Map","handler","owner","findOwningNode","target","nativeEvent","remove","removeEventListener","entry","size","captureProps","onTouchEndCapture","jsx","View","ref","flex","jsxs","PostHogContext","Provider","value"],"sources":["../src/PostHogProvider.tsx"],"sourcesContent":["import React, { useCallback, useEffect, useMemo, useRef } from 'react'\nimport { GestureResponderEvent, StyleProp, View, ViewStyle } from 'react-native'\nimport { PostHog, PostHogOptions } from './posthog-rn'\nimport { autocaptureFromTouchEvent, findOwningNode } from './autocapture'\nimport { useNavigationTracker } from './hooks/useNavigationTracker'\nimport { PostHogContext } from './PostHogContext'\nimport { PostHogAutocaptureOptions } from './types'\nimport { isWeb } from './utils'\nimport { defaultPostHogLabelProp } from './autocapture'\n\n/**\n * Props for the PostHogProvider component.\n *\n * @public\n */\nexport interface PostHogProviderProps {\n /** The child components to render within the PostHog context */\n children: React.ReactNode\n /** PostHog configuration options */\n options?: PostHogOptions\n /**\n * Your PostHog project token, which starts with `phc_`. Find it in your project settings:\n * https://us.posthog.com/settings/project-details#variables\n */\n projectToken?: string\n /**\n * Your PostHog project token. Ignored when `projectToken` is set.\n *\n * @deprecated Use `projectToken` instead. This will be removed in the next major version.\n */\n apiKey?: string\n /** An existing PostHog client instance */\n client?: PostHog\n /**\n * Autocapture configuration - can be a boolean or detailed options.\n *\n * When not set, the default behavior is:\n * - `captureScreens`: true\n * - `captureTouches`: false\n * - `captureAppLifecycleEvents`: true\n *\n * Set to `true` to enable all autocapture features (including touches).\n * Set to `false` to disable all autocapture features.\n */\n autocapture?: boolean | PostHogAutocaptureOptions\n /**\n * Enable debug mode for additional logging\n *\n * @default false\n */\n debug?: boolean\n /** Custom styles for the provider wrapper View */\n style?: StyleProp<ViewStyle>\n}\n\n// One document click listener per client, shared across sibling providers, so one interaction\n// enqueues exactly one $autocapture event (sdk-specs autocapture). `owners` maps each mounted\n// provider's host node to its own options, so a click is scoped to the owning subtree AND\n// captured with that provider's config; its size doubles as the refcount.\ntype WebClickOwners = Map<unknown, React.MutableRefObject<PostHogAutocaptureOptions>>\nconst webClickListeners = new WeakMap<PostHog, { owners: WebClickOwners; remove: () => void }>()\n\nfunction PostHogNavigationHook({\n options,\n client,\n}: {\n options?: PostHogAutocaptureOptions\n client?: PostHog\n}): JSX.Element | null {\n useNavigationTracker(options?.navigation, options?.navigationRef, client)\n return null\n}\n\n/**\n * PostHogProvider is a React component that provides PostHog functionality to your React Native app. You can find all configuration options in the [React Native SDK docs](https://posthog.com/docs/libraries/react-native#configuration-options).\n *\n * Autocapturing navigation requires further configuration. See the [React Native SDK navigation docs](https://posthog.com/docs/libraries/react-native#capturing-screen-views)\n * for more information about autocapturing navigation.\n *\n * This is the recommended way to set up PostHog for React Native. This utilizes the Context API to pass the PostHog client around, enable autocapture.\n *\n * {@label Initialization}\n *\n * @example\n * ```jsx\n * // Add to App.(js|ts)\n * import { usePostHog, PostHogProvider } from 'posthog-react-native'\n *\n * export function MyApp() {\n * return (\n * <PostHogProvider projectToken=\"<ph_project_token>\" options={{\n * host: '<ph_client_api_host>',\n * }}>\n * <MyComponent />\n * </PostHogProvider>\n * )\n * }\n *\n * // And access the PostHog client via the usePostHog hook\n * import { usePostHog } from 'posthog-react-native'\n *\n * const MyComponent = () => {\n * const posthog = usePostHog()\n *\n * useEffect(() => {\n * posthog.capture(\"event_name\")\n * }, [posthog])\n * }\n *\n * ```\n *\n * @example\n * ```jsx\n * // Using with existing client\n * import { PostHog } from 'posthog-react-native'\n *\n * const posthog = new PostHog('<ph_project_token>', {\n * host: '<ph_client_api_host>'\n * })\n *\n * export function MyApp() {\n * return (\n * <PostHogProvider client={posthog}>\n * <MyComponent />\n * </PostHogProvider>\n * )\n * }\n * ```\n *\n * @public\n *\n * @param props - The PostHogProvider props\n */\nexport const PostHogProvider = ({\n children,\n client,\n options,\n projectToken,\n apiKey,\n autocapture,\n style,\n debug = false,\n}: PostHogProviderProps): JSX.Element | null => {\n const captureAll = autocapture === true\n const captureNone = autocapture === false\n\n const token = projectToken ?? apiKey\n\n const posthog = useMemo(() => {\n if (client && token) {\n console.warn(\n 'You have provided both a client and a projectToken to PostHogProvider. The projectToken will be ignored in favour of the client.'\n )\n }\n\n if (client) {\n return client\n }\n\n const parsedOptions = {\n ...options,\n captureAppLifecycleEvents:\n options?.captureAppLifecycleEvents !== undefined ? options.captureAppLifecycleEvents : !captureNone,\n }\n\n return new PostHog(token ?? '', parsedOptions)\n }, [client, token]) // oxlint-disable-line react/exhaustive-deps\n\n const autocaptureOptions = useMemo(\n () => (autocapture && typeof autocapture !== 'boolean' ? autocapture : {}),\n [autocapture]\n )\n\n const captureTouches = !captureNone && posthog && (captureAll || autocaptureOptions?.captureTouches)\n const captureScreens = !captureNone && posthog && (captureAll || (autocaptureOptions?.captureScreens ?? true)) // Default to true if not set\n const phLabelProp = autocaptureOptions?.customLabelProp || defaultPostHogLabelProp\n\n useEffect(() => {\n posthog.debug(debug)\n }, [debug, posthog])\n\n const onTouch = useCallback(\n (type: 'start' | 'move' | 'end', e: GestureResponderEvent) => {\n // TODO: Improve this to ensure we only capture presses and not just ends of a drag for example\n if (!captureTouches) {\n return\n }\n\n if (type === 'end') {\n autocaptureFromTouchEvent(e, posthog, autocaptureOptions)\n }\n },\n [captureTouches, posthog, autocaptureOptions]\n )\n\n // Browsers fire touchend only for touch input, so a mouse never reaches onTouchEndCapture.\n // Listen on the document in the CAPTURE phase: RNW forwards `onClick` but not `onClickCapture`,\n // and its Pressable stops propagation before any bubble-phase handler runs. Document-wide so it\n // still sees Modal; subtree scoping happens in autocapture.tsx. Read options through a ref so an\n // inline `autocapture` prop doesn't re-attach every render.\n const hostRef = useRef<unknown>(null)\n const optionsRef = useRef(autocaptureOptions)\n useEffect(() => {\n optionsRef.current = autocaptureOptions\n }, [autocaptureOptions])\n\n useEffect(() => {\n // The package targets ESNext without the DOM lib, so reach the document off the global.\n const doc = (globalThis as any)?.document\n if (!isWeb() || !captureTouches || !doc?.addEventListener) {\n return\n }\n\n const ownerNode = hostRef.current\n if (!ownerNode) {\n // Without a host node nothing can be scoped to this provider, and a null key would collide\n // with any sibling in the same state.\n return\n }\n\n const existing = webClickListeners.get(posthog)\n if (existing) {\n existing.owners.set(ownerNode, optionsRef)\n } else {\n const owners: WebClickOwners = new Map([[ownerNode, optionsRef]])\n const handler = (e: any): void => {\n const owner = findOwningNode(e, owners)\n if (!owner) {\n return\n }\n const options = owners.get(owner)?.current\n if (!options) {\n return\n }\n autocaptureFromTouchEvent({ target: e.target, nativeEvent: e }, posthog, options, 'click')\n }\n doc.addEventListener('click', handler, true)\n webClickListeners.set(posthog, {\n owners,\n remove: () => doc.removeEventListener('click', handler, true),\n })\n }\n\n return () => {\n const entry = webClickListeners.get(posthog)\n if (!entry) {\n return\n }\n entry.owners.delete(ownerNode)\n if (entry.owners.size === 0) {\n entry.remove()\n webClickListeners.delete(posthog)\n }\n }\n }, [captureTouches, posthog])\n\n const captureProps = isWeb()\n ? {}\n : { onTouchEndCapture: captureTouches ? (e: GestureResponderEvent) => onTouch('end', e) : undefined }\n\n return (\n <View\n ref={hostRef as any}\n {...{ [phLabelProp]: 'PostHogProvider' }} // Dynamically setting customLabelProp (default: ph-label)\n style={style || { flex: 1 }}\n {...captureProps}\n >\n <PostHogContext.Provider value={{ client: posthog }}>\n {captureScreens && <PostHogNavigationHook options={autocaptureOptions} client={posth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AA,aAAA,CAAAA,aAAA,EACH0E,GAAG,CAAE1B,OAAe,KAAA5C,gBAAA,gBACboC,WAAW,CAAG,iBAAiB,OACtClB,KAAK,CAAEA,KAAK,EAAI,CAAEqD,IAAI,CAAE,CAAC,CAAG,EACxBL,YAAY,MAAApD,QAAA,CAEhB,GAAAhD,WAAA,CAAA0G,IAAA,EAAC5G,eAAA,CAAA6G,cAAc,CAACC,QAAQ,EAACC,KAAK,CAAE,CAAEpE,MAAM,CAAEiB,OAAO,CAAG,CAAAV,QAAA,EACjDoB,cAAc,EAAI,GAAApE,WAAA,CAAAsG,GAAA,EAAChE,qBAAqB,EAACE,OAAO,CAAE0B,kBAAmB,CAACzB,MAAM,CAAEiB,OAAQ,EAAG,CACzFV,QAAQ,EACc,CAC3B,EAAM,CAAC,CAEX,CAAC","ignoreList":[]}
@@ -76,6 +76,7 @@ export declare class ErrorTracking {
76
76
  * Defaults to true (don't block locally enabled capture before remote config loads).
77
77
  */
78
78
  private _autocaptureEnabled;
79
+ private _suppressionRules;
79
80
  constructor(instance: PostHog, options: ErrorTrackingOptions | undefined, logger: Logger, fatalCaptureHooks?: FatalCaptureHooks | undefined);
80
81
  /**
81
82
  * Exception-steps config in the native plugin's shape, so the embedded native SDK keeps one
@@ -109,11 +110,18 @@ export declare class ErrorTracking {
109
110
  * Clears the buffer. Called on SDK close, not on capture or identity changes.
110
111
  */
111
112
  clearExceptionSteps(): void;
113
+ /**
114
+ * Whether an exception matches one of the suppression rules from remote config, in which case
115
+ * it should be dropped instead of captured. Mirrors the browser SDK. Records an exception step
116
+ * when it matches, so the next captured exception shows that one was dropped.
117
+ */
118
+ shouldSuppressException(exceptionList: unknown): boolean;
112
119
  shutdown(): void;
113
120
  /**
114
121
  * Called when remote config is loaded.
115
122
  * If errorTracking.autocaptureExceptions is explicitly false, autocapture is disabled.
116
123
  * If it's true or undefined (not yet loaded / not present), autocapture follows local config.
124
+ * errorTracking.suppressionRules replaces the current rules; a response without them clears them.
117
125
  */
118
126
  onRemoteConfig(errorTracking: boolean | {
119
127
  [key: string]: JsonType;
@@ -1,2 +1,2 @@
1
- "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ErrorTracking=void 0;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _core=require("@posthog/core");var _utils=require("./utils");var _utils2=require("../utils");var _OptionalPlugin=require("../optional/OptionalPlugin");var _fatalPayload=require("./fatal-payload");function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]};},e:function e(r){throw r;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var o,a=!0,u=!1;return{s:function s(){t=t.call(r);},n:function n(){var r=t.next();return a=r.done,r;},e:function e(r){u=!0,o=r;},f:function f(){try{a||null==t["return"]||t["return"]();}finally{if(u)throw o;}}};}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0;}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n;}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;}var LogLevelList=['debug','log','info','warn','error'];var FATAL_MESSAGE_KEY_LENGTH=80;function fatalMessageKey(error){var message;if(error instanceof Error){var namePrefix=error.name?"".concat(error.name,": "):'';message=error.message||'';if(!message.startsWith(namePrefix)){message=namePrefix+message;}}else{message=error===undefined?'':String(error);}return Array.from(message).slice(0,FATAL_MESSAGE_KEY_LENGTH).join('');}var ErrorTracking=exports.ErrorTracking=function(){function ErrorTracking(instance){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var logger=arguments.length>2?arguments[2]:undefined;var fatalCaptureHooks=arguments.length>3?arguments[3]:undefined;(0,_classCallCheck2["default"])(this,ErrorTracking);this.instance=instance;this.fatalCaptureHooks=fatalCaptureHooks;this._nativeForwardingEnabled=false;this._autocaptureEnabled=true;this.logger=logger.createLogger('[ErrorTracking]');this.options=this.resolveOptions(options);var exceptionSteps=options.exceptionSteps;this._exceptionStepsConfig=_core.ErrorTracking.resolveExceptionStepsConfig(exceptionSteps?{enabled:exceptionSteps.enabled,max_bytes:exceptionSteps.maxBytes}:undefined);this._exceptionStepsBuffer=new _core.ErrorTracking.ExceptionStepsBuffer(this._exceptionStepsConfig);this.autocapture(this.options.autocapture);}return(0,_createClass2["default"])(ErrorTracking,[{key:"getNativePluginExceptionStepsConfig",value:function getNativePluginExceptionStepsConfig(){return{enabled:this._exceptionStepsConfig.enabled,maxBytes:this._exceptionStepsConfig.max_bytes};}},{key:"addExceptionStep",value:function addExceptionStep(message,properties){if(!this._exceptionStepsConfig.enabled){return;}try{if(!(0,_core.isString)(message)||message.trim().length===0){this.logger.warn('Ignoring exception step because message must be a non-empty string');return;}var userProperties=(0,_core.isObject)(properties)?_objectSpread({},properties):{};var _CoreErrorTracking$st=_core.ErrorTracking.stripReservedExceptionStepFields(userProperties),sanitizedProperties=_CoreErrorTracking$st.sanitizedProperties,droppedKeys=_CoreErrorTracking$st.droppedKeys;if(droppedKeys.length>0){this.logger.warn('Ignoring reserved exception step fields',{droppedKeys:droppedKeys});}this._exceptionStepsBuffer.add(_objectSpread((0,_defineProperty2["default"])((0,_defineProperty2["default"])({},_core.ErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,message),_core.ErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP,new Date().toISOString()),sanitizedProperties));this.forwardExceptionStepToNative(message,properties);}catch(error){this.logger.error('Failed to add exception step. Ignoring breadcrumb.',error);}}},{key:"onNativeErrorTrackingReady",value:function onNativeErrorTrackingReady(){this._nativeForwardingEnabled=true;var _iterator=_createForOfIteratorHelper(this.getAttachableExceptionSteps()),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var step=_step.value;this.forwardExceptionStepToNative(step.$message,step);}}catch(err){_iterator.e(err);}finally{_iterator.f();}}},{key:"forwardExceptionStepToNative",value:function forwardExceptionStepToNative(message,properties){var _this=this;if(!this._nativeForwardingEnabled||!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.addExceptionStep)){return;}try{void Promise.resolve(_OptionalPlugin.OptionalReactNativePlugin.addExceptionStep(message,properties))["catch"](function(e){_this.logger.warn("Failed to forward exception step to native: ".concat(e));});}catch(e){this.logger.warn("Failed to forward exception step to native: ".concat(e));}}},{key:"attachExceptionSteps",value:function attachExceptionSteps(properties){if(!this._exceptionStepsConfig.enabled||!(0,_core.isNullish)(properties.$exception_steps)){return properties;}var steps=this.getAttachableExceptionSteps();if(steps.length===0){return properties;}return _objectSpread(_objectSpread({},properties),{},{$exception_steps:steps});}},{key:"getAttachableExceptionSteps",value:function getAttachableExceptionSteps(){if(!this._exceptionStepsConfig.enabled){return[];}try{return this._exceptionStepsBuffer.getAttachable();}catch(error){this.logger.error('Failed to read buffered exception steps.',error);return[];}}},{key:"clearExceptionSteps",value:function clearExceptionSteps(){this._exceptionStepsBuffer.clear();}},{key:"shutdown",value:function shutdown(){var _a;this._autocaptureEnabled=false;(_a=this._unsubscribeUncaughtExceptions)===null||_a===void 0?void 0:_a.call(this);this._unsubscribeUncaughtExceptions=undefined;this.clearExceptionSteps();}},{key:"onRemoteConfig",value:function onRemoteConfig(errorTracking){if(errorTracking==null){return;}this._autocaptureEnabled=(0,_utils2.getRemoteConfigBool)(errorTracking,'autocaptureExceptions',false);this.logger.info("Error tracking autocapture ".concat(this._autocaptureEnabled?'enabled':'disabled'," by remote config."));}},{key:"isUncaughtExceptionAutocaptureEnabled",value:function isUncaughtExceptionAutocaptureEnabled(){return this.options.autocapture.uncaughtExceptions;}},{key:"resolveOptions",value:function resolveOptions(options){var autocaptureOptions=this.resolveAutocaptureOptions(options.autocapture);return{autocapture:autocaptureOptions};}},{key:"resolveAutocaptureOptions",value:function resolveAutocaptureOptions(){var autocapture=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(typeof autocapture==='boolean'){return{uncaughtExceptions:autocapture,unhandledRejections:autocapture,console:[]};}return{uncaughtExceptions:!!autocapture.uncaughtExceptions,unhandledRejections:!!autocapture.unhandledRejections,console:this.resolveConsoleOptions(autocapture.console)};}},{key:"resolveConsoleOptions",value:function resolveConsoleOptions(){var console=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(typeof console==='boolean'){return console?['error']:[];}return Array.isArray(console)?console.filter(function(level){return LogLevelList.includes(level);}):[];}},{key:"autocaptureUncaughtErrors",value:function autocaptureUncaughtErrors(){var _this2=this;var onUncaughtException=function onUncaughtException(error,isFatal){var marked=isFatal?_this2.markFatalExceptionHandled(error):undefined;if(!_this2._autocaptureEnabled||(0,_core.isPostHogFetchNetworkError)(error)){return marked;}var hint={mechanism:{type:'onuncaughtexception',handled:false}};if(!isFatal){_this2.instance.captureException(error,{},hint);return;}return Promise.all([marked,_this2.handleFatalException(error,hint,(0,_core.uuidv7)(),new Date())]).then(function(){});};try{this._unsubscribeUncaughtExceptions=(0,_utils.trackUncaughtExceptions)(onUncaughtException);}catch(err){this.logger.warn('Failed to track uncaught exceptions: ',err);}}},{key:"markFatalExceptionHandled",value:function markFatalExceptionHandled(error){var _this3=this;var bridge=_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.markFatalExceptionHandled;if(!bridge){return undefined;}try{return Promise.resolve(bridge(fatalMessageKey(error)))["catch"](function(e){_this3.logger.warn("Failed to mark fatal exception as handled: ".concat(e));});}catch(e){this.logger.warn("Failed to mark fatal exception as handled: ".concat(e));return undefined;}}},{key:"handleFatalException",value:function(){var _handleFatalException=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(error,hint,eventUuid,timestamp){var _this4=this;var storageReady,result,_result,queued,nativeCapture,persisted,nativeWrite,_yield$Promise$all,_yield$Promise$all2,persistedOk,_t,_t2,_t3;return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:storageReady=!this.fatalCaptureHooks;if(!this.fatalCaptureHooks){_context.next=4;break;}_context.prev=1;_context.next=2;return this.fatalCaptureHooks.waitForStorageReady();case 2:_t=_context.sent;storageReady=_t===true;_context.next=4;break;case 3:_context.prev=3;_t2=_context["catch"](1);this.logger.warn('Fatal capture skipped because events storage did not initialize.',_t2);case 4:if(!(!storageReady||!this._autocaptureEnabled||this.instance.isDisabled||this.instance.optedOut)){_context.next=5;break;}return _context.abrupt("return");case 5:if(this.fatalCaptureHooks){_context.next=6;break;}this.instance.captureException(error,{$exception_level:'fatal'},hint);return _context.abrupt("return");case 6:_context.prev=6;result=this.fatalCaptureHooks.captureFatalException(error,hint,eventUuid,timestamp,function(queued){return _this4.prepareFatalNativeCapture(queued);});_context.next=8;break;case 7:_context.prev=7;_t3=_context["catch"](6);this.logger.error('Fatal exception capture failed before enqueue.',_t3);return _context.abrupt("return");case 8:_result=result,queued=_result.queued,nativeCapture=_result.nativeCapture;if(!(!queued&&!nativeCapture)){_context.next=9;break;}return _context.abrupt("return");case 9:void this.instance.flush()["catch"](function(){_this4.logger.critical('Failed to flush events');});persisted=this.fatalCaptureHooks.waitForJSPersist();if(nativeCapture){try{nativeWrite=nativeCapture()["catch"](function(e){_this4.logger.warn("Fatal exception native capture failed: ".concat(e));});}catch(e){this.logger.warn("Fatal exception native capture failed: ".concat(e));}}_context.next=10;return Promise.all([persisted,nativeWrite]);case 10:_yield$Promise$all=_context.sent;_yield$Promise$all2=(0,_slicedToArray2["default"])(_yield$Promise$all,1);persistedOk=_yield$Promise$all2[0];if(!persistedOk&&!nativeCapture){this.logger.warn('Fatal exception JS persist failed and no native capture path was available.');}case 11:case"end":return _context.stop();}},_callee,this,[[1,3],[6,7]]);}));function handleFatalException(_x,_x2,_x3,_x4){return _handleFatalException.apply(this,arguments);}return handleFatalException;}()},{key:"prepareFatalNativeCapture",value:function prepareFatalNativeCapture(queuedEvent){var _a,_b;var bridge=_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.captureFatalException;if(!bridge){return undefined;}if(!((_a=this.fatalCaptureHooks)===null||_a===void 0?void 0:_a.isNativeCaptureReady())){return undefined;}if(((_b=this.fatalCaptureHooks)===null||_b===void 0?void 0:_b.getPersistenceMode())==='memory'){return undefined;}if(this.instance.isDisabled||this.instance.optedOut){return undefined;}var properties=(0,_core.isObject)(queuedEvent.properties)?queuedEvent.properties:{};var payload=(0,_fatalPayload.buildFatalExceptionPayload)({timestamp:(0,_core.isString)(queuedEvent.timestamp)?queuedEvent.timestamp:new Date().toISOString(),distinctId:(0,_core.isString)(queuedEvent.distinct_id)?queuedEvent.distinct_id:'',properties:properties});return function(){return bridge(payload.distinctId,payload.timestamp,payload.properties);};}},{key:"autocaptureUnhandledRejections",value:function autocaptureUnhandledRejections(){var _this5=this;var onUnhandledRejection=function onUnhandledRejection(error){if(!_this5._autocaptureEnabled){return;}if((0,_core.isPostHogFetchNetworkError)(error)){return;}var hint={mechanism:{type:'onunhandledrejection',handled:false}};_this5.instance.captureException(error,{},hint);};try{(0,_utils.trackUnhandledRejections)(onUnhandledRejection);}catch(err){this.logger.warn('Failed to track unhandled rejections: ',err);}}},{key:"autocaptureConsole",value:function autocaptureConsole(levels){var _this6=this;var onConsole=function onConsole(level){return function(error,isFatal,syntheticException){if(!_this6._autocaptureEnabled){return;}var hint={mechanism:{type:'onconsole',handled:true},syntheticException:syntheticException};var additionalProperties={$exception_level:level};_this6.instance.captureException(error,additionalProperties,hint);};};try{var _iterator2=_createForOfIteratorHelper(levels),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var level=_step2.value;(0,_utils.trackConsole)(level,onConsole(level));}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}}catch(err){this.logger.warn('Failed to track console errors: ',err);}}},{key:"autocapture",value:function autocapture(autocaptureOptions){if(autocaptureOptions.uncaughtExceptions===true){this.autocaptureUncaughtErrors();}if(autocaptureOptions.unhandledRejections===true){this.autocaptureUnhandledRejections();}if(autocaptureOptions.console.length>0){this.autocaptureConsole(autocaptureOptions.console);}}}]);}();
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ErrorTracking=void 0;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _core=require("@posthog/core");var _surveys=require("@posthog/core/surveys");var _utils=require("./utils");var _utils2=require("../utils");var _OptionalPlugin=require("../optional/OptionalPlugin");var _fatalPayload=require("./fatal-payload");function _createForOfIteratorHelper(r,e){var t="undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(!t){if(Array.isArray(r)||(t=_unsupportedIterableToArray(r))||e&&r&&"number"==typeof r.length){t&&(r=t);var _n=0,F=function F(){};return{s:F,n:function n(){return _n>=r.length?{done:!0}:{done:!1,value:r[_n++]};},e:function e(r){throw r;},f:F};}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}var o,a=!0,u=!1;return{s:function s(){t=t.call(r);},n:function n(){var r=t.next();return a=r.done,r;},e:function e(r){u=!0,o=r;},f:function f(){try{a||null==t["return"]||t["return"]();}finally{if(u)throw o;}}};}function _unsupportedIterableToArray(r,a){if(r){if("string"==typeof r)return _arrayLikeToArray(r,a);var t={}.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?_arrayLikeToArray(r,a):void 0;}}function _arrayLikeToArray(r,a){(null==a||a>r.length)&&(a=r.length);for(var e=0,n=Array(a);e<a;e++)n[e]=r[e];return n;}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;}var LogLevelList=['debug','log','info','warn','error'];var FATAL_MESSAGE_KEY_LENGTH=80;function fatalMessageKey(error){var message;if(error instanceof Error){var namePrefix=error.name?"".concat(error.name,": "):'';message=error.message||'';if(!message.startsWith(namePrefix)){message=namePrefix+message;}}else{message=error===undefined?'':String(error);}return Array.from(message).slice(0,FATAL_MESSAGE_KEY_LENGTH).join('');}function parseSuppressionRules(errorTracking){var rules=(0,_core.isObject)(errorTracking)?errorTracking.suppressionRules:undefined;if(!(0,_core.isArray)(rules)){return[];}return rules.filter(function(rule){return(0,_core.isObject)(rule)&&(0,_core.isArray)(rule.values);});}var ErrorTracking=exports.ErrorTracking=function(){function ErrorTracking(instance){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var logger=arguments.length>2?arguments[2]:undefined;var fatalCaptureHooks=arguments.length>3?arguments[3]:undefined;(0,_classCallCheck2["default"])(this,ErrorTracking);this.instance=instance;this.fatalCaptureHooks=fatalCaptureHooks;this._nativeForwardingEnabled=false;this._autocaptureEnabled=true;this._suppressionRules=[];this.logger=logger.createLogger('[ErrorTracking]');this.options=this.resolveOptions(options);var exceptionSteps=options.exceptionSteps;this._exceptionStepsConfig=_core.ErrorTracking.resolveExceptionStepsConfig(exceptionSteps?{enabled:exceptionSteps.enabled,max_bytes:exceptionSteps.maxBytes}:undefined);this._exceptionStepsBuffer=new _core.ErrorTracking.ExceptionStepsBuffer(this._exceptionStepsConfig);this.autocapture(this.options.autocapture);}return(0,_createClass2["default"])(ErrorTracking,[{key:"getNativePluginExceptionStepsConfig",value:function getNativePluginExceptionStepsConfig(){return{enabled:this._exceptionStepsConfig.enabled,maxBytes:this._exceptionStepsConfig.max_bytes};}},{key:"addExceptionStep",value:function addExceptionStep(message,properties){if(!this._exceptionStepsConfig.enabled){return;}try{if(!(0,_core.isString)(message)||message.trim().length===0){this.logger.warn('Ignoring exception step because message must be a non-empty string');return;}var userProperties=(0,_core.isObject)(properties)?_objectSpread({},properties):{};var _CoreErrorTracking$st=_core.ErrorTracking.stripReservedExceptionStepFields(userProperties),sanitizedProperties=_CoreErrorTracking$st.sanitizedProperties,droppedKeys=_CoreErrorTracking$st.droppedKeys;if(droppedKeys.length>0){this.logger.warn('Ignoring reserved exception step fields',{droppedKeys:droppedKeys});}this._exceptionStepsBuffer.add(_objectSpread((0,_defineProperty2["default"])((0,_defineProperty2["default"])({},_core.ErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,message),_core.ErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP,new Date().toISOString()),sanitizedProperties));this.forwardExceptionStepToNative(message,properties);}catch(error){this.logger.error('Failed to add exception step. Ignoring breadcrumb.',error);}}},{key:"onNativeErrorTrackingReady",value:function onNativeErrorTrackingReady(){this._nativeForwardingEnabled=true;var _iterator=_createForOfIteratorHelper(this.getAttachableExceptionSteps()),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var step=_step.value;this.forwardExceptionStepToNative(step.$message,step);}}catch(err){_iterator.e(err);}finally{_iterator.f();}}},{key:"forwardExceptionStepToNative",value:function forwardExceptionStepToNative(message,properties){var _this=this;if(!this._nativeForwardingEnabled||!(_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.addExceptionStep)){return;}try{void Promise.resolve(_OptionalPlugin.OptionalReactNativePlugin.addExceptionStep(message,properties))["catch"](function(e){_this.logger.warn("Failed to forward exception step to native: ".concat(e));});}catch(e){this.logger.warn("Failed to forward exception step to native: ".concat(e));}}},{key:"attachExceptionSteps",value:function attachExceptionSteps(properties){if(!this._exceptionStepsConfig.enabled||!(0,_core.isNullish)(properties.$exception_steps)){return properties;}var steps=this.getAttachableExceptionSteps();if(steps.length===0){return properties;}return _objectSpread(_objectSpread({},properties),{},{$exception_steps:steps});}},{key:"getAttachableExceptionSteps",value:function getAttachableExceptionSteps(){if(!this._exceptionStepsConfig.enabled){return[];}try{return this._exceptionStepsBuffer.getAttachable();}catch(error){this.logger.error('Failed to read buffered exception steps.',error);return[];}}},{key:"clearExceptionSteps",value:function clearExceptionSteps(){this._exceptionStepsBuffer.clear();}},{key:"shouldSuppressException",value:function shouldSuppressException(exceptionList){if(!(0,_core.isArray)(exceptionList)||exceptionList.length===0||this._suppressionRules.length===0){return false;}try{var exceptionValues={$exception_types:[],$exception_values:[]};var _iterator2=_createForOfIteratorHelper(exceptionList),_step2;try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var exception=_step2.value;if(!(0,_core.isObject)(exception)){continue;}if((0,_core.isString)(exception.type)&&exception.type.length>0){exceptionValues.$exception_types.push(exception.type);}if((0,_core.isString)(exception.value)&&exception.value.length>0){exceptionValues.$exception_values.push(exception.value);}}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}var matched=this._suppressionRules.some(function(rule){var results=rule.values.map(function(v){var compare=_surveys.propertyComparisons[v.operator];var values=exceptionValues[v.key];if(!compare||!values){return false;}var targets=(0,_core.isArray)(v.value)?v.value:[v.value];return targets.length>0?compare(targets,values):false;});return rule.type==='OR'?results.some(Boolean):results.every(Boolean);});if(matched){this.addExceptionStep('Exception dropped: matched a suppression rule');}return matched;}catch(error){this.logger.warn('Failed to evaluate suppression rules. Capturing the exception.',error);return false;}}},{key:"shutdown",value:function shutdown(){var _a;this._autocaptureEnabled=false;(_a=this._unsubscribeUncaughtExceptions)===null||_a===void 0?void 0:_a.call(this);this._unsubscribeUncaughtExceptions=undefined;this.clearExceptionSteps();}},{key:"onRemoteConfig",value:function onRemoteConfig(errorTracking){if(errorTracking==null){return;}this._autocaptureEnabled=(0,_utils2.getRemoteConfigBool)(errorTracking,'autocaptureExceptions',false);this._suppressionRules=parseSuppressionRules(errorTracking);this.logger.info("Error tracking autocapture ".concat(this._autocaptureEnabled?'enabled':'disabled'," by remote config."));}},{key:"isUncaughtExceptionAutocaptureEnabled",value:function isUncaughtExceptionAutocaptureEnabled(){return this.options.autocapture.uncaughtExceptions;}},{key:"resolveOptions",value:function resolveOptions(options){var autocaptureOptions=this.resolveAutocaptureOptions(options.autocapture);return{autocapture:autocaptureOptions};}},{key:"resolveAutocaptureOptions",value:function resolveAutocaptureOptions(){var autocapture=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(typeof autocapture==='boolean'){return{uncaughtExceptions:autocapture,unhandledRejections:autocapture,console:[]};}return{uncaughtExceptions:!!autocapture.uncaughtExceptions,unhandledRejections:!!autocapture.unhandledRejections,console:this.resolveConsoleOptions(autocapture.console)};}},{key:"resolveConsoleOptions",value:function resolveConsoleOptions(){var console=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(typeof console==='boolean'){return console?['error']:[];}return Array.isArray(console)?console.filter(function(level){return LogLevelList.includes(level);}):[];}},{key:"autocaptureUncaughtErrors",value:function autocaptureUncaughtErrors(){var _this2=this;var onUncaughtException=function onUncaughtException(error,isFatal){var marked=isFatal?_this2.markFatalExceptionHandled(error):undefined;if(!_this2._autocaptureEnabled||(0,_core.isPostHogFetchNetworkError)(error)){return marked;}var hint={mechanism:{type:'onuncaughtexception',handled:false}};if(!isFatal){_this2.instance.captureException(error,{},hint);return;}return Promise.all([marked,_this2.handleFatalException(error,hint,(0,_core.uuidv7)(),new Date())]).then(function(){});};try{this._unsubscribeUncaughtExceptions=(0,_utils.trackUncaughtExceptions)(onUncaughtException);}catch(err){this.logger.warn('Failed to track uncaught exceptions: ',err);}}},{key:"markFatalExceptionHandled",value:function markFatalExceptionHandled(error){var _this3=this;var bridge=_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.markFatalExceptionHandled;if(!bridge){return undefined;}try{return Promise.resolve(bridge(fatalMessageKey(error)))["catch"](function(e){_this3.logger.warn("Failed to mark fatal exception as handled: ".concat(e));});}catch(e){this.logger.warn("Failed to mark fatal exception as handled: ".concat(e));return undefined;}}},{key:"handleFatalException",value:function(){var _handleFatalException=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(error,hint,eventUuid,timestamp){var _this4=this;var storageReady,result,_result,queued,nativeCapture,persisted,nativeWrite,_yield$Promise$all,_yield$Promise$all2,persistedOk,_t,_t2,_t3;return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:storageReady=!this.fatalCaptureHooks;if(!this.fatalCaptureHooks){_context.next=4;break;}_context.prev=1;_context.next=2;return this.fatalCaptureHooks.waitForStorageReady();case 2:_t=_context.sent;storageReady=_t===true;_context.next=4;break;case 3:_context.prev=3;_t2=_context["catch"](1);this.logger.warn('Fatal capture skipped because events storage did not initialize.',_t2);case 4:if(!(!storageReady||!this._autocaptureEnabled||this.instance.isDisabled||this.instance.optedOut)){_context.next=5;break;}return _context.abrupt("return");case 5:if(this.fatalCaptureHooks){_context.next=6;break;}this.instance.captureException(error,{$exception_level:'fatal'},hint);return _context.abrupt("return");case 6:_context.prev=6;result=this.fatalCaptureHooks.captureFatalException(error,hint,eventUuid,timestamp,function(queued){return _this4.prepareFatalNativeCapture(queued);});_context.next=8;break;case 7:_context.prev=7;_t3=_context["catch"](6);this.logger.error('Fatal exception capture failed before enqueue.',_t3);return _context.abrupt("return");case 8:_result=result,queued=_result.queued,nativeCapture=_result.nativeCapture;if(!(!queued&&!nativeCapture)){_context.next=9;break;}return _context.abrupt("return");case 9:void this.instance.flush()["catch"](function(){_this4.logger.critical('Failed to flush events');});persisted=this.fatalCaptureHooks.waitForJSPersist();if(nativeCapture){try{nativeWrite=nativeCapture()["catch"](function(e){_this4.logger.warn("Fatal exception native capture failed: ".concat(e));});}catch(e){this.logger.warn("Fatal exception native capture failed: ".concat(e));}}_context.next=10;return Promise.all([persisted,nativeWrite]);case 10:_yield$Promise$all=_context.sent;_yield$Promise$all2=(0,_slicedToArray2["default"])(_yield$Promise$all,1);persistedOk=_yield$Promise$all2[0];if(!persistedOk&&!nativeCapture){this.logger.warn('Fatal exception JS persist failed and no native capture path was available.');}case 11:case"end":return _context.stop();}},_callee,this,[[1,3],[6,7]]);}));function handleFatalException(_x,_x2,_x3,_x4){return _handleFatalException.apply(this,arguments);}return handleFatalException;}()},{key:"prepareFatalNativeCapture",value:function prepareFatalNativeCapture(queuedEvent){var _a,_b;var bridge=_OptionalPlugin.OptionalReactNativePlugin===null||_OptionalPlugin.OptionalReactNativePlugin===void 0?void 0:_OptionalPlugin.OptionalReactNativePlugin.captureFatalException;if(!bridge){return undefined;}if(!((_a=this.fatalCaptureHooks)===null||_a===void 0?void 0:_a.isNativeCaptureReady())){return undefined;}if(((_b=this.fatalCaptureHooks)===null||_b===void 0?void 0:_b.getPersistenceMode())==='memory'){return undefined;}if(this.instance.isDisabled||this.instance.optedOut){return undefined;}var properties=(0,_core.isObject)(queuedEvent.properties)?queuedEvent.properties:{};var payload=(0,_fatalPayload.buildFatalExceptionPayload)({timestamp:(0,_core.isString)(queuedEvent.timestamp)?queuedEvent.timestamp:new Date().toISOString(),distinctId:(0,_core.isString)(queuedEvent.distinct_id)?queuedEvent.distinct_id:'',properties:properties});return function(){return bridge(payload.distinctId,payload.timestamp,payload.properties);};}},{key:"autocaptureUnhandledRejections",value:function autocaptureUnhandledRejections(){var _this5=this;var onUnhandledRejection=function onUnhandledRejection(error){if(!_this5._autocaptureEnabled){return;}if((0,_core.isPostHogFetchNetworkError)(error)){return;}var hint={mechanism:{type:'onunhandledrejection',handled:false}};_this5.instance.captureException(error,{},hint);};try{(0,_utils.trackUnhandledRejections)(onUnhandledRejection);}catch(err){this.logger.warn('Failed to track unhandled rejections: ',err);}}},{key:"autocaptureConsole",value:function autocaptureConsole(levels){var _this6=this;var onConsole=function onConsole(level){return function(error,isFatal,syntheticException){if(!_this6._autocaptureEnabled){return;}var hint={mechanism:{type:'onconsole',handled:true},syntheticException:syntheticException};var additionalProperties={$exception_level:level};_this6.instance.captureException(error,additionalProperties,hint);};};try{var _iterator3=_createForOfIteratorHelper(levels),_step3;try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var level=_step3.value;(0,_utils.trackConsole)(level,onConsole(level));}}catch(err){_iterator3.e(err);}finally{_iterator3.f();}}catch(err){this.logger.warn('Failed to track console errors: ',err);}}},{key:"autocapture",value:function autocapture(autocaptureOptions){if(autocaptureOptions.uncaughtExceptions===true){this.autocaptureUncaughtErrors();}if(autocaptureOptions.unhandledRejections===true){this.autocaptureUnhandledRejections();}if(autocaptureOptions.console.length>0){this.autocaptureConsole(autocaptureOptions.console);}}}]);}();
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_core","require","_utils","_utils2","_OptionalPlugin","_fatalPayload","_createForOfIteratorHelper","r","e","t","Symbol","iterator","Array","isArray","_unsupportedIterableToArray","length","_n","F","s","n","done","value","f","TypeError","o","a","u","call","next","_arrayLikeToArray","toString","slice","constructor","name","from","test","ownKeys","Object","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","defineProperty","LogLevelList","FATAL_MESSAGE_KEY_LENGTH","fatalMessageKey","error","message","Error","namePrefix","concat","startsWith","undefined","String","join","ErrorTracking","exports","instance","options","logger","fatalCaptureHooks","_classCallCheck2","_nativeForwardingEnabled","_autocaptureEnabled","createLogger","resolveOptions","exceptionSteps","_exceptionStepsConfig","CoreErrorTracking","resolveExceptionStepsConfig","enabled","max_bytes","maxBytes","_exceptionStepsBuffer","ExceptionStepsBuffer","autocapture","_createClass2","key","getNativePluginExceptionStepsConfig","addExceptionStep","properties","isString","trim","warn","userProperties","isObject","_CoreErrorTracking$st","stripReservedExceptionStepFields","sanitizedProperties","droppedKeys","add","EXCEPTION_STEP_INTERNAL_FIELDS","MESSAGE","TIMESTAMP","Date","toISOString","forwardExceptionStepToNative","onNativeErrorTrackingReady","_iterator","getAttachableExceptionSteps","_step","step","$message","err","_this","OptionalReactNativePlugin","Promise","resolve","attachExceptionSteps","isNullish","$exception_steps","steps","getAttachable","clearExceptionSteps","clear","shutdown","_a","_unsubscribeUncaughtExceptions","onRemoteConfig","errorTracking","getRemoteConfigBool","info","isUncaughtExceptionAutocaptureEnabled","uncaughtExceptions","autocaptureOptions","resolveAutocaptureOptions","unhandledRejections","console","resolveConsoleOptions","level","includes","autocaptureUncaughtErrors","_this2","onUncaughtException","isFatal","marked","markFatalExceptionHandled","isPostHogFetchNetworkError","hint","mechanism","type","handled","captureException","all","handleFatalException","uuidv7","then","trackUncaughtExceptions","_this3","bridge","_handleFatalException","_asyncToGenerator2","_regenerator","mark","_callee","eventUuid","timestamp","_this4","storageReady","result","_result","queued","nativeCapture","persisted","nativeWrite","_yield$Promise$all","_yield$Promise$all2","persistedOk","_t","_t2","_t3","wrap","_context","prev","waitForStorageReady","sent","isDisabled","optedOut","abrupt","$exception_level","captureFatalException","prepareFatalNativeCapture","flush","critical","waitForJSPersist","_slicedToArray2","stop","_x","_x2","_x3","_x4","queuedEvent","isNativeCaptureReady","_b","getPersistenceMode","payload","buildFatalExceptionPayload","distinctId","distinct_id","autocaptureUnhandledRejections","_this5","onUnhandledRejection","trackUnhandledRejections","autocaptureConsole","levels","_this6","onConsole","syntheticException","additionalProperties","_iterator2","_step2","trackConsole"],"sources":["../../src/error-tracking/index.ts"],"sourcesContent":["import type { PostHog } from '../posthog-rn'\nimport {\n JsonType,\n Logger,\n ErrorTracking as CoreErrorTracking,\n isPostHogFetchNetworkError,\n isNullish,\n isObject,\n isString,\n PostHogEventProperties,\n uuidv7,\n} from '@posthog/core'\nimport { Properties } from '@posthog/types'\nimport { trackConsole, trackUncaughtExceptions, trackUnhandledRejections } from './utils'\nimport { getRemoteConfigBool } from '../utils'\nimport { OptionalReactNativePlugin } from '../optional/OptionalPlugin'\nimport { buildFatalExceptionPayload } from './fatal-payload'\n\ntype LogLevel = 'debug' | 'log' | 'info' | 'warn' | 'error'\n\nconst LogLevelList: LogLevel[] = ['debug', 'log', 'info', 'warn', 'error']\n\n// Native crash reports truncate the JS message (iOS keeps 175 characters, including its own\n// prefix), so the start of the message is what both sides reliably share.\nconst FATAL_MESSAGE_KEY_LENGTH = 80\n\n// The start of the message React Native's ExceptionsManager sends native for this error:\n// `<name>: <message>`, where a thrown non-Error has no name and is converted to a string.\nfunction fatalMessageKey(error: unknown): string {\n let message: string\n if (error instanceof Error) {\n const namePrefix = error.name ? `${error.name}: ` : ''\n message = error.message || ''\n if (!message.startsWith(namePrefix)) {\n message = namePrefix + message\n }\n } else {\n message = error === undefined ? '' : String(error)\n }\n return Array.from(message).slice(0, FATAL_MESSAGE_KEY_LENGTH).join('')\n}\n\n// user provided configuration\ninterface AutocaptureOptions {\n uncaughtExceptions?: boolean\n unhandledRejections?: boolean\n console?: boolean | LogLevel[]\n /**\n * Enables native iOS/Android/macOS crash autocapture through the optional native plugin.\n * On Android this covers Java/Kotlin crashes; native C/C++ (NDK) crashes are enabled with\n * `androidNdkCrashes`. On Apple platforms it covers signal crashes too.\n * Disabled by default. Requires `@posthog/react-native-plugin` installed (2.2.0 or newer for macOS).\n */\n nativeCrashes?: boolean\n /**\n * Enables autocapture of native C/C++ (NDK) crashes on Android, through the optional native\n * plugin. Requires Android 12 (API 31) or later and exception autocapture enabled in the\n * project's error tracking settings.\n *\n * An NDK crash kills the process immediately, so it is captured on the next app launch from\n * the records the OS kept, which means properties such as `$app_version` and the identity\n * describe that launch rather than the crash. The first launch after enabling this also\n * captures the native crashes the OS still holds from before.\n *\n * For readable stack traces, upload the app's `.so` debug symbols. With Expo, set `uploadNativeSymbols`\n * on the `posthog-react-native/expo` config plugin: https://posthog.com/docs/error-tracking/upload-source-maps/react-native#native-crash-symbolication\n *\n * Ignored on other platforms. Disabled by default. Requires `@posthog/react-native-plugin` 2.12.0 or newer.\n */\n androidNdkCrashes?: boolean\n}\n\n/**\n * Controls the breadcrumb-style exception steps recorded via `addExceptionStep` and attached\n * to captured exceptions as `$exception_steps`.\n */\nexport interface ExceptionStepsOptions {\n /**\n * Whether exception steps are recorded and attached.\n * @default true\n */\n enabled?: boolean\n /**\n * Total UTF-8 byte budget (~32KB) for the in-memory buffer. Oldest steps are evicted first when exceeded.\n * @default 32768\n */\n maxBytes?: number\n}\n\nexport interface ErrorTrackingOptions {\n autocapture?: AutocaptureOptions | boolean\n exceptionSteps?: ExceptionStepsOptions\n}\n\n// resolved configuration\ninterface ResolvedAutocaptureOptions {\n uncaughtExceptions: boolean\n unhandledRejections: boolean\n console: LogLevel[]\n}\n\ninterface ResolvedErrorTrackingOptions {\n autocapture: ResolvedAutocaptureOptions\n}\n\n// Hooks supplied by PostHogRN for coordinating the fatal capture with its event storage.\n// Storage readiness is explicit so unknown persisted consent fails closed rather than being\n// mistaken for the in-memory default.\ninterface FatalCaptureHooks {\n // `prepareNativeCapture` is offered the final, before_send-accepted message at the moment\n // it would be enqueued. Returning a thunk transfers ownership of the exception to the\n // native SDK and the JS queue copy is dropped; returning undefined leaves the event in the\n // JS queue as usual. The choice has to be made there, in one step, so a payload that fails\n // to build cannot leave the exception dropped from both queues.\n captureFatalException: (\n error: unknown,\n hint: CoreErrorTracking.EventHint,\n eventUuid: string,\n timestamp: Date,\n prepareNativeCapture: (queued: PostHogEventProperties) => (() => Promise<void>) | undefined\n ) => { queued: boolean; nativeCapture?: () => Promise<void> }\n waitForJSPersist: () => Promise<boolean>\n waitForStorageReady: () => Promise<boolean>\n getPersistenceMode: () => 'memory' | 'file' | undefined\n // Both native SDKs silently no-op a capture before setup() has run. Native init is async\n // and happens after the storage preload, so an early-startup crash can arrive first —\n // exactly the crashes this path exists for. Ownership only transfers once native is up.\n isNativeCaptureReady: () => boolean\n}\n\nexport class ErrorTracking {\n private logger: Logger\n private options: ResolvedErrorTrackingOptions\n private _exceptionStepsConfig: CoreErrorTracking.ResolvedExceptionStepsConfig\n private _exceptionStepsBuffer: CoreErrorTracking.ExceptionStepsBuffer\n private _nativeForwardingEnabled: boolean = false\n private _unsubscribeUncaughtExceptions?: () => void\n\n /**\n * Controls whether autocaptured exceptions are actually sent.\n * When remote config disables error tracking, this is set to false\n * so that installed handlers become no-ops.\n * Defaults to true (don't block locally enabled capture before remote config loads).\n */\n private _autocaptureEnabled: boolean = true\n\n constructor(\n private instance: PostHog,\n options: ErrorTrackingOptions = {},\n logger: Logger,\n private readonly fatalCaptureHooks?: FatalCaptureHooks\n ) {\n this.logger = logger.createLogger('[ErrorTracking]')\n this.options = this.resolveOptions(options)\n const exceptionSteps = options.exceptionSteps\n this._exceptionStepsConfig = CoreErrorTracking.resolveExceptionStepsConfig(\n exceptionSteps ? { enabled: exceptionSteps.enabled, max_bytes: exceptionSteps.maxBytes } : undefined\n )\n this._exceptionStepsBuffer = new CoreErrorTracking.ExceptionStepsBuffer(this._exceptionStepsConfig)\n this.autocapture(this.options.autocapture)\n }\n\n /**\n * Exception-steps config in the native plugin's shape, so the embedded native SDK keeps one\n * logical buffer with the same byte budget and enabled state.\n */\n getNativePluginExceptionStepsConfig(): ExceptionStepsOptions {\n return { enabled: this._exceptionStepsConfig.enabled, maxBytes: this._exceptionStepsConfig.max_bytes }\n }\n\n /**\n * Records a breadcrumb-style exception step in the instance buffer and mirrors it to the embedded\n * native SDK. The `$timestamp` is captured at call time. Invalid messages are ignored with a\n * warning and never throw. The step only reaches native when it was actually buffered.\n */\n addExceptionStep(message: string, properties?: Properties): void {\n if (!this._exceptionStepsConfig.enabled) {\n return\n }\n\n try {\n if (!isString(message) || message.trim().length === 0) {\n this.logger.warn('Ignoring exception step because message must be a non-empty string')\n return\n }\n\n const userProperties = isObject(properties) ? { ...properties } : {}\n const { sanitizedProperties, droppedKeys } = CoreErrorTracking.stripReservedExceptionStepFields(userProperties)\n\n if (droppedKeys.length > 0) {\n this.logger.warn('Ignoring reserved exception step fields', { droppedKeys })\n }\n\n this._exceptionStepsBuffer.add({\n [CoreErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE]: message,\n [CoreErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP]: new Date().toISOString(),\n ...sanitizedProperties,\n })\n this.forwardExceptionStepToNative(message, properties)\n } catch (error) {\n this.logger.error('Failed to add exception step. Ignoring breadcrumb.', error)\n }\n }\n\n /**\n * Native error tracking initializes asynchronously, so steps recorded before then are buffered\n * only in JS. The host calls this once native is ready to enable forwarding and replay the buffer,\n * so a native crash shortly after startup carries the steps recorded before native was ready.\n */\n onNativeErrorTrackingReady(): void {\n this._nativeForwardingEnabled = true\n for (const step of this.getAttachableExceptionSteps()) {\n this.forwardExceptionStepToNative(step.$message, step as Properties)\n }\n }\n\n private forwardExceptionStepToNative(message: string, properties?: Properties): void {\n if (!this._nativeForwardingEnabled || !OptionalReactNativePlugin?.addExceptionStep) {\n return\n }\n try {\n // Fire-and-forget: the native layer validates and buffers independently and must never block.\n void Promise.resolve(OptionalReactNativePlugin.addExceptionStep(message, properties)).catch((e) => {\n this.logger.warn(`Failed to forward exception step to native: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Failed to forward exception step to native: ${e}`)\n }\n }\n\n /**\n * Returns `properties` with a snapshot of the buffered steps attached as `$exception_steps`,\n * unless the feature is disabled, the caller already provided that key, or the buffer is empty.\n * The buffer is left intact so subsequent exceptions read the same steps.\n */\n attachExceptionSteps(properties: PostHogEventProperties): PostHogEventProperties {\n if (!this._exceptionStepsConfig.enabled || !isNullish(properties.$exception_steps)) {\n return properties\n }\n const steps = this.getAttachableExceptionSteps()\n if (steps.length === 0) {\n return properties\n }\n // Steps are already normalized to their JSON-safe wire form by the buffer.\n return { ...properties, $exception_steps: steps as unknown as JsonType }\n }\n\n /**\n * Snapshot of the buffered steps (oldest first), or an empty array when disabled or empty.\n */\n getAttachableExceptionSteps(): CoreErrorTracking.ExceptionStep[] {\n if (!this._exceptionStepsConfig.enabled) {\n return []\n }\n try {\n return this._exceptionStepsBuffer.getAttachable()\n } catch (error) {\n this.logger.error('Failed to read buffered exception steps.', error)\n return []\n }\n }\n\n /**\n * Clears the buffer. Called on SDK close, not on capture or identity changes.\n */\n clearExceptionSteps(): void {\n this._exceptionStepsBuffer.clear()\n }\n\n shutdown(): void {\n this._autocaptureEnabled = false\n this._unsubscribeUncaughtExceptions?.()\n this._unsubscribeUncaughtExceptions = undefined\n this.clearExceptionSteps()\n }\n\n /**\n * Called when remote config is loaded.\n * If errorTracking.autocaptureExceptions is explicitly false, autocapture is disabled.\n * If it's true or undefined (not yet loaded / not present), autocapture follows local config.\n */\n onRemoteConfig(errorTracking: boolean | { [key: string]: JsonType } | undefined): void {\n if (errorTracking == null) {\n // Remote config doesn't include errorTracking — don't change anything\n return\n }\n\n // Default to false: if remote config is present but the key is missing, disable autocapture\n this._autocaptureEnabled = getRemoteConfigBool(errorTracking, 'autocaptureExceptions', false)\n\n this.logger.info(\n `Error tracking autocapture ${this._autocaptureEnabled ? 'enabled' : 'disabled'} by remote config.`\n )\n }\n\n /**\n * Whether the app asked for fatal JavaScript exceptions to be autocaptured. This is the\n * locally configured value, deliberately not gated on the remote kill-switch: it decides\n * whether the native SDK is worth initializing, and that happens before remote config has\n * been fetched.\n */\n isUncaughtExceptionAutocaptureEnabled(): boolean {\n return this.options.autocapture.uncaughtExceptions\n }\n\n private resolveOptions(options: ErrorTrackingOptions): ResolvedErrorTrackingOptions {\n const autocaptureOptions = this.resolveAutocaptureOptions(options.autocapture)\n return {\n autocapture: autocaptureOptions,\n }\n }\n\n private resolveAutocaptureOptions(autocapture: AutocaptureOptions | boolean = false): ResolvedAutocaptureOptions {\n if (typeof autocapture === 'boolean') {\n return {\n uncaughtExceptions: autocapture,\n unhandledRejections: autocapture,\n console: [],\n }\n }\n return {\n uncaughtExceptions: !!autocapture.uncaughtExceptions,\n unhandledRejections: !!autocapture.unhandledRejections,\n console: this.resolveConsoleOptions(autocapture.console),\n }\n }\n\n private resolveConsoleOptions(console: boolean | LogLevel[] = false): LogLevel[] {\n if (typeof console === 'boolean') {\n return console ? ['error'] : []\n }\n return Array.isArray(console) ? console.filter((level) => LogLevelList.includes(level)) : []\n }\n\n private autocaptureUncaughtErrors() {\n const onUncaughtException = (error: unknown, isFatal: boolean): void | Promise<void> => {\n const marked = isFatal ? this.markFatalExceptionHandled(error) : undefined\n if (!this._autocaptureEnabled || isPostHogFetchNetworkError(error)) {\n return marked\n }\n const hint: CoreErrorTracking.EventHint = {\n mechanism: { type: 'onuncaughtexception', handled: false },\n }\n if (!isFatal) {\n this.instance.captureException(error, {}, hint)\n return\n }\n return Promise.all([marked, this.handleFatalException(error, hint, uuidv7(), new Date())]).then(() => {})\n }\n try {\n this._unsubscribeUncaughtExceptions = trackUncaughtExceptions(onUncaughtException)\n } catch (err) {\n this.logger.warn('Failed to track uncaught exceptions: ', err)\n }\n }\n\n // React Native turns this fatal into a native crash once the handler chain finishes. The\n // native plugin drops that crash report only when it contains the message marked here, so\n // fatals that bypass this handler (React render errors) still reach error tracking.\n private markFatalExceptionHandled(error: unknown): Promise<void> | undefined {\n const bridge = OptionalReactNativePlugin?.markFatalExceptionHandled\n if (!bridge) {\n return undefined\n }\n try {\n return Promise.resolve(bridge(fatalMessageKey(error))).catch((e) => {\n this.logger.warn(`Failed to mark fatal exception as handled: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Failed to mark fatal exception as handled: ${e}`)\n return undefined\n }\n }\n\n private async handleFatalException(\n error: unknown,\n hint: CoreErrorTracking.EventHint,\n eventUuid: string,\n timestamp: Date\n ): Promise<void> {\n let storageReady = !this.fatalCaptureHooks\n if (this.fatalCaptureHooks) {\n try {\n storageReady = (await this.fatalCaptureHooks.waitForStorageReady()) === true\n } catch (e) {\n this.logger.warn('Fatal capture skipped because events storage did not initialize.', e)\n }\n }\n // Unknown consent must fail closed. A crash is less important than persisting data\n // for a user whose opt-out state could not be loaded.\n if (!storageReady || !this._autocaptureEnabled || this.instance.isDisabled || this.instance.optedOut) {\n return\n }\n\n if (!this.fatalCaptureHooks) {\n this.instance.captureException(error, { $exception_level: 'fatal' as CoreErrorTracking.SeverityLevel }, hint)\n return\n }\n\n // Hand the final payload to the native SDK. Both native SDKs recognise a `$exception`\n // with `$exception_level: 'fatal'` and write it to their own disk queue synchronously\n // before returning, which is the durability the JS queue cannot promise while\n // AsyncStorage is still draining. Native owns delivery from there, including retry\n // across the relaunch, so there is nothing for the next launch to recover — and the JS\n // queue copy is dropped so the exception is not sent twice.\n let result: { queued: boolean; nativeCapture?: () => Promise<void> }\n try {\n result = this.fatalCaptureHooks.captureFatalException(error, hint, eventUuid, timestamp, (queued) =>\n this.prepareFatalNativeCapture(queued)\n )\n } catch (e) {\n // Without the final queued event we cannot know whether before_send accepted or\n // redacted the exception, so sending a raw fallback would bypass filtering.\n this.logger.error('Fatal exception capture failed before enqueue.', e)\n return\n }\n const { queued, nativeCapture } = result\n if (!queued && !nativeCapture) {\n // before_send dropped it.\n return\n }\n\n void this.instance.flush().catch(() => {\n this.logger.critical('Failed to flush events')\n })\n // Other events may still be queued behind this one, so the JS store is still worth\n // draining even when native owns the exception itself.\n const persisted = this.fatalCaptureHooks.waitForJSPersist()\n let nativeWrite: Promise<void> | undefined\n if (nativeCapture) {\n try {\n nativeWrite = nativeCapture().catch((e) => {\n this.logger.warn(`Fatal exception native capture failed: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Fatal exception native capture failed: ${e}`)\n }\n }\n const [persistedOk] = await Promise.all([persisted, nativeWrite])\n if (!persistedOk && !nativeCapture) {\n this.logger.warn('Fatal exception JS persist failed and no native capture path was available.')\n }\n }\n\n private prepareFatalNativeCapture(queuedEvent: PostHogEventProperties): (() => Promise<void>) | undefined {\n const bridge = OptionalReactNativePlugin?.captureFatalException\n if (!bridge) {\n return undefined\n }\n // Handing the event to a native SDK that is not set up yet would drop it: native\n // no-ops the capture, and the JS queue copy has already been given up.\n if (!this.fatalCaptureHooks?.isNativeCaptureReady()) {\n return undefined\n }\n // Memory-persistence apps asked for nothing on disk. The native queue is disk-backed,\n // so honour that here rather than routing around it.\n if (this.fatalCaptureHooks?.getPersistenceMode() === 'memory') {\n return undefined\n }\n if (this.instance.isDisabled || this.instance.optedOut) {\n return undefined\n }\n\n const properties = isObject(queuedEvent.properties) ? (queuedEvent.properties as PostHogEventProperties) : {}\n const payload = buildFatalExceptionPayload({\n timestamp: isString(queuedEvent.timestamp) ? queuedEvent.timestamp : new Date().toISOString(),\n distinctId: isString(queuedEvent.distinct_id) ? queuedEvent.distinct_id : '',\n // The event was normalized and emitted only after before_send accepted it.\n properties,\n })\n return () => bridge(payload.distinctId, payload.timestamp, payload.properties)\n }\n\n private autocaptureUnhandledRejections() {\n const onUnhandledRejection = (error: unknown) => {\n // Gate on remote config — if remotely disabled, don't capture\n if (!this._autocaptureEnabled) {\n return\n }\n\n // Offline/timeout failures are expected, not application errors.\n if (isPostHogFetchNetworkError(error)) {\n return\n }\n\n const hint: CoreErrorTracking.EventHint = {\n mechanism: {\n type: 'onunhandledrejection',\n handled: false,\n },\n }\n this.instance.captureException(error, {}, hint)\n }\n\n try {\n trackUnhandledRejections(onUnhandledRejection)\n } catch (err) {\n this.logger.warn('Failed to track unhandled rejections: ', err)\n }\n }\n\n private autocaptureConsole(levels: LogLevel[]) {\n const onConsole = (level: LogLevel) => (error: unknown, isFatal: boolean, syntheticException?: Error) => {\n // Gate on remote config — if remotely disabled, don't capture\n if (!this._autocaptureEnabled) {\n return\n }\n\n const hint: CoreErrorTracking.EventHint = {\n mechanism: {\n type: 'onconsole',\n handled: true,\n },\n syntheticException,\n }\n const additionalProperties = {\n $exception_level: level as CoreErrorTracking.SeverityLevel,\n }\n this.instance.captureException(error, additionalProperties, hint)\n }\n\n try {\n for (const level of levels) {\n trackConsole(level, onConsole(level))\n }\n } catch (err) {\n this.logger.warn('Failed to track console errors: ', err)\n }\n }\n\n private autocapture(autocaptureOptions: ResolvedAutocaptureOptions) {\n if (autocaptureOptions.uncaughtExceptions === true) {\n this.autocaptureUncaughtErrors()\n }\n if (autocaptureOptions.unhandledRejections === true) {\n this.autocaptureUnhandledRejections()\n }\n if (autocaptureOptions.console.length > 0) {\n this.autocaptureConsole(autocaptureOptions.console)\n }\n }\n}\n"],"mappings":"utBACA,IAAAA,KAAA,CAAAC,OAAA,kBAYA,IAAAC,MAAA,CAAAD,OAAA,YACA,IAAAE,OAAA,CAAAF,OAAA,aACA,IAAAG,eAAA,CAAAH,OAAA,+BACA,IAAAI,aAAA,CAAAJ,OAAA,oBAA4D,SAAAK,2BAAAC,CAAA,CAAAC,CAAA,MAAAC,CAAA,qBAAAC,MAAA,EAAAH,CAAA,CAAAG,MAAA,CAAAC,QAAA,GAAAJ,CAAA,mBAAAE,CAAA,KAAAG,KAAA,CAAAC,OAAA,CAAAN,CAAA,IAAAE,CAAA,CAAAK,2BAAA,CAAAP,CAAA,IAAAC,CAAA,EAAAD,CAAA,mBAAAA,CAAA,CAAAQ,MAAA,EAAAN,CAAA,GAAAF,CAAA,CAAAE,CAAA,MAAAO,EAAA,GAAAC,CAAA,UAAAA,EAAA,WAAAC,CAAA,CAAAD,CAAA,CAAAE,CAAA,UAAAA,EAAA,SAAAH,EAAA,EAAAT,CAAA,CAAAQ,MAAA,EAAAK,IAAA,MAAAA,IAAA,IAAAC,KAAA,CAAAd,CAAA,CAAAS,EAAA,OAAAR,CAAA,UAAAA,EAAAD,CAAA,QAAAA,CAAA,GAAAe,CAAA,CAAAL,CAAA,aAAAM,SAAA,+IAAAC,CAAA,CAAAC,CAAA,IAAAC,CAAA,WAAAR,CAAA,UAAAA,EAAA,EAAAT,CAAA,CAAAA,CAAA,CAAAkB,IAAA,CAAApB,CAAA,IAAAY,CAAA,UAAAA,EAAA,MAAAZ,CAAA,CAAAE,CA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AI3E,kBAAkB,CAACG,OAAO,CAACzH,MAAM,CAAG,CAAC,CAAE,CACzC,IAAI,CAACqM,kBAAkB,CAAC/E,kBAAkB,CAACG,OAAO,CAAC,CACrD,CACF,CAAC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_core","require","_surveys","_utils","_utils2","_OptionalPlugin","_fatalPayload","_createForOfIteratorHelper","r","e","t","Symbol","iterator","Array","isArray","_unsupportedIterableToArray","length","_n","F","s","n","done","value","f","TypeError","o","a","u","call","next","_arrayLikeToArray","toString","slice","constructor","name","from","test","ownKeys","Object","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","enumerable","push","apply","_objectSpread","arguments","forEach","_defineProperty2","getOwnPropertyDescriptors","defineProperties","defineProperty","LogLevelList","FATAL_MESSAGE_KEY_LENGTH","fatalMessageKey","error","message","Error","namePrefix","concat","startsWith","undefined","String","join","parseSuppressionRules","errorTracking","rules","isObject","suppressionRules","rule","values","ErrorTracking","exports","instance","options","logger","fatalCaptureHooks","_classCallCheck2","_nativeForwardingEnabled","_autocaptureEnabled","_suppressionRules","createLogger","resolveOptions","exceptionSteps","_exceptionStepsConfig","CoreErrorTracking","resolveExceptionStepsConfig","enabled","max_bytes","maxBytes","_exceptionStepsBuffer","ExceptionStepsBuffer","autocapture","_createClass2","key","getNativePluginExceptionStepsConfig","addExceptionStep","properties","isString","trim","warn","userProperties","_CoreErrorTracking$st","stripReservedExceptionStepFields","sanitizedProperties","droppedKeys","add","EXCEPTION_STEP_INTERNAL_FIELDS","MESSAGE","TIMESTAMP","Date","toISOString","forwardExceptionStepToNative","onNativeErrorTrackingReady","_iterator","getAttachableExceptionSteps","_step","step","$message","err","_this","OptionalReactNativePlugin","Promise","resolve","attachExceptionSteps","isNullish","$exception_steps","steps","getAttachable","clearExceptionSteps","clear","shouldSuppressException","exceptionList","exceptionValues","$exception_types","$exception_values","_iterator2","_step2","exception","type","matched","some","results","map","v","compare","propertyComparisons","operator","targets","Boolean","every","shutdown","_a","_unsubscribeUncaughtExceptions","onRemoteConfig","getRemoteConfigBool","info","isUncaughtExceptionAutocaptureEnabled","uncaughtExceptions","autocaptureOptions","resolveAutocaptureOptions","unhandledRejections","console","resolveConsoleOptions","level","includes","autocaptureUncaughtErrors","_this2","onUncaughtException","isFatal","marked","markFatalExceptionHandled","isPostHogFetchNetworkError","hint","mechanism","handled","captureException","all","handleFatalException","uuidv7","then","trackUncaughtExceptions","_this3","bridge","_handleFatalException","_asyncToGenerator2","_regenerator","mark","_callee","eventUuid","timestamp","_this4","storageReady","result","_result","queued","nativeCapture","persisted","nativeWrite","_yield$Promise$all","_yield$Promise$all2","persistedOk","_t","_t2","_t3","wrap","_context","prev","waitForStorageReady","sent","isDisabled","optedOut","abrupt","$exception_level","captureFatalException","prepareFatalNativeCapture","flush","critical","waitForJSPersist","_slicedToArray2","stop","_x","_x2","_x3","_x4","queuedEvent","isNativeCaptureReady","_b","getPersistenceMode","payload","buildFatalExceptionPayload","distinctId","distinct_id","autocaptureUnhandledRejections","_this5","onUnhandledRejection","trackUnhandledRejections","autocaptureConsole","levels","_this6","onConsole","syntheticException","additionalProperties","_iterator3","_step3","trackConsole"],"sources":["../../src/error-tracking/index.ts"],"sourcesContent":["import type { PostHog } from '../posthog-rn'\nimport {\n JsonType,\n Logger,\n ErrorTracking as CoreErrorTracking,\n isPostHogFetchNetworkError,\n isArray,\n isNullish,\n isObject,\n isString,\n PostHogEventProperties,\n PropertyMatchType,\n uuidv7,\n} from '@posthog/core'\nimport { propertyComparisons } from '@posthog/core/surveys'\nimport { Properties } from '@posthog/types'\nimport { trackConsole, trackUncaughtExceptions, trackUnhandledRejections } from './utils'\nimport { getRemoteConfigBool } from '../utils'\nimport { OptionalReactNativePlugin } from '../optional/OptionalPlugin'\nimport { buildFatalExceptionPayload } from './fatal-payload'\n\ntype LogLevel = 'debug' | 'log' | 'info' | 'warn' | 'error'\n\nconst LogLevelList: LogLevel[] = ['debug', 'log', 'info', 'warn', 'error']\n\n// Native crash reports truncate the JS message (iOS keeps 175 characters, including its own\n// prefix), so the start of the message is what both sides reliably share.\nconst FATAL_MESSAGE_KEY_LENGTH = 80\n\n// The start of the message React Native's ExceptionsManager sends native for this error:\n// `<name>: <message>`, where a thrown non-Error has no name and is converted to a string.\nfunction fatalMessageKey(error: unknown): string {\n let message: string\n if (error instanceof Error) {\n const namePrefix = error.name ? `${error.name}: ` : ''\n message = error.message || ''\n if (!message.startsWith(namePrefix)) {\n message = namePrefix + message\n }\n } else {\n message = error === undefined ? '' : String(error)\n }\n return Array.from(message).slice(0, FATAL_MESSAGE_KEY_LENGTH).join('')\n}\n\n// user provided configuration\ninterface AutocaptureOptions {\n uncaughtExceptions?: boolean\n unhandledRejections?: boolean\n console?: boolean | LogLevel[]\n /**\n * Enables native iOS/Android/macOS crash autocapture through the optional native plugin.\n * On Android this covers Java/Kotlin crashes; native C/C++ (NDK) crashes are enabled with\n * `androidNdkCrashes`. On Apple platforms it covers signal crashes too.\n * Disabled by default. Requires `@posthog/react-native-plugin` installed (2.2.0 or newer for macOS).\n */\n nativeCrashes?: boolean\n /**\n * Enables autocapture of native C/C++ (NDK) crashes on Android, through the optional native\n * plugin. Requires Android 12 (API 31) or later and exception autocapture enabled in the\n * project's error tracking settings.\n *\n * An NDK crash kills the process immediately, so it is captured on the next app launch from\n * the records the OS kept, which means properties such as `$app_version` and the identity\n * describe that launch rather than the crash. The first launch after enabling this also\n * captures the native crashes the OS still holds from before.\n *\n * For readable stack traces, upload the app's `.so` debug symbols. With Expo, set `uploadNativeSymbols`\n * on the `posthog-react-native/expo` config plugin: https://posthog.com/docs/error-tracking/upload-source-maps/react-native#native-crash-symbolication\n *\n * Ignored on other platforms. Disabled by default. Requires `@posthog/react-native-plugin` 2.12.0 or newer.\n */\n androidNdkCrashes?: boolean\n}\n\n/**\n * Controls the breadcrumb-style exception steps recorded via `addExceptionStep` and attached\n * to captured exceptions as `$exception_steps`.\n */\nexport interface ExceptionStepsOptions {\n /**\n * Whether exception steps are recorded and attached.\n * @default true\n */\n enabled?: boolean\n /**\n * Total UTF-8 byte budget (~32KB) for the in-memory buffer. Oldest steps are evicted first when exceeded.\n * @default 32768\n */\n maxBytes?: number\n}\n\nexport interface ErrorTrackingOptions {\n autocapture?: AutocaptureOptions | boolean\n exceptionSteps?: ExceptionStepsOptions\n}\n\n// resolved configuration\ninterface ResolvedAutocaptureOptions {\n uncaughtExceptions: boolean\n unhandledRejections: boolean\n console: LogLevel[]\n}\n\ninterface ResolvedErrorTrackingOptions {\n autocapture: ResolvedAutocaptureOptions\n}\n\n// Same shape as the browser SDK's ErrorTrackingSuppressionRule, delivered in remote config as\n// `errorTracking.suppressionRules`.\ninterface ErrorTrackingSuppressionRule {\n type: 'AND' | 'OR'\n values: {\n key: '$exception_types' | '$exception_values'\n operator: PropertyMatchType\n value: string | string[]\n }[]\n}\n\nfunction parseSuppressionRules(errorTracking: boolean | { [key: string]: JsonType }): ErrorTrackingSuppressionRule[] {\n const rules = isObject(errorTracking) ? errorTracking.suppressionRules : undefined\n if (!isArray(rules)) {\n return []\n }\n return rules.filter((rule) => isObject(rule) && isArray(rule.values)) as unknown as ErrorTrackingSuppressionRule[]\n}\n\n// Hooks supplied by PostHogRN for coordinating the fatal capture with its event storage.\n// Storage readiness is explicit so unknown persisted consent fails closed rather than being\n// mistaken for the in-memory default.\ninterface FatalCaptureHooks {\n // `prepareNativeCapture` is offered the final, before_send-accepted message at the moment\n // it would be enqueued. Returning a thunk transfers ownership of the exception to the\n // native SDK and the JS queue copy is dropped; returning undefined leaves the event in the\n // JS queue as usual. The choice has to be made there, in one step, so a payload that fails\n // to build cannot leave the exception dropped from both queues.\n captureFatalException: (\n error: unknown,\n hint: CoreErrorTracking.EventHint,\n eventUuid: string,\n timestamp: Date,\n prepareNativeCapture: (queued: PostHogEventProperties) => (() => Promise<void>) | undefined\n ) => { queued: boolean; nativeCapture?: () => Promise<void> }\n waitForJSPersist: () => Promise<boolean>\n waitForStorageReady: () => Promise<boolean>\n getPersistenceMode: () => 'memory' | 'file' | undefined\n // Both native SDKs silently no-op a capture before setup() has run. Native init is async\n // and happens after the storage preload, so an early-startup crash can arrive first —\n // exactly the crashes this path exists for. Ownership only transfers once native is up.\n isNativeCaptureReady: () => boolean\n}\n\nexport class ErrorTracking {\n private logger: Logger\n private options: ResolvedErrorTrackingOptions\n private _exceptionStepsConfig: CoreErrorTracking.ResolvedExceptionStepsConfig\n private _exceptionStepsBuffer: CoreErrorTracking.ExceptionStepsBuffer\n private _nativeForwardingEnabled: boolean = false\n private _unsubscribeUncaughtExceptions?: () => void\n\n /**\n * Controls whether autocaptured exceptions are actually sent.\n * When remote config disables error tracking, this is set to false\n * so that installed handlers become no-ops.\n * Defaults to true (don't block locally enabled capture before remote config loads).\n */\n private _autocaptureEnabled: boolean = true\n\n // Kept in memory only: the remote config they come from is already persisted and replayed\n // through onRemoteConfig at startup.\n private _suppressionRules: ErrorTrackingSuppressionRule[] = []\n\n constructor(\n private instance: PostHog,\n options: ErrorTrackingOptions = {},\n logger: Logger,\n private readonly fatalCaptureHooks?: FatalCaptureHooks\n ) {\n this.logger = logger.createLogger('[ErrorTracking]')\n this.options = this.resolveOptions(options)\n const exceptionSteps = options.exceptionSteps\n this._exceptionStepsConfig = CoreErrorTracking.resolveExceptionStepsConfig(\n exceptionSteps ? { enabled: exceptionSteps.enabled, max_bytes: exceptionSteps.maxBytes } : undefined\n )\n this._exceptionStepsBuffer = new CoreErrorTracking.ExceptionStepsBuffer(this._exceptionStepsConfig)\n this.autocapture(this.options.autocapture)\n }\n\n /**\n * Exception-steps config in the native plugin's shape, so the embedded native SDK keeps one\n * logical buffer with the same byte budget and enabled state.\n */\n getNativePluginExceptionStepsConfig(): ExceptionStepsOptions {\n return { enabled: this._exceptionStepsConfig.enabled, maxBytes: this._exceptionStepsConfig.max_bytes }\n }\n\n /**\n * Records a breadcrumb-style exception step in the instance buffer and mirrors it to the embedded\n * native SDK. The `$timestamp` is captured at call time. Invalid messages are ignored with a\n * warning and never throw. The step only reaches native when it was actually buffered.\n */\n addExceptionStep(message: string, properties?: Properties): void {\n if (!this._exceptionStepsConfig.enabled) {\n return\n }\n\n try {\n if (!isString(message) || message.trim().length === 0) {\n this.logger.warn('Ignoring exception step because message must be a non-empty string')\n return\n }\n\n const userProperties = isObject(properties) ? { ...properties } : {}\n const { sanitizedProperties, droppedKeys } = CoreErrorTracking.stripReservedExceptionStepFields(userProperties)\n\n if (droppedKeys.length > 0) {\n this.logger.warn('Ignoring reserved exception step fields', { droppedKeys })\n }\n\n this._exceptionStepsBuffer.add({\n [CoreErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE]: message,\n [CoreErrorTracking.EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP]: new Date().toISOString(),\n ...sanitizedProperties,\n })\n this.forwardExceptionStepToNative(message, properties)\n } catch (error) {\n this.logger.error('Failed to add exception step. Ignoring breadcrumb.', error)\n }\n }\n\n /**\n * Native error tracking initializes asynchronously, so steps recorded before then are buffered\n * only in JS. The host calls this once native is ready to enable forwarding and replay the buffer,\n * so a native crash shortly after startup carries the steps recorded before native was ready.\n */\n onNativeErrorTrackingReady(): void {\n this._nativeForwardingEnabled = true\n for (const step of this.getAttachableExceptionSteps()) {\n this.forwardExceptionStepToNative(step.$message, step as Properties)\n }\n }\n\n private forwardExceptionStepToNative(message: string, properties?: Properties): void {\n if (!this._nativeForwardingEnabled || !OptionalReactNativePlugin?.addExceptionStep) {\n return\n }\n try {\n // Fire-and-forget: the native layer validates and buffers independently and must never block.\n void Promise.resolve(OptionalReactNativePlugin.addExceptionStep(message, properties)).catch((e) => {\n this.logger.warn(`Failed to forward exception step to native: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Failed to forward exception step to native: ${e}`)\n }\n }\n\n /**\n * Returns `properties` with a snapshot of the buffered steps attached as `$exception_steps`,\n * unless the feature is disabled, the caller already provided that key, or the buffer is empty.\n * The buffer is left intact so subsequent exceptions read the same steps.\n */\n attachExceptionSteps(properties: PostHogEventProperties): PostHogEventProperties {\n if (!this._exceptionStepsConfig.enabled || !isNullish(properties.$exception_steps)) {\n return properties\n }\n const steps = this.getAttachableExceptionSteps()\n if (steps.length === 0) {\n return properties\n }\n // Steps are already normalized to their JSON-safe wire form by the buffer.\n return { ...properties, $exception_steps: steps as unknown as JsonType }\n }\n\n /**\n * Snapshot of the buffered steps (oldest first), or an empty array when disabled or empty.\n */\n getAttachableExceptionSteps(): CoreErrorTracking.ExceptionStep[] {\n if (!this._exceptionStepsConfig.enabled) {\n return []\n }\n try {\n return this._exceptionStepsBuffer.getAttachable()\n } catch (error) {\n this.logger.error('Failed to read buffered exception steps.', error)\n return []\n }\n }\n\n /**\n * Clears the buffer. Called on SDK close, not on capture or identity changes.\n */\n clearExceptionSteps(): void {\n this._exceptionStepsBuffer.clear()\n }\n\n /**\n * Whether an exception matches one of the suppression rules from remote config, in which case\n * it should be dropped instead of captured. Mirrors the browser SDK. Records an exception step\n * when it matches, so the next captured exception shows that one was dropped.\n */\n shouldSuppressException(exceptionList: unknown): boolean {\n if (!isArray(exceptionList) || exceptionList.length === 0 || this._suppressionRules.length === 0) {\n return false\n }\n\n try {\n const exceptionValues: Record<string, string[]> = { $exception_types: [], $exception_values: [] }\n for (const exception of exceptionList) {\n if (!isObject(exception)) {\n continue\n }\n if (isString(exception.type) && exception.type.length > 0) {\n exceptionValues.$exception_types.push(exception.type)\n }\n if (isString(exception.value) && exception.value.length > 0) {\n exceptionValues.$exception_values.push(exception.value)\n }\n }\n\n const matched = this._suppressionRules.some((rule) => {\n const results = rule.values.map((v) => {\n const compare = propertyComparisons[v.operator]\n const values = exceptionValues[v.key]\n if (!compare || !values) {\n return false\n }\n const targets = isArray(v.value) ? v.value : [v.value]\n return targets.length > 0 ? compare(targets, values) : false\n })\n return rule.type === 'OR' ? results.some(Boolean) : results.every(Boolean)\n })\n\n if (matched) {\n this.addExceptionStep('Exception dropped: matched a suppression rule')\n }\n return matched\n } catch (error) {\n // Suppression only ever filters what we capture, so failing to evaluate it must not cost\n // us the exception.\n this.logger.warn('Failed to evaluate suppression rules. Capturing the exception.', error)\n return false\n }\n }\n\n shutdown(): void {\n this._autocaptureEnabled = false\n this._unsubscribeUncaughtExceptions?.()\n this._unsubscribeUncaughtExceptions = undefined\n this.clearExceptionSteps()\n }\n\n /**\n * Called when remote config is loaded.\n * If errorTracking.autocaptureExceptions is explicitly false, autocapture is disabled.\n * If it's true or undefined (not yet loaded / not present), autocapture follows local config.\n * errorTracking.suppressionRules replaces the current rules; a response without them clears them.\n */\n onRemoteConfig(errorTracking: boolean | { [key: string]: JsonType } | undefined): void {\n if (errorTracking == null) {\n // Remote config doesn't include errorTracking — don't change anything\n return\n }\n\n // Default to false: if remote config is present but the key is missing, disable autocapture\n this._autocaptureEnabled = getRemoteConfigBool(errorTracking, 'autocaptureExceptions', false)\n this._suppressionRules = parseSuppressionRules(errorTracking)\n\n this.logger.info(\n `Error tracking autocapture ${this._autocaptureEnabled ? 'enabled' : 'disabled'} by remote config.`\n )\n }\n\n /**\n * Whether the app asked for fatal JavaScript exceptions to be autocaptured. This is the\n * locally configured value, deliberately not gated on the remote kill-switch: it decides\n * whether the native SDK is worth initializing, and that happens before remote config has\n * been fetched.\n */\n isUncaughtExceptionAutocaptureEnabled(): boolean {\n return this.options.autocapture.uncaughtExceptions\n }\n\n private resolveOptions(options: ErrorTrackingOptions): ResolvedErrorTrackingOptions {\n const autocaptureOptions = this.resolveAutocaptureOptions(options.autocapture)\n return {\n autocapture: autocaptureOptions,\n }\n }\n\n private resolveAutocaptureOptions(autocapture: AutocaptureOptions | boolean = false): ResolvedAutocaptureOptions {\n if (typeof autocapture === 'boolean') {\n return {\n uncaughtExceptions: autocapture,\n unhandledRejections: autocapture,\n console: [],\n }\n }\n return {\n uncaughtExceptions: !!autocapture.uncaughtExceptions,\n unhandledRejections: !!autocapture.unhandledRejections,\n console: this.resolveConsoleOptions(autocapture.console),\n }\n }\n\n private resolveConsoleOptions(console: boolean | LogLevel[] = false): LogLevel[] {\n if (typeof console === 'boolean') {\n return console ? ['error'] : []\n }\n return Array.isArray(console) ? console.filter((level) => LogLevelList.includes(level)) : []\n }\n\n private autocaptureUncaughtErrors() {\n const onUncaughtException = (error: unknown, isFatal: boolean): void | Promise<void> => {\n const marked = isFatal ? this.markFatalExceptionHandled(error) : undefined\n if (!this._autocaptureEnabled || isPostHogFetchNetworkError(error)) {\n return marked\n }\n const hint: CoreErrorTracking.EventHint = {\n mechanism: { type: 'onuncaughtexception', handled: false },\n }\n if (!isFatal) {\n this.instance.captureException(error, {}, hint)\n return\n }\n return Promise.all([marked, this.handleFatalException(error, hint, uuidv7(), new Date())]).then(() => {})\n }\n try {\n this._unsubscribeUncaughtExceptions = trackUncaughtExceptions(onUncaughtException)\n } catch (err) {\n this.logger.warn('Failed to track uncaught exceptions: ', err)\n }\n }\n\n // React Native turns this fatal into a native crash once the handler chain finishes. The\n // native plugin drops that crash report only when it contains the message marked here, so\n // fatals that bypass this handler (React render errors) still reach error tracking.\n private markFatalExceptionHandled(error: unknown): Promise<void> | undefined {\n const bridge = OptionalReactNativePlugin?.markFatalExceptionHandled\n if (!bridge) {\n return undefined\n }\n try {\n return Promise.resolve(bridge(fatalMessageKey(error))).catch((e) => {\n this.logger.warn(`Failed to mark fatal exception as handled: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Failed to mark fatal exception as handled: ${e}`)\n return undefined\n }\n }\n\n private async handleFatalException(\n error: unknown,\n hint: CoreErrorTracking.EventHint,\n eventUuid: string,\n timestamp: Date\n ): Promise<void> {\n let storageReady = !this.fatalCaptureHooks\n if (this.fatalCaptureHooks) {\n try {\n storageReady = (await this.fatalCaptureHooks.waitForStorageReady()) === true\n } catch (e) {\n this.logger.warn('Fatal capture skipped because events storage did not initialize.', e)\n }\n }\n // Unknown consent must fail closed. A crash is less important than persisting data\n // for a user whose opt-out state could not be loaded.\n if (!storageReady || !this._autocaptureEnabled || this.instance.isDisabled || this.instance.optedOut) {\n return\n }\n\n if (!this.fatalCaptureHooks) {\n this.instance.captureException(error, { $exception_level: 'fatal' as CoreErrorTracking.SeverityLevel }, hint)\n return\n }\n\n // Hand the final payload to the native SDK. Both native SDKs recognise a `$exception`\n // with `$exception_level: 'fatal'` and write it to their own disk queue synchronously\n // before returning, which is the durability the JS queue cannot promise while\n // AsyncStorage is still draining. Native owns delivery from there, including retry\n // across the relaunch, so there is nothing for the next launch to recover — and the JS\n // queue copy is dropped so the exception is not sent twice.\n let result: { queued: boolean; nativeCapture?: () => Promise<void> }\n try {\n result = this.fatalCaptureHooks.captureFatalException(error, hint, eventUuid, timestamp, (queued) =>\n this.prepareFatalNativeCapture(queued)\n )\n } catch (e) {\n // Without the final queued event we cannot know whether before_send accepted or\n // redacted the exception, so sending a raw fallback would bypass filtering.\n this.logger.error('Fatal exception capture failed before enqueue.', e)\n return\n }\n const { queued, nativeCapture } = result\n if (!queued && !nativeCapture) {\n // before_send dropped it.\n return\n }\n\n void this.instance.flush().catch(() => {\n this.logger.critical('Failed to flush events')\n })\n // Other events may still be queued behind this one, so the JS store is still worth\n // draining even when native owns the exception itself.\n const persisted = this.fatalCaptureHooks.waitForJSPersist()\n let nativeWrite: Promise<void> | undefined\n if (nativeCapture) {\n try {\n nativeWrite = nativeCapture().catch((e) => {\n this.logger.warn(`Fatal exception native capture failed: ${e}`)\n })\n } catch (e) {\n this.logger.warn(`Fatal exception native capture failed: ${e}`)\n }\n }\n const [persistedOk] = await Promise.all([persisted, nativeWrite])\n if (!persistedOk && !nativeCapture) {\n this.logger.warn('Fatal exception JS persist failed and no native capture path was available.')\n }\n }\n\n private prepareFatalNativeCapture(queuedEvent: PostHogEventProperties): (() => Promise<void>) | undefined {\n const bridge = OptionalReactNativePlugin?.captureFatalException\n if (!bridge) {\n return undefined\n }\n // Handing the event to a native SDK that is not set up yet would drop it: native\n // no-ops the capture, and the JS queue copy has already been given up.\n if (!this.fatalCaptureHooks?.isNativeCaptureReady()) {\n return undefined\n }\n // Memory-persistence apps asked for nothing on disk. The native queue is disk-backed,\n // so honour that here rather than routing around it.\n if (this.fatalCaptureHooks?.getPersistenceMode() === 'memory') {\n return undefined\n }\n if (this.instance.isDisabled || this.instance.optedOut) {\n return undefined\n }\n\n const properties = isObject(queuedEvent.properties) ? (queuedEvent.properties as PostHogEventProperties) : {}\n const payload = buildFatalExceptionPayload({\n timestamp: isString(queuedEvent.timestamp) ? queuedEvent.timestamp : new Date().toISOString(),\n distinctId: isString(queuedEvent.distinct_id) ? queuedEvent.distinct_id : '',\n // The event was normalized and emitted only after before_send accepted it.\n properties,\n })\n return () => bridge(payload.distinctId, payload.timestamp, payload.properties)\n }\n\n private autocaptureUnhandledRejections() {\n const onUnhandledRejection = (error: unknown) => {\n // Gate on remote config — if remotely disabled, don't capture\n if (!this._autocaptureEnabled) {\n return\n }\n\n // Offline/timeout failures are expected, not application errors.\n if (isPostHogFetchNetworkError(error)) {\n return\n }\n\n const hint: CoreErrorTracking.EventHint = {\n mechanism: {\n type: 'onunhandledrejection',\n handled: false,\n },\n }\n this.instance.captureException(error, {}, hint)\n }\n\n try {\n trackUnhandledRejections(onUnhandledRejection)\n } catch (err) {\n this.logger.warn('Failed to track unhandled rejections: ', err)\n }\n }\n\n private autocaptureConsole(levels: LogLevel[]) {\n const onConsole = (level: LogLevel) => (error: unknown, isFatal: boolean, syntheticException?: Error) => {\n // Gate on remote config — if remotely disabled, don't capture\n if (!this._autocaptureEnabled) {\n return\n }\n\n const hint: CoreErrorTracking.EventHint = {\n mechanism: {\n type: 'onconsole',\n handled: true,\n },\n syntheticException,\n }\n const additionalProperties = {\n $exception_level: level as CoreErrorTracking.SeverityLevel,\n }\n this.instance.captureException(error, additionalProperties, hint)\n }\n\n try {\n for (const level of levels) {\n trackConsole(level, onConsole(level))\n }\n } catch (err) {\n this.logger.warn('Failed to track console errors: ', err)\n }\n }\n\n private autocapture(autocaptureOptions: ResolvedAutocaptureOptions) {\n if (autocaptureOptions.uncaughtExceptions === true) {\n this.autocaptureUncaughtErrors()\n }\n if (autocaptureOptions.unhandledRejections === true) {\n this.autocaptureUnhandledRejections()\n }\n if (autocaptureOptions.console.length > 0) {\n this.autocaptureConsole(autocaptureOptions.console)\n }\n }\n}\n"],"mappings":"utBACA,IAAAA,KAAA,CAAAC,OAAA,kBAaA,IAAAC,QAAA,CAAAD,OAAA,0BAEA,IAAAE,MAAA,CAAAF,OAAA,YACA,IAAAG,OAAA,CAAAH,OAAA,aACA,IAAAI,eAAA,CAAAJ,OAAA,+BACA,IAAAK,aAAA,CAAAL,OAAA,oBAA4D,SAAAM,2BAAAC,CAAA,CAAAC,CAAA,MAAAC,CAAA,qBAAAC,MAAA,EAAAH,CAAA,CAAAG,MAAA,CAAAC,QAAA,GAAAJ,CAAA,mBAAAE,CAAA,KAAAG,KAAA,CAAAC,OAAA,CAAAN,CAAA,IAAAE,CAAA,CAAAK,2BAAA,CAAAP,CAAA,IAAAC,CAAA,EAAAD,CAAA,mBAAAA,CAAA,CAAAQ,MAAA,EAAAN,CAAA,GAAAF,CAAA,CAAAE,CAAA,MAAAO,EAAA,GAAAC,CAAA,UAAAA,EAAA,WAAAC,CAAA,CAAAD,CAAA,CAAAE,CAAA,UAAAA,EAAA,SAAAH,EAAA,EAAAT,CAAA,CAAAQ,MAAA,EAAAK,IAAA,MAAAA,IAAA,IAAAC,KAAA,CAAAd,CAAA,CAAAS,EAAA,OAAAR,CAAA,UAAAA,EAAAD,CAAA,QAAAA,CAAA,GAAAe,CAAA,CAAAL,CAAA,aAAAM,SAAA,+IAAAC,CAAA,CAAAC,CAAA,IAAAC,CAAA,WAAAR,CAAA,UAAAA,EAAA,EAAAT,CAAA,CAAAA,CAAA,CAAAkB,IAAA,CAAApB,CAAA,IAAAY,CAAA,UAAAA,EAAA,MAAAZ,CAAA,CAAAE,CAAA,CAAAmB,IAAA,UAAAH,CAAA,CAAAlB,CAAA,CAAAa,IAAA,CAAAb,CAAA,GAAAC,CAAA,UAAAA,EAAAD,CAAA,EAAAmB,CAAA,I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AAE,CAClC,CACA,GAAIP,kBAAkB,CAACE,mBAAmB,GAAK,IAAI,CAAE,CACnD,IAAI,CAACwE,8BAA8B,EAAE,CACvC,CACA,GAAI1E,kBAAkB,CAACG,OAAO,CAACnJ,MAAM,CAAG,CAAC,CAAE,CACzC,IAAI,CAAC8N,kBAAkB,CAAC9E,kBAAkB,CAACG,OAAO,CAAC,CACrD,CACF,CAAC","ignoreList":[]}
@@ -229,6 +229,12 @@ export declare class PostHog extends PostHogCore {
229
229
  private _setDefaultPersonProperties;
230
230
  private _overrideDisplayLanguage;
231
231
  private _requestHeaders;
232
+ /**
233
+ * The project token the client was created with.
234
+ *
235
+ * @deprecated Use `projectToken` instead. This will be removed in the next major version.
236
+ */
237
+ get apiKey(): string;
232
238
  /**
233
239
  * Creates a new PostHog instance for React Native. You can find all configuration options in the [React Native SDK docs](https://posthog.com/docs/libraries/react-native#configuration-options).
234
240
  *
@@ -241,7 +247,7 @@ export declare class PostHog extends PostHogCore {
241
247
  * // posthog.ts
242
248
  * import PostHog from 'posthog-react-native'
243
249
  *
244
- * export const posthog = new PostHog('<ph_project_api_key>', {
250
+ * export const posthog = new PostHog('<ph_project_token>', {
245
251
  * host: '<ph_client_api_host>'
246
252
  * })
247
253
  *
@@ -260,11 +266,11 @@ export declare class PostHog extends PostHogCore {
260
266
  *
261
267
  * @public
262
268
  *
263
- * @param apiKey - Your PostHog project token, which starts with `phc_`. Find it in your project
269
+ * @param projectToken - Your PostHog project token, which starts with `phc_`. Find it in your project
264
270
  * settings: https://us.posthog.com/settings/project-details#variables
265
271
  * @param options - PostHog configuration options
266
272
  */
267
- constructor(apiKey: string, options?: PostHogOptions);
273
+ constructor(projectToken: string, options?: PostHogOptions);
268
274
  /**
269
275
  *
270
276
  * @internal