posthog-react-native 4.74.2 → 4.75.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.
- package/dist/PostHogErrorBoundary.js.map +1 -1
- package/dist/PostHogProvider.js.map +1 -1
- package/dist/autocapture.d.ts +1 -1
- package/dist/autocapture.js.map +1 -1
- package/dist/error-tracking/index.js.map +1 -1
- package/dist/error-tracking/utils.js.map +1 -1
- package/dist/frameworks/wix-navigation.js +1 -1
- package/dist/frameworks/wix-navigation.js.map +1 -1
- package/dist/hooks/useNavigationTracker.js.map +1 -1
- package/dist/logs-defaults.js +1 -1
- package/dist/logs-defaults.js.map +1 -1
- package/dist/optional/OptionalExpoUpdates.js.map +1 -1
- package/dist/optional/OptionalPlugin.js.map +1 -1
- package/dist/optional/OptionalReactNativeSafeArea.js.map +1 -1
- package/dist/optional/OptionalReactNativeSvg.js.map +1 -1
- package/dist/posthog-rn.js +1 -1
- package/dist/posthog-rn.js.map +1 -1
- package/dist/surveys/PostHogSurveyProvider.js +1 -1
- package/dist/surveys/PostHogSurveyProvider.js.map +1 -1
- package/dist/surveys/components/QuestionHeader.js.map +1 -1
- package/dist/surveys/components/QuestionTypes.js +1 -1
- package/dist/surveys/components/QuestionTypes.js.map +1 -1
- package/dist/surveys/components/SurveyModal.d.ts +5 -0
- package/dist/surveys/components/SurveyModal.js +1 -1
- package/dist/surveys/components/SurveyModal.js.map +1 -1
- package/dist/surveys/components/Surveys.d.ts +7 -4
- package/dist/surveys/components/Surveys.js +1 -1
- package/dist/surveys/components/Surveys.js.map +1 -1
- package/dist/surveys/getActiveMatchingSurveys.d.ts +1 -1
- package/dist/surveys/getActiveMatchingSurveys.js +1 -1
- package/dist/surveys/getActiveMatchingSurveys.js.map +1 -1
- package/dist/surveys/icons.js.map +1 -1
- package/dist/surveys/safeStyleSheet.js.map +1 -1
- package/dist/surveys/survey-progress.d.ts +23 -0
- package/dist/surveys/survey-progress.js +2 -0
- package/dist/surveys/survey-progress.js.map +1 -0
- package/dist/surveys/survey-shuffling.js.map +1 -1
- package/dist/surveys/surveys-utils.d.ts +1 -1
- package/dist/surveys/useActivatedSurveys.js +1 -1
- package/dist/surveys/useActivatedSurveys.js.map +1 -1
- package/dist/surveys/useSurveyStorage.d.ts +3 -1
- package/dist/surveys/useSurveyStorage.js +1 -1
- package/dist/surveys/useSurveyStorage.js.map +1 -1
- package/dist/tooling/expoconfig.js +1 -1
- package/dist/tooling/expoconfig.js.map +1 -1
- package/dist/tooling/metroconfig.js.map +1 -1
- package/dist/tooling/posthogMetroSerializer.js.map +1 -1
- package/dist/tooling/utils.js.map +1 -1
- package/dist/tooling/vendor/metro/countLines.d.ts +1 -1
- package/dist/tooling/vendor/metro/utils.js.map +1 -1
- package/dist/utils.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useActivatedSurveys.js","names":["_react","require","_surveys","_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","SURVEY_SHOWN_EVENT_NAME","useActivatedSurveys","posthog","surveys","_useState","useState","Set","_useState2","_slicedToArray2","activatedSurveys","setActivatedSurveys","eventMap","useMemo","newEventMap","Map","_iterator","filter","doesSurveyActivateByEvent","_step","survey","_iterator2","_c","_b","_a","conditions","events","values","_step2","event","configs","_d","get","push","surveyId","id","propertyFilters","set","err","
|
|
1
|
+
{"version":3,"file":"useActivatedSurveys.js","names":["_react","require","_surveys","_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","SURVEY_SHOWN_EVENT_NAME","useActivatedSurveys","posthog","surveys","_useState","useState","Set","_useState2","_slicedToArray2","activatedSurveys","setActivatedSurveys","useEffect","on","eventMap","useMemo","newEventMap","Map","_iterator","filter","doesSurveyActivateByEvent","_step","survey","_iterator2","_c","_b","_a","conditions","events","values","_step2","event","configs","_d","get","push","surveyId","id","propertyFilters","set","err","size","payload","has","matchingSurveyIds","config","matchPropertyFilters","properties","map","current","concat","_toConsumableArray2","$survey_id"],"sources":["../../src/surveys/useActivatedSurveys.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'react'\n\nimport type { PropertyFilters, Survey } from '@posthog/core'\nimport { doesSurveyActivateByEvent, matchPropertyFilters } from '@posthog/core/surveys'\nimport { PostHog } from '../posthog-rn'\n\nconst SURVEY_SHOWN_EVENT_NAME = 'survey shown'\n\ninterface EventSurveyConfig {\n surveyId: string\n propertyFilters?: PropertyFilters\n}\n\nexport function useActivatedSurveys(posthog: PostHog, surveys: Survey[]): ReadonlySet<string> {\n const [activatedSurveys, setActivatedSurveys] = useState<ReadonlySet<string>>(new Set())\n\n useEffect(() => {\n setActivatedSurveys(new Set())\n return posthog.on('surveysReset', () => setActivatedSurveys(new Set()))\n }, [posthog])\n\n const eventMap = useMemo(() => {\n const newEventMap = new Map<string, EventSurveyConfig[]>()\n for (const survey of surveys.filter(doesSurveyActivateByEvent)) {\n for (const event of survey.conditions?.events?.values ?? []) {\n const configs = newEventMap.get(event.name) ?? []\n configs.push({\n surveyId: survey.id,\n propertyFilters: event.propertyFilters,\n })\n newEventMap.set(event.name, configs)\n }\n }\n return newEventMap\n }, [surveys])\n\n useEffect(() => {\n if (eventMap.size > 0) {\n return posthog.on('capture', (payload: { event: string; properties?: Record<string, unknown> }) => {\n if (eventMap.has(payload.event)) {\n const configs = eventMap.get(payload.event) ?? []\n const matchingSurveyIds = configs\n .filter((config) => matchPropertyFilters(config.propertyFilters, payload.properties))\n .map((config) => config.surveyId)\n\n if (matchingSurveyIds.length > 0) {\n setActivatedSurveys((current) => new Set([...current, ...matchingSurveyIds]))\n }\n } else if (payload.event === SURVEY_SHOWN_EVENT_NAME) {\n const surveyId = payload.properties?.$survey_id as string | undefined\n if (surveyId) {\n setActivatedSurveys((current) => {\n if (!current.has(surveyId)) {\n return current\n }\n const next = new Set(current)\n next.delete(surveyId)\n return next\n })\n }\n }\n })\n }\n }, [eventMap, posthog])\n\n return activatedSurveys\n}\n"],"mappings":"yYAAA,IAAAA,MAAA,CAAAC,OAAA,UAGA,IAAAC,QAAA,CAAAD,OAAA,0BAAuF,SAAAE,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,IAAAF,CAAA,CAAAjB,CAAA,GAAAe,CAAA,UAAAA,EA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AQ,CAAE,CACZzB,mBAAmB,CAAC,SAACsC,OAAO,CAAI,CAC9B,GAAI,CAACA,OAAO,CAACN,GAAG,CAACP,QAAQ,CAAC,CAAE,CAC1B,MAAO,CAAAa,OAAO,CAChB,CACA,GAAM,CAAAxD,IAAI,CAAG,GAAI,CAAAc,GAAG,CAAC0C,OAAO,CAAC,CAC7BxD,IAAI,UAAO,CAAC2C,QAAQ,CAAC,CACrB,MAAO,CAAA3C,IAAI,CACb,CAAC,CAAC,CACJ,CACF,CACF,CAAC,CAAC,CACJ,CACF,CAAC,CAAE,CAACqB,QAAQ,CAAEX,OAAO,CAAC,CAAC,CAEvB,MAAO,CAAAO,gBAAgB,CACzB","ignoreList":[]}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { SurveyWithIteration } from '@posthog/core/surveys';
|
|
2
|
+
import type { PostHog } from '../posthog-rn';
|
|
2
3
|
type SurveyStorage = {
|
|
4
|
+
isReady: boolean;
|
|
3
5
|
seenSurveys: string[];
|
|
4
6
|
setSeenSurvey: (survey: SurveyWithIteration) => void;
|
|
5
7
|
lastSeenSurveyDate: Date | undefined;
|
|
6
8
|
setLastSeenSurveyDate: (date: Date) => void;
|
|
7
9
|
};
|
|
8
10
|
export declare function updateSeenSurveys(current: string[], survey: SurveyWithIteration): string[];
|
|
9
|
-
export declare function useSurveyStorage(): SurveyStorage;
|
|
11
|
+
export declare function useSurveyStorage(client?: PostHog): SurveyStorage;
|
|
10
12
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.updateSeenSurveys=updateSeenSurveys;exports.useSurveyStorage=useSurveyStorage;var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _core=require("@posthog/core");var _surveys=require("@posthog/core/surveys");var _react=require("react");var _usePostHog=require("../hooks/usePostHog");var MAX_SEEN_SURVEYS=20;function updateSeenSurveys(current,survey){var surveyKey=(0,_surveys.getSurveyIterationKey)(survey);return[surveyKey].concat((0,_toConsumableArray2["default"])(current.filter(function(key){return!(0,_surveys.isSurveyKeyForSurvey)(key,survey.id);}))).slice(0,MAX_SEEN_SURVEYS);}function useSurveyStorage(){var
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.updateSeenSurveys=updateSeenSurveys;exports.useSurveyStorage=useSurveyStorage;var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _core=require("@posthog/core");var _surveys=require("@posthog/core/surveys");var _react=require("react");var _usePostHog=require("../hooks/usePostHog");var MAX_SEEN_SURVEYS=20;function updateSeenSurveys(current,survey){var surveyKey=(0,_surveys.getSurveyIterationKey)(survey);return[surveyKey].concat((0,_toConsumableArray2["default"])(current.filter(function(key){return!(0,_surveys.isSurveyKeyForSurvey)(key,survey.id);}))).slice(0,MAX_SEEN_SURVEYS);}function useSurveyStorage(client){var fromHook=(0,_usePostHog.usePostHog)();var posthogStorage=client!==null&&client!==void 0?client:fromHook;var _useState=(0,_react.useState)(false),_useState2=(0,_slicedToArray2["default"])(_useState,2),isReady=_useState2[0],setIsReady=_useState2[1];var _useState3=(0,_react.useState)(undefined),_useState4=(0,_slicedToArray2["default"])(_useState3,2),lastSeenSurveyDate=_useState4[0],setLastSeenSurveyDate=_useState4[1];var _useState5=(0,_react.useState)([]),_useState6=(0,_slicedToArray2["default"])(_useState5,2),seenSurveys=_useState6[0],setSeenSurveys=_useState6[1];(0,_react.useEffect)(function(){var mounted=true;setIsReady(false);var load=function load(){if(!mounted)return;var lastSeenSurveyDate=posthogStorage.getPersistedProperty(_core.PostHogPersistedProperty.SurveyLastSeenDate);if(typeof lastSeenSurveyDate==='string'){setLastSeenSurveyDate(new Date(lastSeenSurveyDate));}var serialisedSeenSurveys=posthogStorage.getPersistedProperty(_core.PostHogPersistedProperty.SurveysSeen);if(typeof serialisedSeenSurveys==='string'){var parsedSeenSurveys;try{parsedSeenSurveys=JSON.parse(serialisedSeenSurveys);}catch(_a){parsedSeenSurveys=[];}if(Array.isArray(parsedSeenSurveys)){setSeenSurveys(parsedSeenSurveys.filter(function(key){return typeof key==='string';}));}}else{setSeenSurveys([]);}setIsReady(true);};void posthogStorage.ready().then(load);var unsubscribe=posthogStorage.on('surveysReset',function(){void posthogStorage.ready().then(load);});return function(){mounted=false;unsubscribe();};},[posthogStorage]);return{isReady:isReady,seenSurveys:seenSurveys,setSeenSurvey:(0,_react.useCallback)(function(survey){setSeenSurveys(function(current){var newValue=updateSeenSurveys(current,survey);posthogStorage.setPersistedProperty(_core.PostHogPersistedProperty.SurveysSeen,JSON.stringify(newValue));return newValue;});},[posthogStorage]),lastSeenSurveyDate:lastSeenSurveyDate,setLastSeenSurveyDate:(0,_react.useCallback)(function(date){setLastSeenSurveyDate(date);posthogStorage.setPersistedProperty(_core.PostHogPersistedProperty.SurveyLastSeenDate,date.toISOString());},[posthogStorage])};}
|
|
2
2
|
//# sourceMappingURL=useSurveyStorage.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSurveyStorage.js","names":["_core","require","_surveys","_react","_usePostHog","MAX_SEEN_SURVEYS","updateSeenSurveys","current","survey","surveyKey","getSurveyIterationKey","concat","_toConsumableArray2","filter","key","isSurveyKeyForSurvey","id","slice","useSurveyStorage","
|
|
1
|
+
{"version":3,"file":"useSurveyStorage.js","names":["_core","require","_surveys","_react","_usePostHog","MAX_SEEN_SURVEYS","updateSeenSurveys","current","survey","surveyKey","getSurveyIterationKey","concat","_toConsumableArray2","filter","key","isSurveyKeyForSurvey","id","slice","useSurveyStorage","client","fromHook","usePostHog","posthogStorage","_useState","useState","_useState2","_slicedToArray2","isReady","setIsReady","_useState3","undefined","_useState4","lastSeenSurveyDate","setLastSeenSurveyDate","_useState5","_useState6","seenSurveys","setSeenSurveys","useEffect","mounted","load","getPersistedProperty","PostHogPersistedProperty","SurveyLastSeenDate","Date","serialisedSeenSurveys","SurveysSeen","parsedSeenSurveys","JSON","parse","Array","isArray","ready","then","unsubscribe","on","setSeenSurvey","useCallback","newValue","setPersistedProperty","stringify","date","toISOString"],"sources":["../../src/surveys/useSurveyStorage.ts"],"sourcesContent":["import { PostHogPersistedProperty } from '@posthog/core'\nimport { getSurveyIterationKey, isSurveyKeyForSurvey, SurveyWithIteration } from '@posthog/core/surveys'\nimport { useCallback, useEffect, useState } from 'react'\nimport { usePostHog } from '../hooks/usePostHog'\nimport type { PostHog } from '../posthog-rn'\n\ntype SurveyStorage = {\n isReady: boolean\n // Iteration-qualified keys (getSurveyIterationKey) so repeating surveys re-show when a new iteration starts\n seenSurveys: string[]\n setSeenSurvey: (survey: SurveyWithIteration) => void\n lastSeenSurveyDate: Date | undefined\n setLastSeenSurveyDate: (date: Date) => void\n}\n\n// To keep storage bounded, only keep the last 20 seen surveys\nconst MAX_SEEN_SURVEYS = 20\n\n// One slot per survey: stale keys from earlier iterations (or the pre-iteration bare id)\n// can never match again and would otherwise evict other surveys' seen state.\nexport function updateSeenSurveys(current: string[], survey: SurveyWithIteration): string[] {\n const surveyKey = getSurveyIterationKey(survey)\n return [surveyKey, ...current.filter((key) => !isSurveyKeyForSurvey(key, survey.id))].slice(0, MAX_SEEN_SURVEYS)\n}\n\nexport function useSurveyStorage(client?: PostHog): SurveyStorage {\n const fromHook = usePostHog()\n const posthogStorage = client ?? fromHook\n const [isReady, setIsReady] = useState(false)\n const [lastSeenSurveyDate, setLastSeenSurveyDate] = useState<Date | undefined>(undefined)\n const [seenSurveys, setSeenSurveys] = useState<string[]>([])\n\n useEffect(() => {\n let mounted = true\n setIsReady(false)\n const load = () => {\n if (!mounted) return\n const lastSeenSurveyDate = posthogStorage.getPersistedProperty(PostHogPersistedProperty.SurveyLastSeenDate)\n if (typeof lastSeenSurveyDate === 'string') {\n setLastSeenSurveyDate(new Date(lastSeenSurveyDate))\n }\n\n const serialisedSeenSurveys = posthogStorage.getPersistedProperty(PostHogPersistedProperty.SurveysSeen)\n if (typeof serialisedSeenSurveys === 'string') {\n let parsedSeenSurveys: unknown\n try {\n parsedSeenSurveys = JSON.parse(serialisedSeenSurveys)\n } catch {\n parsedSeenSurveys = []\n }\n if (Array.isArray(parsedSeenSurveys)) {\n setSeenSurveys(parsedSeenSurveys.filter((key): key is string => typeof key === 'string'))\n }\n } else {\n setSeenSurveys([])\n }\n setIsReady(true)\n }\n void posthogStorage.ready().then(load)\n const unsubscribe = posthogStorage.on('surveysReset', () => {\n void posthogStorage.ready().then(load)\n })\n return () => {\n mounted = false\n unsubscribe()\n }\n }, [posthogStorage])\n\n return {\n isReady,\n seenSurveys,\n setSeenSurvey: useCallback(\n (survey: SurveyWithIteration) => {\n setSeenSurveys((current) => {\n const newValue = updateSeenSurveys(current, survey)\n posthogStorage.setPersistedProperty(PostHogPersistedProperty.SurveysSeen, JSON.stringify(newValue))\n return newValue\n })\n },\n [posthogStorage]\n ),\n lastSeenSurveyDate,\n setLastSeenSurveyDate: useCallback(\n (date: Date) => {\n setLastSeenSurveyDate(date)\n posthogStorage.setPersistedProperty(PostHogPersistedProperty.SurveyLastSeenDate, date.toISOString())\n },\n [posthogStorage]\n ),\n }\n}\n"],"mappings":"+aAAA,IAAAA,KAAA,CAAAC,OAAA,kBACA,IAAAC,QAAA,CAAAD,OAAA,0BACA,IAAAE,MAAA,CAAAF,OAAA,UACA,IAAAG,WAAA,CAAAH,OAAA,wBAaA,GAAM,CAAAI,gBAAgB,CAAG,EAAE,CAIrB,QAAU,CAAAC,iBAAiBA,CAACC,OAAiB,CAAEC,MAA2B,EAC9E,GAAM,CAAAC,SAAS,CAAG,GAAAC,8BAAqB,EAACF,MAAM,CAAC,CAC/C,MAAO,CAACC,SAAS,EAAAE,MAAA,IAAAC,mB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EE,IAAI,CAACY,SAAS,CAACF,QAAQ,CAAC,CAAC,CACnG,MAAO,CAAAA,QAAQ,CACjB,CAAC,CAAC,CACJ,CAAC,CACD,CAACpC,cAAc,CAAC,CACjB,CACDU,kBAAkB,CAAlBA,kBAAkB,CAClBC,qBAAqB,CAAE,GAAAwB,kBAAW,EAChC,SAACI,IAAU,CAAI,CACb5B,qBAAqB,CAAC4B,IAAI,CAAC,CAC3BvC,cAAc,CAACqC,oBAAoB,CAACjB,8BAAwB,CAACC,kBAAkB,CAAEkB,IAAI,CAACC,WAAW,EAAE,CAAC,CACtG,CAAC,CACD,CAACxC,cAAc,CAAC,C,CAEnB,CACH","ignoreList":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.POSTHOG_RELEASE_MODES=void 0;exports.addDsymUploadBuildPhase=addDsymUploadBuildPhase;exports.addPostHogAndroidGradlePluginClasspath=addPostHogAndroidGradlePluginClasspath;exports.addPostHogWithBundledScriptsToBundleShellScript=addPostHogWithBundledScriptsToBundleShellScript;exports.applyDotenvFileBuildSetting=applyDotenvFileBuildSetting;exports.applyPostHogAndroidGradlePlugin=applyPostHogAndroidGradlePlugin;exports.buildAndroidDotenvFileGradleValue=buildAndroidDotenvFileGradleValue;exports.buildAndroidSkipOnConflictGradleLine=buildAndroidSkipOnConflictGradleLine;exports.buildDsymUploadShellScript=buildDsymUploadShellScript;exports.buildIosDotenvFileBuildSetting=buildIosDotenvFileBuildSetting;exports.disableUserScriptSandboxing=disableUserScriptSandboxing;exports.modifyExistingXcodeBuildScript=modifyExistingXcodeBuildScript;exports.moveDsymUploadBuildPhaseToEnd=moveDsymUploadBuildPhaseToEnd;exports.resolveDotenvFileProp=resolveDotenvFileProp;exports.resolveNativeSymbolUpload=resolveNativeSymbolUpload;exports.resolveReleaseModeProp=resolveReleaseModeProp;exports.updateDotenvFileGradleProperties=updateDotenvFileGradleProperties;exports.updateHermesReleaseModeGradleProperties=updateHermesReleaseModeGradleProperties;exports.updateMainActivityNewIntentOverride=updateMainActivityNewIntentOverride;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _objectWithoutProperties2=_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _excluded=["nextMod"],_excluded2=["nextMod"];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 fs=require('fs');var path=require('path');var _require=require('@expo/config-plugins'),AndroidConfig=_require.AndroidConfig,withAppBuildGradle=_require.withAppBuildGradle,withBaseMod=_require.withBaseMod,withDangerousMod=_require.withDangerousMod,withGradleProperties=_require.withGradleProperties,withXcodeProject=_require.withXcodeProject;var POSTHOG_ANDROID_GRADLE_PLUGIN_VERSION='1.6.0';var resolvePostHogReactNativePackageJsonPath="[\"node\", \"--print\", \"require('path').join(require('path').dirname(require.resolve('posthog-react-native')), '..', 'tooling', 'posthog.gradle')\"].execute().text.trim()";var POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY='posthogReactNativeSkipOnConflict';var POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY='posthog.hermesReleaseMode';var POSTHOG_RELEASE_MODES=exports.POSTHOG_RELEASE_MODES=['symbol-set','event'];function resolveReleaseModeProp(releaseMode,environmentMode){var trimmed=(releaseMode===null||releaseMode===void 0?void 0:releaseMode.trim())||(environmentMode===null||environmentMode===void 0?void 0:environmentMode.trim());if(!trimmed){return undefined;}if(!POSTHOG_RELEASE_MODES.includes(trimmed)){throw new Error("[posthog-react-native] releaseMode must be one of ".concat(POSTHOG_RELEASE_MODES.join(', '),", was '").concat(trimmed,"'"));}return trimmed;}function buildAndroidSkipOnConflictGradleLine(skipOnConflict){if(!skipOnConflict){return null;}return"project.ext.".concat(POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY," = true");}var withAndroidPlugin=function withAndroidPlugin(config){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return withAppBuildGradle(config,function(config){if(config.modResults.language!=='groovy'){console.warn('Cannot configure PostHog in the app gradle because the build.gradle is not groovy');}var buildGradle=config.modResults.contents;var applyFrom="apply from: new File(".concat(resolvePostHogReactNativePackageJsonPath,")");var skipOnConflictLine=buildAndroidSkipOnConflictGradleLine(skipOnConflict);var applyBlock=skipOnConflictLine?"".concat(skipOnConflictLine,"\n").concat(applyFrom):applyFrom;var skipOnConflictPattern=new RegExp("^project\\.ext\\.".concat(POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY,"\\s*=\\s*(true|false)\\n?"),'m');if(buildGradle.includes(applyFrom)){var contents=buildGradle.replace(skipOnConflictPattern,'');if(skipOnConflictLine){contents=contents.replace(applyFrom,"".concat(skipOnConflictLine,"\n").concat(applyFrom));}config.modResults.contents=contents;return config;}var pattern=/^android\s*\{/m;if(buildGradle.match(pattern)){config.modResults.contents=buildGradle.replace(pattern,"".concat(applyBlock,"\n\nandroid {"));}else{console.warn('PostHog: Could not find "android {" block in build.gradle');}return config;});};function matchingBraceIndex(s,openBraceIndex){var depth=0;for(var i=openBraceIndex;i<s.length;i++){if(s[i]==='{'){depth++;}else if(s[i]==='}'){depth--;if(depth===0){return i;}}}return-1;}function addPostHogAndroidGradlePluginClasspath(projectBuildGradle){if(projectBuildGradle.includes('posthog-android-gradle-plugin')){return{contents:projectBuildGradle,classpathPresent:true};}var classpathLine=" classpath(\"com.posthog:posthog-android-gradle-plugin:".concat(POSTHOG_ANDROID_GRADLE_PLUGIN_VERSION,"\")");var buildscriptMatch=/buildscript\s*\{/.exec(projectBuildGradle);var buildscriptOpenBrace=buildscriptMatch?buildscriptMatch.index+buildscriptMatch[0].length-1:-1;var buildscriptEnd=buildscriptOpenBrace===-1?-1:matchingBraceIndex(projectBuildGradle,buildscriptOpenBrace);var buildscriptBody=buildscriptEnd===-1?'':projectBuildGradle.slice(buildscriptOpenBrace,buildscriptEnd);var dependenciesMatch=buildscriptBody?/dependencies\s*\{/.exec(buildscriptBody):null;if(!dependenciesMatch){console.warn('PostHog: Could not find a buildscript dependencies block in the project build.gradle; '+'skipping the com.posthog.android classpath. Native symbols will not be uploaded.');return{contents:projectBuildGradle,classpathPresent:false};}var insertAt=buildscriptOpenBrace+dependenciesMatch.index+dependenciesMatch[0].length;return{contents:"".concat(projectBuildGradle.slice(0,insertAt),"\n").concat(classpathLine).concat(projectBuildGradle.slice(insertAt)),classpathPresent:true};}function applyPostHogAndroidGradlePlugin(appBuildGradle){if(/apply plugin: ["']com\.posthog\.android["']/.test(appBuildGradle)){return appBuildGradle;}var applyLine='apply plugin: "com.posthog.android"';var appPluginPattern=/^([ \t]*apply plugin: ["']com\.android\.application["'].*)$/m;if(appPluginPattern.test(appBuildGradle)){return appBuildGradle.replace(appPluginPattern,"$1\n".concat(applyLine));}var androidBlockPattern=/^android\s*\{/m;if(androidBlockPattern.test(appBuildGradle)){return appBuildGradle.replace(androidBlockPattern,"".concat(applyLine,"\n\nandroid {"));}console.warn('PostHog: Could not find where to apply com.posthog.android in the app build.gradle');return appBuildGradle;}var withFinalizedProjectBuildGradle=function withFinalizedProjectBuildGradle(config,_action){return withBaseMod(config,{platform:'android',mod:'projectBuildGradle',skipEmptyMod:false,action:function action(config){return(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(){var _config$modRequest,nextMod,modRequest,results;return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:_config$modRequest=config.modRequest,nextMod=_config$modRequest.nextMod,modRequest=(0,_objectWithoutProperties2["default"])(_config$modRequest,_excluded);_context.next=1;return nextMod(_objectSpread(_objectSpread({},config),{},{modRequest:modRequest}));case 1:results=_context.sent;return _context.abrupt("return",_action(results));case 2:case"end":return _context.stop();}},_callee);}))();}});};var withAndroidNativeSymbolsPlugin=function withAndroidNativeSymbolsPlugin(config){return withFinalizedProjectBuildGradle(config,function(){var _ref=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(config){var result,appBuildGradle,contents;return _regenerator["default"].wrap(function(_context2){while(1)switch(_context2.prev=_context2.next){case 0:if(!(config.modResults.language!=='groovy')){_context2.next=1;break;}console.warn('Cannot configure the PostHog Android Gradle plugin because the project build.gradle is not groovy');return _context2.abrupt("return",config);case 1:result=addPostHogAndroidGradlePluginClasspath(config.modResults.contents);if(!(result.contents!==config.modResults.contents)){_context2.next=3;break;}_context2.next=2;return fs.promises.writeFile(config.modResults.path,result.contents);case 2:config.modResults.contents=result.contents;case 3:if(result.classpathPresent){_context2.next=4;break;}return _context2.abrupt("return",config);case 4:_context2.next=5;return AndroidConfig.Paths.getAppBuildGradleAsync(config.modRequest.projectRoot);case 5:appBuildGradle=_context2.sent;if(!(appBuildGradle.language!=='groovy')){_context2.next=6;break;}console.warn('Cannot configure the PostHog Android Gradle plugin because the app build.gradle is not groovy');return _context2.abrupt("return",config);case 6:contents=applyPostHogAndroidGradlePlugin(appBuildGradle.contents);if(!(contents!==appBuildGradle.contents)){_context2.next=7;break;}_context2.next=7;return fs.promises.writeFile(appBuildGradle.path,contents);case 7:return _context2.abrupt("return",config);case 8:case"end":return _context2.stop();}},_callee2);}));return function(_x){return _ref.apply(this,arguments);};}());};var POSTHOG_NEW_INTENT_MARKER='posthog-new-intent';var POSTHOG_NEW_INTENT_BEGIN="// @generated begin ".concat(POSTHOG_NEW_INTENT_MARKER," - posthog-react-native (DO NOT MODIFY)");var POSTHOG_NEW_INTENT_END="// @generated end ".concat(POSTHOG_NEW_INTENT_MARKER);var NEW_INTENT_DOC=" /**\n * Records the intent that reopened the app so getIntent() stays correct.\n *\n * Works around a React Native defect that drops notification taps and deep links arriving while\n * the React context is still starting. Managed by the posthog-react-native Expo config plugin;\n * remove it with { patchMainActivityNewIntent: false } in app.json.\n * https://posthog.com/docs/workflows/push-notifications/react-native\n */";var NEW_INTENT_KOTLIN_BODY=" override fun onNewIntent(intent: android.content.Intent) {\n setIntent(intent)\n super.onNewIntent(intent)\n }";var NEW_INTENT_JAVA_BODY=" @Override\n public void onNewIntent(android.content.Intent intent) {\n setIntent(intent);\n super.onNewIntent(intent);\n }";function newIntentOverrideBlock(language){var body=language==='java'?NEW_INTENT_JAVA_BODY:NEW_INTENT_KOTLIN_BODY;return"\n ".concat(POSTHOG_NEW_INTENT_BEGIN,"\n").concat(NEW_INTENT_DOC,"\n").concat(body,"\n ").concat(POSTHOG_NEW_INTENT_END,"\n");}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');}var POSTHOG_NEW_INTENT_BLOCK_PATTERN=new RegExp("\\r?\\n?[ \\t]*".concat(escapeRegExp(POSTHOG_NEW_INTENT_BEGIN),"[\\s\\S]*?").concat(escapeRegExp(POSTHOG_NEW_INTENT_END),"[ \\t]*\\r?\\n"),'g');function literalEnd(s,start,language){var quote=s[start];var raw=quote==='"'&&s.startsWith('"""',start);var i=start+(raw?3:1);while(i<s.length){var c=s[i];if(raw){if(s.startsWith('"""',i)){while(s[i]==='"'){i++;}return i;}}else if(c==='\n'){return-1;}else if(c===quote){return i+1;}if(c==='\\'&&(!raw||language==='java')){i+=2;continue;}if(language==='kt'&"e==='"'&&c==='$'&&s[i+1]==='{'){var close=matchingBraceIndexInSource(s,i+1,language);if(close===-1){return-1;}i=close+1;continue;}i++;}return-1;}function matchingBraceIndexInSource(s,openBraceIndex,language){var depth=0;var i=openBraceIndex;while(i<s.length){var c=s[i];if(c==='/'&&s[i+1]==='/'){var end=s.indexOf('\n',i);i=end===-1?s.length:end;continue;}if(c==='/'&&s[i+1]==='*'){var depthOfComment=1;i+=2;while(i<s.length&&depthOfComment>0){if(language==='kt'&&s[i]==='/'&&s[i+1]==='*'){depthOfComment++;i+=2;continue;}if(s[i]==='*'&&s[i+1]==='/'){depthOfComment--;i+=2;continue;}i++;}if(depthOfComment>0){return-1;}continue;}if(c==='"'||c==="'"){var _end=literalEnd(s,i,language);if(_end===-1){return-1;}i=_end;continue;}if(c==='{'){depth++;}else if(c==='}'){depth--;if(depth===0){return i;}}i++;}return-1;}function maskCommentsAndLiterals(source,language){var out=source.split('');var blank=function blank(from,to){for(var j=from;j<to&&j<out.length;j++){if(out[j]!=='\n'){out[j]=' ';}}};var i=0;while(i<source.length){var c=source[i];if(c==='/'&&source[i+1]==='/'){var end=source.indexOf('\n',i);var stop=end===-1?source.length:end;blank(i,stop);i=stop;continue;}if(c==='/'&&source[i+1]==='*'){var depth=1;var j=i+2;while(j<source.length&&depth>0){if(language==='kt'&&source[j]==='/'&&source[j+1]==='*'){depth++;j+=2;continue;}if(source[j]==='*'&&source[j+1]==='/'){depth--;j+=2;continue;}j++;}blank(i,j);i=j;continue;}if(c==='"'||c==="'"){var _end2=literalEnd(source,i,language);if(_end2===-1){blank(i,source.length);return out.join('');}blank(i,_end2);i=_end2;continue;}i++;}return out.join('');}function mainActivityBody(contents,language){var code=maskCommentsAndLiterals(contents,language);var declaration=/\bclass\s+MainActivity\b/.exec(code);if(!declaration){return undefined;}var searchFrom=declaration.index+declaration[0].length;var open=code.indexOf('{',searchFrom);if(open===-1||!/^[^;{}]*$/.test(code.slice(searchFrom,open))){return undefined;}var depth=0;var close=-1;for(var i=open;i<code.length;i++){if(code[i]==='{'){depth++;}else if(code[i]==='}'){depth--;if(depth===0){close=i;break;}}}return close===-1?undefined:{open:open,close:close};}function updateMainActivityNewIntentOverride(contents,language,enabled){var withoutManagedBlock=contents.replace(POSTHOG_NEW_INTENT_BLOCK_PATTERN,'');if(!enabled){return withoutManagedBlock;}var body=mainActivityBody(withoutManagedBlock,language);if(!body){console.warn('[posthog-react-native] Could not find the MainActivity class body; skipping the onNewIntent '+'override. Notification taps delivered while the React context is starting will be lost.');return withoutManagedBlock;}var codeOnly=maskCommentsAndLiterals(withoutManagedBlock,language);if(/\b(fun|void)\s+onNewIntent\s*\(/.test(codeOnly.slice(body.open,body.close))){console.warn('[posthog-react-native] MainActivity already overrides onNewIntent; leaving it alone. '+'Add `setIntent(intent)` as its first statement so a notification tap that arrives before '+'the React context is ready is not lost, or set `{ patchMainActivityNewIntent: false }` '+'on the plugin to silence this.');return withoutManagedBlock;}return withoutManagedBlock.slice(0,body.open+1)+newIntentOverrideBlock(language)+withoutManagedBlock.slice(body.open+1);}var MAIN_ACTIVITY_SOURCE_ROOTS=['android/app/src/main/java','android/app/src/main/kotlin'];function findMainActivityPath(projectRoot){var _walk=function walk(dir){if(!fs.existsSync(dir)){return undefined;}var _iterator=_createForOfIteratorHelper(fs.readdirSync(dir,{withFileTypes:true})),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var entry=_step.value;var candidate=path.join(dir,entry.name);if(!entry.isDirectory()){if(/^MainActivity\.(kt|java)$/.test(entry.name)){return candidate;}continue;}var hit=_walk(candidate);if(hit){return hit;}}}catch(err){_iterator.e(err);}finally{_iterator.f();}return undefined;};for(var _i=0,_MAIN_ACTIVITY_SOURCE=MAIN_ACTIVITY_SOURCE_ROOTS;_i<_MAIN_ACTIVITY_SOURCE.length;_i++){var sourceRoot=_MAIN_ACTIVITY_SOURCE[_i];var hit=_walk(path.join(projectRoot,sourceRoot));if(hit){return hit;}}return undefined;}var withMainActivityNewIntent=function withMainActivityNewIntent(config,enabled){return withDangerousMod(config,['android',(function(){var _ref2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(config){var mainActivityPath,contents,updated;return _regenerator["default"].wrap(function(_context3){while(1)switch(_context3.prev=_context3.next){case 0:mainActivityPath=findMainActivityPath(config.modRequest.projectRoot);if(mainActivityPath){_context3.next=1;break;}console.warn('[posthog-react-native] Could not find MainActivity under android/app/src/main/{java,kotlin}; '+'skipping the onNewIntent override. Notification taps delivered while the React context is '+'starting will be lost.');return _context3.abrupt("return",config);case 1:_context3.next=2;return fs.promises.readFile(mainActivityPath,'utf8');case 2:contents=_context3.sent;updated=updateMainActivityNewIntentOverride(contents,mainActivityPath.endsWith('.java')?'java':'kt',enabled);if(!(updated!==contents)){_context3.next=3;break;}_context3.next=3;return fs.promises.writeFile(mainActivityPath,updated);case 3:if(!contents.includes(POSTHOG_NEW_INTENT_BEGIN)&&updated.includes(POSTHOG_NEW_INTENT_BEGIN)){console.warn("[posthog-react-native] Added an onNewIntent override to ".concat(path.relative(config.modRequest.projectRoot,mainActivityPath)," so a notification tap that arrives before the React context is ready is not lost. ")+'Set `{ patchMainActivityNewIntent: false }` on the plugin in app.json to opt out.');}return _context3.abrupt("return",config);case 4:case"end":return _context3.stop();}},_callee3);}));return function(_x2){return _ref2.apply(this,arguments);};}())]);};function modifyExistingXcodeBuildScript(script){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var releaseMode=arguments.length>2?arguments[2]:undefined;if(!(script===null||script===void 0?void 0:script.shellScript)){console.warn("[posthog-react-native] Could not find the 'Bundle React Native code and images' build phase; "+'skipping sourcemap upload setup.');return;}if(!script.shellScript.match(/(packager|scripts)\/react-native-xcode\.sh\b/)){return;}if(script.shellScript.includes('posthog-xcode.sh')){var _code=migrateLegacyPostHogWrapperInvocation(JSON.parse(script.shellScript));script.shellScript=JSON.stringify(updatePostHogBundlePhaseExports(_code,skipOnConflict,releaseMode));return;}if(script.shellScript.includes('posthog-react-native')){return;}var code=JSON.parse(script.shellScript);script.shellScript=JSON.stringify(addPostHogWithBundledScriptsToBundleShellScript(code,skipOnConflict,releaseMode));}var POSTHOG_REACT_NATIVE_XCODE_PATH="`\"$NODE_BINARY\" --print \"require('path').join(require('path').dirname(require.resolve('posthog-react-native')), '..', 'tooling', 'posthog-xcode.sh')\"`";var POSTHOG_SKIP_ON_CONFLICT_EXPORT='export POSTHOG_SKIP_ON_CONFLICT=1';var POSTHOG_RELEASE_MODE_EXPORT_PREFIX='export POSTHOG_RELEASE_MODE=';function buildBundlePhaseExports(skipOnConflict,releaseMode){var exports=[];if(skipOnConflict){exports.push(POSTHOG_SKIP_ON_CONFLICT_EXPORT);}if(releaseMode){exports.push("".concat(POSTHOG_RELEASE_MODE_EXPORT_PREFIX).concat(releaseMode));}return exports;}var REACT_NATIVE_XCODE_LINE=/^([ \t]*)(?![A-Za-z_][A-Za-z0-9_]*=)([^\n]*(?:packager|scripts)\/react-native-xcode\.sh\b[^\n]*)$/m;function migrateLegacyPostHogWrapperInvocation(script){return script.replace("/bin/sh ".concat(POSTHOG_REACT_NATIVE_XCODE_PATH),POSTHOG_REACT_NATIVE_XCODE_PATH);}function updatePostHogBundlePhaseExports(script,skipOnConflict,releaseMode){var _a,_b;var skipArg='--posthog-skip-on-conflict --';var lines=script.replace(new RegExp("\\s*".concat(skipArg,"\\s*"),'g'),' ').split('\n').filter(function(line){return line.trim()!==POSTHOG_SKIP_ON_CONFLICT_EXPORT;}).filter(function(line){return!line.trim().startsWith(POSTHOG_RELEASE_MODE_EXPORT_PREFIX);});var exports=buildBundlePhaseExports(skipOnConflict,releaseMode);if(exports.length>0){var commandIndex=lines.findIndex(function(line){return line.includes(POSTHOG_REACT_NATIVE_XCODE_PATH);});if(commandIndex!==-1){var indent=(_b=(_a=lines[commandIndex].match(/^[ \t]*/))===null||_a===void 0?void 0:_a[0])!==null&&_b!==void 0?_b:'';lines.splice.apply(lines,[commandIndex,0].concat((0,_toConsumableArray2["default"])(exports.map(function(line){return"".concat(indent).concat(line);}))));}}return lines.join('\n');}function addPostHogWithBundledScriptsToBundleShellScript(script){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var releaseMode=arguments.length>2?arguments[2]:undefined;return script.replace(REACT_NATIVE_XCODE_LINE,function(_match,indent,rnCommand){var exports=buildBundlePhaseExports(skipOnConflict,releaseMode).map(function(line){return"".concat(indent).concat(line,"\n");}).join('');return"".concat(exports).concat(indent).concat(POSTHOG_REACT_NATIVE_XCODE_PATH," ").concat(rnCommand);});}var POSTHOG_DSYM_BUILD_PHASE_NAME='Upload PostHog Debug Symbols';var POSTHOG_DSYM_INPUT_PATH='"$(DWARF_DSYM_FOLDER_PATH)/$(DWARF_DSYM_FILE_NAME)/Contents/Resources/DWARF/$(EXECUTABLE_NAME)"';function buildDsymUploadShellScript(){var includeSource=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return composeDsymUploadShellScript(includeSource,skipOnConflict);}function composeDsymUploadShellScript(includeSource,skipOnConflict){var lines=['# Upload iOS dSYMs to PostHog so native crashes can be symbolicated.','# upload-symbols.sh ships inside the posthog-ios dependency.'];if(includeSource){lines.push('# Also upload native source files for source-code context around crashes.','export POSTHOG_INCLUDE_SOURCE=1');}if(skipOnConflict){lines.push('# Skip dSYMs that already exist in PostHog with different content instead of failing the build.','export POSTHOG_SKIP_ON_CONFLICT=1');}lines.push('PODS_SCRIPT="${PODS_ROOT}/PostHog/build-tools/upload-symbols.sh"','SPM_SCRIPT="${BUILD_DIR%/Build/*}/SourcePackages/checkouts/posthog-ios/build-tools/upload-symbols.sh"','if [ -f "$PODS_SCRIPT" ]; then',' /bin/sh "$PODS_SCRIPT"','elif [ -f "$SPM_SCRIPT" ]; then',' /bin/sh "$SPM_SCRIPT"','else',' echo "warning: PostHog upload-symbols.sh not found in Pods or SwiftPM checkouts; skipping dSYM upload."','fi');return lines.join('\n');}function legacyDsymReleaseModeLines(releaseMode){return[releaseMode?"POSTHOG_RESOLVED_RELEASE_MODE=\"".concat(releaseMode,"\""):'POSTHOG_RESOLVED_RELEASE_MODE="${POSTHOG_RELEASE_MODE:-}"','case "$POSTHOG_RESOLVED_RELEASE_MODE" in',' ""|symbol-set) ;;',' event)',' # Upload dSYMs without binding them to a release, so each crash resolves its own from the',' # app version and namespace the SDK sends. posthog-ios versions whose upload-symbols.sh',' # does not read this variable ignore it and keep binding the dSYMs.',' export POSTHOG_NO_RELEASE_BIND=1',' ;;',' *)'," echo \"error: posthog release mode must be 'symbol-set' or 'event', was '$POSTHOG_RESOLVED_RELEASE_MODE'\"",' exit 1',' ;;','esac'];}function buildLegacyReleaseModeDsymUploadShellScript(includeSource,skipOnConflict,releaseMode){var lines=composeDsymUploadShellScript(includeSource,skipOnConflict).split('\n');var uploadIndex=lines.findIndex(function(line){return line.startsWith('PODS_SCRIPT=');});lines.splice.apply(lines,[uploadIndex,0].concat((0,_toConsumableArray2["default"])(legacyDsymReleaseModeLines(releaseMode))));return lines.join('\n');}function encodePbxShellScript(script){return'"'+script.replace(/"/g,'\\"')+'"';}function decodePbxShellScript(stored){if(!stored.startsWith('"')||!stored.endsWith('"')){return stored;}return stored.slice(1,-1).replace(/\\(.)/g,function(_match,ch){return ch==='n'?'\n':ch==='t'?'\t':ch;});}function isPluginGeneratedDsymUploadBuildPhase(phase){if(typeof(phase===null||phase===void 0?void 0:phase.shellScript)!=='string'){return false;}var stored=decodePbxShellScript(phase.shellScript);return[false,true].some(function(source){return[false,true].some(function(skip){return stored===buildDsymUploadShellScript(source,skip)||[undefined].concat(POSTHOG_RELEASE_MODES).some(function(mode){return stored===buildLegacyReleaseModeDsymUploadShellScript(source,skip,mode);});});});}function moveDsymUploadBuildPhaseToEnd(xcodeProject){var _a,_b;var existing=xcodeProject.pbxItemByComment(POSTHOG_DSYM_BUILD_PHASE_NAME,'PBXShellScriptBuildPhase');if(!isPluginGeneratedDsymUploadBuildPhase(existing)){return;}var buildPhases=(_b=(_a=xcodeProject.getFirstTarget)===null||_a===void 0?void 0:_a.call(xcodeProject).firstTarget)===null||_b===void 0?void 0:_b.buildPhases;if(Array.isArray(buildPhases)){var phaseIndex=buildPhases.findIndex(function(phase){return phase.comment===POSTHOG_DSYM_BUILD_PHASE_NAME;});if(phaseIndex!==-1&&phaseIndex!==buildPhases.length-1){buildPhases.push.apply(buildPhases,(0,_toConsumableArray2["default"])(buildPhases.splice(phaseIndex,1)));}}}function addDsymUploadBuildPhase(xcodeProject){var includeSource=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var skipOnConflict=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var existing=xcodeProject.pbxItemByComment(POSTHOG_DSYM_BUILD_PHASE_NAME,'PBXShellScriptBuildPhase');if(existing){if(isPluginGeneratedDsymUploadBuildPhase(existing)){existing.shellScript=encodePbxShellScript(buildDsymUploadShellScript(includeSource,skipOnConflict));existing.inputPaths=Array.from(new Set([].concat((0,_toConsumableArray2["default"])(Array.isArray(existing.inputPaths)?existing.inputPaths:[]),[POSTHOG_DSYM_INPUT_PATH])));}}else{xcodeProject.addBuildPhase([],'PBXShellScriptBuildPhase',POSTHOG_DSYM_BUILD_PHASE_NAME,null,{inputPaths:[POSTHOG_DSYM_INPUT_PATH],shellPath:'/bin/sh',shellScript:buildDsymUploadShellScript(includeSource,skipOnConflict)});}moveDsymUploadBuildPhaseToEnd(xcodeProject);}function disableUserScriptSandboxing(xcodeProject){var configurations=xcodeProject.pbxXCBuildConfigurationSection();for(var key in configurations){var configuration=configurations[key];if(configuration&&configuration.buildSettings){configuration.buildSettings.ENABLE_USER_SCRIPT_SANDBOXING='"NO"';}}}var POSTHOG_DOTENV_BUILD_SETTING='POSTHOG_CLI_DOTENV_FILE';var POSTHOG_DOTENV_GRADLE_PROPERTY='posthog.dotenvFile';function normalizeDotenvFileProp(dotenvFile){return dotenvFile.replace(/^\.\//,'');}function resolveDotenvFileProp(dotenvFile){var trimmed=dotenvFile===null||dotenvFile===void 0?void 0:dotenvFile.trim();return trimmed?trimmed:undefined;}function isAbsoluteDotenvPath(dotenvFile){return dotenvFile.startsWith('/')||/^[A-Za-z]:[\\/]/.test(dotenvFile);}function buildIosDotenvFileBuildSetting(dotenvFile){var value=isAbsoluteDotenvPath(dotenvFile)?dotenvFile:"$(SRCROOT)/../".concat(normalizeDotenvFileProp(dotenvFile));return'"'+value.replace(/(["\\])/g,'\\$1')+'"';}function applyDotenvFileBuildSetting(xcodeProject,dotenvFile){var configurations=xcodeProject.pbxXCBuildConfigurationSection();for(var key in configurations){var configuration=configurations[key];if(configuration&&configuration.buildSettings){if(dotenvFile){configuration.buildSettings[POSTHOG_DOTENV_BUILD_SETTING]=buildIosDotenvFileBuildSetting(dotenvFile);}else{delete configuration.buildSettings[POSTHOG_DOTENV_BUILD_SETTING];}}}}function buildAndroidDotenvFileGradleValue(dotenvFile){return isAbsoluteDotenvPath(dotenvFile)?dotenvFile:"../".concat(normalizeDotenvFileProp(dotenvFile));}function updateDotenvFileGradleProperties(properties,dotenvFile){var rest=properties.filter(function(item){return!(item.type==='property'&&item.key===POSTHOG_DOTENV_GRADLE_PROPERTY);});if(!dotenvFile){return rest;}rest.push({type:'property',key:POSTHOG_DOTENV_GRADLE_PROPERTY,value:buildAndroidDotenvFileGradleValue(dotenvFile)});return rest;}function updateHermesReleaseModeGradleProperties(properties,releaseMode){var rest=properties.filter(function(item){return!(item.type==='property'&&item.key===POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY);});if(!releaseMode){return rest;}rest.push({type:'property',key:POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY,value:releaseMode});return rest;}var withPostHogGradleProperties=function withPostHogGradleProperties(config,dotenvFile,releaseMode){return withGradleProperties(config,function(config){config.modResults=updateDotenvFileGradleProperties(config.modResults,dotenvFile);config.modResults=updateHermesReleaseModeGradleProperties(config.modResults,releaseMode);return config;});};function resolveNativeSymbolUpload(prop){if(prop===true){return{enabled:true,includeSource:false};}if(prop&&(0,_typeof2["default"])(prop)==='object'){return{enabled:true,includeSource:prop.includeSource===true};}return{enabled:false,includeSource:false};}var withFinalizedXcodeProject=function withFinalizedXcodeProject(config,_action2){return withBaseMod(config,{platform:'ios',mod:'xcodeproj',action:function action(config){return(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(){var _config$modRequest2,nextMod,modRequest,results;return _regenerator["default"].wrap(function(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_config$modRequest2=config.modRequest,nextMod=_config$modRequest2.nextMod,modRequest=(0,_objectWithoutProperties2["default"])(_config$modRequest2,_excluded2);_context4.next=1;return nextMod(_objectSpread(_objectSpread({},config),{},{modRequest:modRequest}));case 1:results=_context4.sent;return _context4.abrupt("return",_action2(results));case 2:case"end":return _context4.stop();}},_callee4);}))();}});};var withIosPlugin=function withIosPlugin(config){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var nativeSymbols=resolveNativeSymbolUpload(props.uploadNativeSymbols);config=withXcodeProject(config,function(config){var xcodeProject=config.modResults;var bundleReactNativePhase=xcodeProject.pbxItemByComment('Bundle React Native code and images','PBXShellScriptBuildPhase');modifyExistingXcodeBuildScript(bundleReactNativePhase,props.skipOnConflict===true,props.releaseMode);if(nativeSymbols.enabled){addDsymUploadBuildPhase(xcodeProject,nativeSymbols.includeSource,props.skipOnConflict===true);}applyDotenvFileBuildSetting(xcodeProject,props.dotenvFile);if(props.disableSandboxing!==false){disableUserScriptSandboxing(xcodeProject);console.warn('[posthog-react-native] Setting ENABLE_USER_SCRIPT_SANDBOXING=NO on all Xcode '+'build configurations so sourcemap uploads can resolve git metadata. '+'If your org requires sandboxing to stay enabled, set `{ disableSandboxing: false }` '+'on the plugin in app.json — note that stock Expo projects may fail to build under '+'sandboxing until every script build phase declares its input/output files.');}return config;});if(nativeSymbols.enabled){config=withFinalizedXcodeProject(config,function(config){moveDsymUploadBuildPhaseToEnd(config.modResults);return config;});}return config;};var withPostHogPlugin=function withPostHogPlugin(config){var rawProps=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var props=_objectSpread(_objectSpread({},rawProps),{},{dotenvFile:resolveDotenvFileProp(rawProps.dotenvFile),releaseMode:resolveReleaseModeProp(rawProps.releaseMode,process.env.POSTHOG_RELEASE_MODE)});if(resolveNativeSymbolUpload(props.uploadNativeSymbols).enabled){config=withAndroidNativeSymbolsPlugin(config);}config=withAndroidPlugin(config,props.skipOnConflict===true);config=withPostHogGradleProperties(config,props.dotenvFile,props.releaseMode);config=withMainActivityNewIntent(config,props.patchMainActivityNewIntent!==false);return withIosPlugin(config,props);};var postHogPlugin=function postHogPlugin(config){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return withPostHogPlugin(config,props);};module.exports=postHogPlugin;module.exports.modifyExistingXcodeBuildScript=modifyExistingXcodeBuildScript;module.exports.addPostHogWithBundledScriptsToBundleShellScript=addPostHogWithBundledScriptsToBundleShellScript;module.exports.disableUserScriptSandboxing=disableUserScriptSandboxing;module.exports.buildDsymUploadShellScript=buildDsymUploadShellScript;module.exports.addDsymUploadBuildPhase=addDsymUploadBuildPhase;module.exports.moveDsymUploadBuildPhaseToEnd=moveDsymUploadBuildPhaseToEnd;module.exports.resolveNativeSymbolUpload=resolveNativeSymbolUpload;module.exports.buildAndroidSkipOnConflictGradleLine=buildAndroidSkipOnConflictGradleLine;module.exports.addPostHogAndroidGradlePluginClasspath=addPostHogAndroidGradlePluginClasspath;module.exports.applyPostHogAndroidGradlePlugin=applyPostHogAndroidGradlePlugin;module.exports.buildIosDotenvFileBuildSetting=buildIosDotenvFileBuildSetting;module.exports.applyDotenvFileBuildSetting=applyDotenvFileBuildSetting;module.exports.resolveDotenvFileProp=resolveDotenvFileProp;module.exports.buildAndroidDotenvFileGradleValue=buildAndroidDotenvFileGradleValue;module.exports.updateDotenvFileGradleProperties=updateDotenvFileGradleProperties;module.exports.POSTHOG_RELEASE_MODES=POSTHOG_RELEASE_MODES;module.exports.resolveReleaseModeProp=resolveReleaseModeProp;module.exports.updateHermesReleaseModeGradleProperties=updateHermesReleaseModeGradleProperties;module.exports.updateMainActivityNewIntentOverride=updateMainActivityNewIntentOverride;
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.POSTHOG_RELEASE_MODES=void 0;exports.addDsymUploadBuildPhase=addDsymUploadBuildPhase;exports.addPostHogAndroidGradlePluginClasspath=addPostHogAndroidGradlePluginClasspath;exports.addPostHogWithBundledScriptsToBundleShellScript=addPostHogWithBundledScriptsToBundleShellScript;exports.applyDotenvFileBuildSetting=applyDotenvFileBuildSetting;exports.applyPostHogAndroidGradlePlugin=applyPostHogAndroidGradlePlugin;exports.buildAndroidDotenvFileGradleValue=buildAndroidDotenvFileGradleValue;exports.buildAndroidSkipOnConflictGradleLine=buildAndroidSkipOnConflictGradleLine;exports.buildDsymUploadShellScript=buildDsymUploadShellScript;exports.buildIosDotenvFileBuildSetting=buildIosDotenvFileBuildSetting;exports.disableUserScriptSandboxing=disableUserScriptSandboxing;exports.modifyExistingXcodeBuildScript=modifyExistingXcodeBuildScript;exports.moveDsymUploadBuildPhaseToEnd=moveDsymUploadBuildPhaseToEnd;exports.resolveDotenvFileProp=resolveDotenvFileProp;exports.resolveNativeSymbolUpload=resolveNativeSymbolUpload;exports.resolveReleaseModeProp=resolveReleaseModeProp;exports.updateDotenvFileGradleProperties=updateDotenvFileGradleProperties;exports.updateHermesReleaseModeGradleProperties=updateHermesReleaseModeGradleProperties;exports.updateMainActivityNewIntentOverride=updateMainActivityNewIntentOverride;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _objectWithoutProperties2=_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _excluded=["nextMod"],_excluded2=["nextMod"];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 fs=require('fs');var path=require('path');var _require=require('@expo/config-plugins'),AndroidConfig=_require.AndroidConfig,withAppBuildGradle=_require.withAppBuildGradle,withBaseMod=_require.withBaseMod,withDangerousMod=_require.withDangerousMod,withGradleProperties=_require.withGradleProperties,withXcodeProject=_require.withXcodeProject;var POSTHOG_ANDROID_GRADLE_PLUGIN_VERSION='1.6.0';var resolvePostHogReactNativePackageJsonPath="[\"node\", \"--print\", \"require('path').join(require('path').dirname(require.resolve('posthog-react-native')), '..', 'tooling', 'posthog.gradle')\"].execute().text.trim()";var POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY='posthogReactNativeSkipOnConflict';var POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY='posthog.hermesReleaseMode';var POSTHOG_RELEASE_MODES=exports.POSTHOG_RELEASE_MODES=['symbol-set','event'];function resolveReleaseModeProp(releaseMode,environmentMode){var trimmed=(releaseMode===null||releaseMode===void 0?void 0:releaseMode.trim())||(environmentMode===null||environmentMode===void 0?void 0:environmentMode.trim());if(!trimmed){return undefined;}if(!POSTHOG_RELEASE_MODES.includes(trimmed)){throw new Error("[posthog-react-native] releaseMode must be one of ".concat(POSTHOG_RELEASE_MODES.join(', '),", was '").concat(trimmed,"'"));}return trimmed;}function buildAndroidSkipOnConflictGradleLine(skipOnConflict){if(!skipOnConflict){return null;}return"project.ext.".concat(POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY," = true");}var withAndroidPlugin=function withAndroidPlugin(config){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return withAppBuildGradle(config,function(config){if(config.modResults.language!=='groovy'){console.warn('Cannot configure PostHog in the app gradle because the build.gradle is not groovy');}var buildGradle=config.modResults.contents;var applyFrom="apply from: new File(".concat(resolvePostHogReactNativePackageJsonPath,")");var skipOnConflictLine=buildAndroidSkipOnConflictGradleLine(skipOnConflict);var applyBlock=skipOnConflictLine?"".concat(skipOnConflictLine,"\n").concat(applyFrom):applyFrom;var skipOnConflictPattern=new RegExp("^project\\.ext\\.".concat(POSTHOG_ANDROID_SKIP_ON_CONFLICT_PROPERTY,"\\s*=\\s*(true|false)\\n?"),'m');if(buildGradle.includes(applyFrom)){var contents=buildGradle.replace(skipOnConflictPattern,'');if(skipOnConflictLine){contents=contents.replace(applyFrom,"".concat(skipOnConflictLine,"\n").concat(applyFrom));}config.modResults.contents=contents;return config;}var pattern=/^android\s*\{/m;if(buildGradle.match(pattern)){config.modResults.contents=buildGradle.replace(pattern,"".concat(applyBlock,"\n\nandroid {"));}else{console.warn('PostHog: Could not find "android {" block in build.gradle');}return config;});};function matchingBraceIndex(s,openBraceIndex){var depth=0;for(var i=openBraceIndex;i<s.length;i++){if(s[i]==='{'){depth++;}else if(s[i]==='}'){depth--;if(depth===0){return i;}}}return-1;}function addPostHogAndroidGradlePluginClasspath(projectBuildGradle){if(projectBuildGradle.includes('posthog-android-gradle-plugin')){return{contents:projectBuildGradle,classpathPresent:true};}var classpathLine=" classpath(\"com.posthog:posthog-android-gradle-plugin:".concat(POSTHOG_ANDROID_GRADLE_PLUGIN_VERSION,"\")");var buildscriptMatch=/buildscript\s*\{/.exec(projectBuildGradle);var buildscriptOpenBrace=buildscriptMatch?buildscriptMatch.index+buildscriptMatch[0].length-1:-1;var buildscriptEnd=buildscriptOpenBrace===-1?-1:matchingBraceIndex(projectBuildGradle,buildscriptOpenBrace);var buildscriptBody=buildscriptEnd===-1?'':projectBuildGradle.slice(buildscriptOpenBrace,buildscriptEnd);var dependenciesMatch=buildscriptBody?/dependencies\s*\{/.exec(buildscriptBody):null;if(!dependenciesMatch){console.warn('PostHog: Could not find a buildscript dependencies block in the project build.gradle; '+'skipping the com.posthog.android classpath. Native symbols will not be uploaded.');return{contents:projectBuildGradle,classpathPresent:false};}var insertAt=buildscriptOpenBrace+dependenciesMatch.index+dependenciesMatch[0].length;return{contents:"".concat(projectBuildGradle.slice(0,insertAt),"\n").concat(classpathLine).concat(projectBuildGradle.slice(insertAt)),classpathPresent:true};}function applyPostHogAndroidGradlePlugin(appBuildGradle){if(/apply plugin: ["']com\.posthog\.android["']/.test(appBuildGradle)){return appBuildGradle;}var applyLine='apply plugin: "com.posthog.android"';var appPluginPattern=/^([ \t]*apply plugin: ["']com\.android\.application["'].*)$/m;if(appPluginPattern.test(appBuildGradle)){return appBuildGradle.replace(appPluginPattern,"$1\n".concat(applyLine));}var androidBlockPattern=/^android\s*\{/m;if(androidBlockPattern.test(appBuildGradle)){return appBuildGradle.replace(androidBlockPattern,"".concat(applyLine,"\n\nandroid {"));}console.warn('PostHog: Could not find where to apply com.posthog.android in the app build.gradle');return appBuildGradle;}var withFinalizedProjectBuildGradle=function withFinalizedProjectBuildGradle(config,_action){return withBaseMod(config,{platform:'android',mod:'projectBuildGradle',skipEmptyMod:false,action:function action(config){return(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(){var _config$modRequest,nextMod,modRequest,results;return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:_config$modRequest=config.modRequest,nextMod=_config$modRequest.nextMod,modRequest=(0,_objectWithoutProperties2["default"])(_config$modRequest,_excluded);_context.next=1;return nextMod(_objectSpread(_objectSpread({},config),{},{modRequest:modRequest}));case 1:results=_context.sent;return _context.abrupt("return",_action(results));case 2:case"end":return _context.stop();}},_callee);}))();}});};var withAndroidNativeSymbolsPlugin=function withAndroidNativeSymbolsPlugin(config){return withFinalizedProjectBuildGradle(config,function(){var _ref=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(config){var result,appBuildGradle,contents;return _regenerator["default"].wrap(function(_context2){while(1)switch(_context2.prev=_context2.next){case 0:if(!(config.modResults.language!=='groovy')){_context2.next=1;break;}console.warn('Cannot configure the PostHog Android Gradle plugin because the project build.gradle is not groovy');return _context2.abrupt("return",config);case 1:result=addPostHogAndroidGradlePluginClasspath(config.modResults.contents);if(!(result.contents!==config.modResults.contents)){_context2.next=3;break;}_context2.next=2;return fs.promises.writeFile(config.modResults.path,result.contents);case 2:config.modResults.contents=result.contents;case 3:if(result.classpathPresent){_context2.next=4;break;}return _context2.abrupt("return",config);case 4:_context2.next=5;return AndroidConfig.Paths.getAppBuildGradleAsync(config.modRequest.projectRoot);case 5:appBuildGradle=_context2.sent;if(!(appBuildGradle.language!=='groovy')){_context2.next=6;break;}console.warn('Cannot configure the PostHog Android Gradle plugin because the app build.gradle is not groovy');return _context2.abrupt("return",config);case 6:contents=applyPostHogAndroidGradlePlugin(appBuildGradle.contents);if(!(contents!==appBuildGradle.contents)){_context2.next=7;break;}_context2.next=7;return fs.promises.writeFile(appBuildGradle.path,contents);case 7:return _context2.abrupt("return",config);case 8:case"end":return _context2.stop();}},_callee2);}));return function(_x){return _ref.apply(this,arguments);};}());};var POSTHOG_NEW_INTENT_MARKER='posthog-new-intent';var POSTHOG_NEW_INTENT_BEGIN="// @generated begin ".concat(POSTHOG_NEW_INTENT_MARKER," - posthog-react-native (DO NOT MODIFY)");var POSTHOG_NEW_INTENT_END="// @generated end ".concat(POSTHOG_NEW_INTENT_MARKER);var NEW_INTENT_DOC=" /**\n * Records the intent that reopened the app so getIntent() stays correct.\n *\n * Works around a React Native defect that drops notification taps and deep links arriving while\n * the React context is still starting. Managed by the posthog-react-native Expo config plugin;\n * remove it with { patchMainActivityNewIntent: false } in app.json.\n * https://posthog.com/docs/workflows/push-notifications/react-native\n */";var NEW_INTENT_KOTLIN_BODY=" override fun onNewIntent(intent: android.content.Intent) {\n setIntent(intent)\n super.onNewIntent(intent)\n }";var NEW_INTENT_JAVA_BODY=" @Override\n public void onNewIntent(android.content.Intent intent) {\n setIntent(intent);\n super.onNewIntent(intent);\n }";function newIntentOverrideBlock(language){var body=language==='java'?NEW_INTENT_JAVA_BODY:NEW_INTENT_KOTLIN_BODY;return"\n ".concat(POSTHOG_NEW_INTENT_BEGIN,"\n").concat(NEW_INTENT_DOC,"\n").concat(body,"\n ").concat(POSTHOG_NEW_INTENT_END,"\n");}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');}var POSTHOG_NEW_INTENT_BLOCK_PATTERN=new RegExp("\\r?\\n?[ \\t]*".concat(escapeRegExp(POSTHOG_NEW_INTENT_BEGIN),"[\\s\\S]*?").concat(escapeRegExp(POSTHOG_NEW_INTENT_END),"[ \\t]*\\r?\\n"),'g');function literalEnd(s,start,language){var quote=s[start];var raw=quote==='"'&&s.startsWith('"""',start);var i=start+(raw?3:1);while(i<s.length){var c=s[i];if(raw){if(s.startsWith('"""',i)){while(s[i]==='"'){i++;}return i;}}else if(c==='\n'){return-1;}else if(c===quote){return i+1;}if(c==='\\'&&(!raw||language==='java')){i+=2;continue;}if(language==='kt'&"e==='"'&&c==='$'&&s[i+1]==='{'){var close=matchingBraceIndexInSource(s,i+1,language);if(close===-1){return-1;}i=close+1;continue;}i++;}return-1;}function matchingBraceIndexInSource(s,openBraceIndex,language){var depth=0;var i=openBraceIndex;while(i<s.length){var c=s[i];if(c==='/'&&s[i+1]==='/'){var end=s.indexOf('\n',i);i=end===-1?s.length:end;continue;}if(c==='/'&&s[i+1]==='*'){var depthOfComment=1;i+=2;while(i<s.length&&depthOfComment>0){if(language==='kt'&&s[i]==='/'&&s[i+1]==='*'){depthOfComment++;i+=2;continue;}if(s[i]==='*'&&s[i+1]==='/'){depthOfComment--;i+=2;continue;}i++;}if(depthOfComment>0){return-1;}continue;}if(c==='"'||c==="'"){var _end=literalEnd(s,i,language);if(_end===-1){return-1;}i=_end;continue;}if(c==='{'){depth++;}else if(c==='}'){depth--;if(depth===0){return i;}}i++;}return-1;}function maskCommentsAndLiterals(source,language){var out=source.split('');var blank=function blank(from,to){for(var j=from;j<to&&j<out.length;j++){if(out[j]!=='\n'){out[j]=' ';}}};var i=0;while(i<source.length){var c=source[i];if(c==='/'&&source[i+1]==='/'){var end=source.indexOf('\n',i);var stop=end===-1?source.length:end;blank(i,stop);i=stop;continue;}if(c==='/'&&source[i+1]==='*'){var depth=1;var j=i+2;while(j<source.length&&depth>0){if(language==='kt'&&source[j]==='/'&&source[j+1]==='*'){depth++;j+=2;continue;}if(source[j]==='*'&&source[j+1]==='/'){depth--;j+=2;continue;}j++;}blank(i,j);i=j;continue;}if(c==='"'||c==="'"){var _end2=literalEnd(source,i,language);if(_end2===-1){blank(i,source.length);return out.join('');}blank(i,_end2);i=_end2;continue;}i++;}return out.join('');}function mainActivityBody(contents,language){var code=maskCommentsAndLiterals(contents,language);var declaration=/\bclass\s+MainActivity\b/.exec(code);if(!declaration){return undefined;}var searchFrom=declaration.index+declaration[0].length;var open=code.indexOf('{',searchFrom);if(open===-1||!/^[^;{}]*$/.test(code.slice(searchFrom,open))){return undefined;}var depth=0;var close=-1;for(var i=open;i<code.length;i++){if(code[i]==='{'){depth++;}else if(code[i]==='}'){depth--;if(depth===0){close=i;break;}}}return close===-1?undefined:{open:open,close:close};}function updateMainActivityNewIntentOverride(contents,language,enabled){var withoutManagedBlock=contents.replace(POSTHOG_NEW_INTENT_BLOCK_PATTERN,'');if(!enabled){return withoutManagedBlock;}var body=mainActivityBody(withoutManagedBlock,language);if(!body){console.warn('[posthog-react-native] Could not find the MainActivity class body; skipping the onNewIntent '+'override. Notification taps delivered while the React context is starting will be lost.');return withoutManagedBlock;}var codeOnly=maskCommentsAndLiterals(withoutManagedBlock,language);if(/\b(fun|void)\s+onNewIntent\s*\(/.test(codeOnly.slice(body.open,body.close))){console.warn('[posthog-react-native] MainActivity already overrides onNewIntent; leaving it alone. '+'Add `setIntent(intent)` as its first statement so a notification tap that arrives before '+'the React context is ready is not lost, or set `{ patchMainActivityNewIntent: false }` '+'on the plugin to silence this.');return withoutManagedBlock;}return withoutManagedBlock.slice(0,body.open+1)+newIntentOverrideBlock(language)+withoutManagedBlock.slice(body.open+1);}var MAIN_ACTIVITY_SOURCE_ROOTS=['android/app/src/main/java','android/app/src/main/kotlin'];function findMainActivityPath(projectRoot){var _walk=function walk(dir){if(!fs.existsSync(dir)){return undefined;}var _iterator=_createForOfIteratorHelper(fs.readdirSync(dir,{withFileTypes:true})),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var entry=_step.value;var candidate=path.join(dir,entry.name);if(!entry.isDirectory()){if(/^MainActivity\.(kt|java)$/.test(entry.name)){return candidate;}continue;}var hit=_walk(candidate);if(hit){return hit;}}}catch(err){_iterator.e(err);}finally{_iterator.f();}return undefined;};for(var _i=0,_MAIN_ACTIVITY_SOURCE=MAIN_ACTIVITY_SOURCE_ROOTS;_i<_MAIN_ACTIVITY_SOURCE.length;_i++){var sourceRoot=_MAIN_ACTIVITY_SOURCE[_i];var hit=_walk(path.join(projectRoot,sourceRoot));if(hit){return hit;}}return undefined;}var withMainActivityNewIntent=function withMainActivityNewIntent(config,enabled){return withDangerousMod(config,['android',(function(){var _ref2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(config){var mainActivityPath,contents,updated;return _regenerator["default"].wrap(function(_context3){while(1)switch(_context3.prev=_context3.next){case 0:mainActivityPath=findMainActivityPath(config.modRequest.projectRoot);if(mainActivityPath){_context3.next=1;break;}console.warn('[posthog-react-native] Could not find MainActivity under android/app/src/main/{java,kotlin}; '+'skipping the onNewIntent override. Notification taps delivered while the React context is '+'starting will be lost.');return _context3.abrupt("return",config);case 1:_context3.next=2;return fs.promises.readFile(mainActivityPath,'utf8');case 2:contents=_context3.sent;updated=updateMainActivityNewIntentOverride(contents,mainActivityPath.endsWith('.java')?'java':'kt',enabled);if(!(updated!==contents)){_context3.next=3;break;}_context3.next=3;return fs.promises.writeFile(mainActivityPath,updated);case 3:if(!contents.includes(POSTHOG_NEW_INTENT_BEGIN)&&updated.includes(POSTHOG_NEW_INTENT_BEGIN)){console.warn("[posthog-react-native] Added an onNewIntent override to ".concat(path.relative(config.modRequest.projectRoot,mainActivityPath)," so a notification tap that arrives before the React context is ready is not lost. ")+'Set `{ patchMainActivityNewIntent: false }` on the plugin in app.json to opt out.');}return _context3.abrupt("return",config);case 4:case"end":return _context3.stop();}},_callee3);}));return function(_x2){return _ref2.apply(this,arguments);};}())]);};function modifyExistingXcodeBuildScript(script){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var releaseMode=arguments.length>2?arguments[2]:undefined;if(!(script===null||script===void 0?void 0:script.shellScript)){console.warn("[posthog-react-native] Could not find the 'Bundle React Native code and images' build phase; "+'skipping sourcemap upload setup.');return;}if(!script.shellScript.match(/(packager|scripts)\/react-native-xcode\.sh\b/)){return;}if(script.shellScript.includes('posthog-xcode.sh')){var _code=migrateLegacyPostHogWrapperInvocation(JSON.parse(script.shellScript));script.shellScript=JSON.stringify(updatePostHogBundlePhaseExports(_code,skipOnConflict,releaseMode));return;}if(script.shellScript.includes('posthog-react-native')){return;}var code=JSON.parse(script.shellScript);script.shellScript=JSON.stringify(addPostHogWithBundledScriptsToBundleShellScript(code,skipOnConflict,releaseMode));}var POSTHOG_REACT_NATIVE_XCODE_PATH="`\"$NODE_BINARY\" --print \"require('path').join(require('path').dirname(require.resolve('posthog-react-native')), '..', 'tooling', 'posthog-xcode.sh')\"`";var POSTHOG_SKIP_ON_CONFLICT_EXPORT='export POSTHOG_SKIP_ON_CONFLICT=1';var POSTHOG_RELEASE_MODE_EXPORT_PREFIX='export POSTHOG_RELEASE_MODE=';function buildBundlePhaseExports(skipOnConflict,releaseMode){var exports=[];if(skipOnConflict){exports.push(POSTHOG_SKIP_ON_CONFLICT_EXPORT);}if(releaseMode){exports.push("".concat(POSTHOG_RELEASE_MODE_EXPORT_PREFIX).concat(releaseMode));}return exports;}var REACT_NATIVE_XCODE_LINE=/^([ \t]*)(?![A-Za-z_][A-Za-z0-9_]*=)([^\n]*(?:packager|scripts)\/react-native-xcode\.sh\b[^\n]*)$/m;function migrateLegacyPostHogWrapperInvocation(script){return script.replace("/bin/sh ".concat(POSTHOG_REACT_NATIVE_XCODE_PATH),POSTHOG_REACT_NATIVE_XCODE_PATH);}function updatePostHogBundlePhaseExports(script,skipOnConflict,releaseMode){var _a;var _b;var skipArg='--posthog-skip-on-conflict --';var lines=script.replace(new RegExp("\\s*".concat(skipArg,"\\s*"),'g'),' ').split('\n').filter(function(line){return line.trim()!==POSTHOG_SKIP_ON_CONFLICT_EXPORT;}).filter(function(line){return!line.trim().startsWith(POSTHOG_RELEASE_MODE_EXPORT_PREFIX);});var exports=buildBundlePhaseExports(skipOnConflict,releaseMode);if(exports.length>0){var commandIndex=lines.findIndex(function(line){return line.includes(POSTHOG_REACT_NATIVE_XCODE_PATH);});if(commandIndex!==-1){var indent=(_b=(_a=lines[commandIndex].match(/^[ \t]*/))===null||_a===void 0?void 0:_a[0])!==null&&_b!==void 0?_b:'';lines.splice.apply(lines,[commandIndex,0].concat((0,_toConsumableArray2["default"])(exports.map(function(line){return"".concat(indent).concat(line);}))));}}return lines.join('\n');}function addPostHogWithBundledScriptsToBundleShellScript(script){var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var releaseMode=arguments.length>2?arguments[2]:undefined;return script.replace(REACT_NATIVE_XCODE_LINE,function(_match,indent,rnCommand){var exports=buildBundlePhaseExports(skipOnConflict,releaseMode).map(function(line){return"".concat(indent).concat(line,"\n");}).join('');return"".concat(exports).concat(indent).concat(POSTHOG_REACT_NATIVE_XCODE_PATH," ").concat(rnCommand);});}var POSTHOG_DSYM_BUILD_PHASE_NAME='Upload PostHog Debug Symbols';var POSTHOG_DSYM_INPUT_PATH='"$(DWARF_DSYM_FOLDER_PATH)/$(DWARF_DSYM_FILE_NAME)/Contents/Resources/DWARF/$(EXECUTABLE_NAME)"';function buildDsymUploadShellScript(){var includeSource=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var skipOnConflict=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return composeDsymUploadShellScript(includeSource,skipOnConflict);}function composeDsymUploadShellScript(includeSource,skipOnConflict){var lines=['# Upload iOS dSYMs to PostHog so native crashes can be symbolicated.','# upload-symbols.sh ships inside the posthog-ios dependency.'];if(includeSource){lines.push('# Also upload native source files for source-code context around crashes.','export POSTHOG_INCLUDE_SOURCE=1');}if(skipOnConflict){lines.push('# Skip dSYMs that already exist in PostHog with different content instead of failing the build.','export POSTHOG_SKIP_ON_CONFLICT=1');}lines.push('PODS_SCRIPT="${PODS_ROOT}/PostHog/build-tools/upload-symbols.sh"','SPM_SCRIPT="${BUILD_DIR%/Build/*}/SourcePackages/checkouts/posthog-ios/build-tools/upload-symbols.sh"','if [ -f "$PODS_SCRIPT" ]; then',' /bin/sh "$PODS_SCRIPT"','elif [ -f "$SPM_SCRIPT" ]; then',' /bin/sh "$SPM_SCRIPT"','else',' echo "warning: PostHog upload-symbols.sh not found in Pods or SwiftPM checkouts; skipping dSYM upload."','fi');return lines.join('\n');}function legacyDsymReleaseModeLines(releaseMode){return[releaseMode?"POSTHOG_RESOLVED_RELEASE_MODE=\"".concat(releaseMode,"\""):'POSTHOG_RESOLVED_RELEASE_MODE="${POSTHOG_RELEASE_MODE:-}"','case "$POSTHOG_RESOLVED_RELEASE_MODE" in',' ""|symbol-set) ;;',' event)',' # Upload dSYMs without binding them to a release, so each crash resolves its own from the',' # app version and namespace the SDK sends. posthog-ios versions whose upload-symbols.sh',' # does not read this variable ignore it and keep binding the dSYMs.',' export POSTHOG_NO_RELEASE_BIND=1',' ;;',' *)'," echo \"error: posthog release mode must be 'symbol-set' or 'event', was '$POSTHOG_RESOLVED_RELEASE_MODE'\"",' exit 1',' ;;','esac'];}function buildLegacyReleaseModeDsymUploadShellScript(includeSource,skipOnConflict,releaseMode){var lines=composeDsymUploadShellScript(includeSource,skipOnConflict).split('\n');var uploadIndex=lines.findIndex(function(line){return line.startsWith('PODS_SCRIPT=');});lines.splice.apply(lines,[uploadIndex,0].concat((0,_toConsumableArray2["default"])(legacyDsymReleaseModeLines(releaseMode))));return lines.join('\n');}function encodePbxShellScript(script){return'"'+script.replace(/"/g,'\\"')+'"';}function decodePbxShellScript(stored){if(!stored.startsWith('"')||!stored.endsWith('"')){return stored;}return stored.slice(1,-1).replace(/\\(.)/g,function(_match,ch){return ch==='n'?'\n':ch==='t'?'\t':ch;});}function isPluginGeneratedDsymUploadBuildPhase(phase){if(typeof(phase===null||phase===void 0?void 0:phase.shellScript)!=='string'){return false;}var stored=decodePbxShellScript(phase.shellScript);return[false,true].some(function(source){return[false,true].some(function(skip){return stored===buildDsymUploadShellScript(source,skip)||[undefined].concat(POSTHOG_RELEASE_MODES).some(function(mode){return stored===buildLegacyReleaseModeDsymUploadShellScript(source,skip,mode);});});});}function moveDsymUploadBuildPhaseToEnd(xcodeProject){var _a,_b;var existing=xcodeProject.pbxItemByComment(POSTHOG_DSYM_BUILD_PHASE_NAME,'PBXShellScriptBuildPhase');if(!isPluginGeneratedDsymUploadBuildPhase(existing)){return;}var buildPhases=(_b=(_a=xcodeProject.getFirstTarget)===null||_a===void 0?void 0:_a.call(xcodeProject).firstTarget)===null||_b===void 0?void 0:_b.buildPhases;if(Array.isArray(buildPhases)){var phaseIndex=buildPhases.findIndex(function(phase){return phase.comment===POSTHOG_DSYM_BUILD_PHASE_NAME;});if(phaseIndex!==-1&&phaseIndex!==buildPhases.length-1){buildPhases.push.apply(buildPhases,(0,_toConsumableArray2["default"])(buildPhases.splice(phaseIndex,1)));}}}function addDsymUploadBuildPhase(xcodeProject){var includeSource=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var skipOnConflict=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var existing=xcodeProject.pbxItemByComment(POSTHOG_DSYM_BUILD_PHASE_NAME,'PBXShellScriptBuildPhase');if(existing){if(isPluginGeneratedDsymUploadBuildPhase(existing)){existing.shellScript=encodePbxShellScript(buildDsymUploadShellScript(includeSource,skipOnConflict));existing.inputPaths=Array.from(new Set([].concat((0,_toConsumableArray2["default"])(Array.isArray(existing.inputPaths)?existing.inputPaths:[]),[POSTHOG_DSYM_INPUT_PATH])));}}else{xcodeProject.addBuildPhase([],'PBXShellScriptBuildPhase',POSTHOG_DSYM_BUILD_PHASE_NAME,null,{inputPaths:[POSTHOG_DSYM_INPUT_PATH],shellPath:'/bin/sh',shellScript:buildDsymUploadShellScript(includeSource,skipOnConflict)});}moveDsymUploadBuildPhaseToEnd(xcodeProject);}function disableUserScriptSandboxing(xcodeProject){var configurations=xcodeProject.pbxXCBuildConfigurationSection();for(var key in configurations){var configuration=configurations[key];if(configuration&&configuration.buildSettings){configuration.buildSettings.ENABLE_USER_SCRIPT_SANDBOXING='"NO"';}}}var POSTHOG_DOTENV_BUILD_SETTING='POSTHOG_CLI_DOTENV_FILE';var POSTHOG_DOTENV_GRADLE_PROPERTY='posthog.dotenvFile';function normalizeDotenvFileProp(dotenvFile){return dotenvFile.replace(/^\.\//,'');}function resolveDotenvFileProp(dotenvFile){var trimmed=dotenvFile===null||dotenvFile===void 0?void 0:dotenvFile.trim();return trimmed?trimmed:undefined;}function isAbsoluteDotenvPath(dotenvFile){return dotenvFile.startsWith('/')||/^[A-Za-z]:[\\/]/.test(dotenvFile);}function buildIosDotenvFileBuildSetting(dotenvFile){var value=isAbsoluteDotenvPath(dotenvFile)?dotenvFile:"$(SRCROOT)/../".concat(normalizeDotenvFileProp(dotenvFile));return'"'+value.replace(/(["\\])/g,'\\$1')+'"';}function applyDotenvFileBuildSetting(xcodeProject,dotenvFile){var configurations=xcodeProject.pbxXCBuildConfigurationSection();for(var key in configurations){var configuration=configurations[key];if(configuration&&configuration.buildSettings){if(dotenvFile){configuration.buildSettings[POSTHOG_DOTENV_BUILD_SETTING]=buildIosDotenvFileBuildSetting(dotenvFile);}else{delete configuration.buildSettings[POSTHOG_DOTENV_BUILD_SETTING];}}}}function buildAndroidDotenvFileGradleValue(dotenvFile){return isAbsoluteDotenvPath(dotenvFile)?dotenvFile:"../".concat(normalizeDotenvFileProp(dotenvFile));}function updateDotenvFileGradleProperties(properties,dotenvFile){var rest=properties.filter(function(item){return!(item.type==='property'&&item.key===POSTHOG_DOTENV_GRADLE_PROPERTY);});if(!dotenvFile){return rest;}rest.push({type:'property',key:POSTHOG_DOTENV_GRADLE_PROPERTY,value:buildAndroidDotenvFileGradleValue(dotenvFile)});return rest;}function updateHermesReleaseModeGradleProperties(properties,releaseMode){var rest=properties.filter(function(item){return!(item.type==='property'&&item.key===POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY);});if(!releaseMode){return rest;}rest.push({type:'property',key:POSTHOG_HERMES_RELEASE_MODE_GRADLE_PROPERTY,value:releaseMode});return rest;}var withPostHogGradleProperties=function withPostHogGradleProperties(config,dotenvFile,releaseMode){return withGradleProperties(config,function(config){config.modResults=updateDotenvFileGradleProperties(config.modResults,dotenvFile);config.modResults=updateHermesReleaseModeGradleProperties(config.modResults,releaseMode);return config;});};function resolveNativeSymbolUpload(prop){if(prop===true){return{enabled:true,includeSource:false};}if(prop&&(0,_typeof2["default"])(prop)==='object'){return{enabled:true,includeSource:prop.includeSource===true};}return{enabled:false,includeSource:false};}var withFinalizedXcodeProject=function withFinalizedXcodeProject(config,_action2){return withBaseMod(config,{platform:'ios',mod:'xcodeproj',action:function action(config){return(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(){var _config$modRequest2,nextMod,modRequest,results;return _regenerator["default"].wrap(function(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_config$modRequest2=config.modRequest,nextMod=_config$modRequest2.nextMod,modRequest=(0,_objectWithoutProperties2["default"])(_config$modRequest2,_excluded2);_context4.next=1;return nextMod(_objectSpread(_objectSpread({},config),{},{modRequest:modRequest}));case 1:results=_context4.sent;return _context4.abrupt("return",_action2(results));case 2:case"end":return _context4.stop();}},_callee4);}))();}});};var withIosPlugin=function withIosPlugin(config){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var nativeSymbols=resolveNativeSymbolUpload(props.uploadNativeSymbols);config=withXcodeProject(config,function(config){var xcodeProject=config.modResults;var bundleReactNativePhase=xcodeProject.pbxItemByComment('Bundle React Native code and images','PBXShellScriptBuildPhase');modifyExistingXcodeBuildScript(bundleReactNativePhase,props.skipOnConflict===true,props.releaseMode);if(nativeSymbols.enabled){addDsymUploadBuildPhase(xcodeProject,nativeSymbols.includeSource,props.skipOnConflict===true);}applyDotenvFileBuildSetting(xcodeProject,props.dotenvFile);if(props.disableSandboxing!==false){disableUserScriptSandboxing(xcodeProject);console.warn('[posthog-react-native] Setting ENABLE_USER_SCRIPT_SANDBOXING=NO on all Xcode '+'build configurations so sourcemap uploads can resolve git metadata. '+'If your org requires sandboxing to stay enabled, set `{ disableSandboxing: false }` '+'on the plugin in app.json — note that stock Expo projects may fail to build under '+'sandboxing until every script build phase declares its input/output files.');}return config;});if(nativeSymbols.enabled){config=withFinalizedXcodeProject(config,function(config){moveDsymUploadBuildPhaseToEnd(config.modResults);return config;});}return config;};var withPostHogPlugin=function withPostHogPlugin(config){var rawProps=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var props=_objectSpread(_objectSpread({},rawProps),{},{dotenvFile:resolveDotenvFileProp(rawProps.dotenvFile),releaseMode:resolveReleaseModeProp(rawProps.releaseMode,process.env.POSTHOG_RELEASE_MODE)});if(resolveNativeSymbolUpload(props.uploadNativeSymbols).enabled){config=withAndroidNativeSymbolsPlugin(config);}config=withAndroidPlugin(config,props.skipOnConflict===true);config=withPostHogGradleProperties(config,props.dotenvFile,props.releaseMode);config=withMainActivityNewIntent(config,props.patchMainActivityNewIntent!==false);return withIosPlugin(config,props);};var postHogPlugin=function postHogPlugin(config){var props=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return withPostHogPlugin(config,props);};module.exports=postHogPlugin;module.exports.modifyExistingXcodeBuildScript=modifyExistingXcodeBuildScript;module.exports.addPostHogWithBundledScriptsToBundleShellScript=addPostHogWithBundledScriptsToBundleShellScript;module.exports.disableUserScriptSandboxing=disableUserScriptSandboxing;module.exports.buildDsymUploadShellScript=buildDsymUploadShellScript;module.exports.addDsymUploadBuildPhase=addDsymUploadBuildPhase;module.exports.moveDsymUploadBuildPhaseToEnd=moveDsymUploadBuildPhaseToEnd;module.exports.resolveNativeSymbolUpload=resolveNativeSymbolUpload;module.exports.buildAndroidSkipOnConflictGradleLine=buildAndroidSkipOnConflictGradleLine;module.exports.addPostHogAndroidGradlePluginClasspath=addPostHogAndroidGradlePluginClasspath;module.exports.applyPostHogAndroidGradlePlugin=applyPostHogAndroidGradlePlugin;module.exports.buildIosDotenvFileBuildSetting=buildIosDotenvFileBuildSetting;module.exports.applyDotenvFileBuildSetting=applyDotenvFileBuildSetting;module.exports.resolveDotenvFileProp=resolveDotenvFileProp;module.exports.buildAndroidDotenvFileGradleValue=buildAndroidDotenvFileGradleValue;module.exports.updateDotenvFileGradleProperties=updateDotenvFileGradleProperties;module.exports.POSTHOG_RELEASE_MODES=POSTHOG_RELEASE_MODES;module.exports.resolveReleaseModeProp=resolveReleaseModeProp;module.exports.updateHermesReleaseModeGradleProperties=updateHermesReleaseModeGradleProperties;module.exports.updateMainActivityNewIntentOverride=updateMainActivityNewIntentOverride;
|
|
2
2
|
//# sourceMappingURL=expoconfig.js.map
|