79 lines
2.6 KiB
TypeScript
79 lines
2.6 KiB
TypeScript
import PostHog from 'posthog-react-native';
|
|
|
|
type AnalyticsProperties = Record<string, unknown>;
|
|
|
|
type SafeAnalytics = {
|
|
capture: (event: string, properties?: AnalyticsProperties) => void;
|
|
identify: (userId: string, properties?: AnalyticsProperties) => void;
|
|
/** Setzt Person-Properties ohne die User-ID zu aendern (z. B. Experiment-Varianten). */
|
|
identifyProperties: (properties: AnalyticsProperties) => void;
|
|
screen: (name: string, properties?: AnalyticsProperties) => void;
|
|
reset: () => void;
|
|
};
|
|
|
|
const POSTHOG_API_KEY = (
|
|
process.env.EXPO_PUBLIC_POSTHOG_API_KEY || 'phc_FX6HRgx9NSpS5moxjMF6xyc37yMwjoeu6TbWUqNNKlk'
|
|
).trim();
|
|
const POSTHOG_HOST = (process.env.EXPO_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com').trim();
|
|
|
|
// Kein Provider im Layout — die Provider-Variante (Autocapture) hat frueher den
|
|
// App-Start zerlegt (siehe Commit "App chrash + seo"). Die Instanz laeuft rein in JS,
|
|
// scheitert die Initialisierung, bleibt client null und alle Aufrufe sind no-ops.
|
|
let client: PostHog | null = null;
|
|
|
|
try {
|
|
if (POSTHOG_API_KEY.startsWith('phc_')) {
|
|
client = new PostHog(POSTHOG_API_KEY, {
|
|
host: POSTHOG_HOST,
|
|
captureAppLifecycleEvents: true, // Application Opened/Backgrounded → DAU/WAU-Dashboards
|
|
});
|
|
}
|
|
} catch (error) {
|
|
console.warn('[Analytics] PostHog initialization failed — analytics disabled.', error);
|
|
client = null;
|
|
}
|
|
|
|
const safeAnalytics: SafeAnalytics = {
|
|
capture: (event, properties) => {
|
|
try {
|
|
client?.capture(event, properties as Record<string, string>);
|
|
} catch (error) {
|
|
console.warn('[Analytics] capture failed', event, error);
|
|
}
|
|
},
|
|
identify: (userId, properties) => {
|
|
try {
|
|
client?.identify(userId, properties as Record<string, string>);
|
|
} catch (error) {
|
|
console.warn('[Analytics] identify failed', error);
|
|
}
|
|
},
|
|
identifyProperties: (properties) => {
|
|
try {
|
|
// PostHog RN: register() haengt die Properties an alle folgenden Events an,
|
|
// damit laesst sich der komplette Funnel nach Variante segmentieren.
|
|
client?.register(properties as Record<string, string>);
|
|
} catch (error) {
|
|
console.warn('[Analytics] identifyProperties failed', error);
|
|
}
|
|
},
|
|
screen: (name, properties) => {
|
|
try {
|
|
client?.screen(name, properties as Record<string, string>);
|
|
} catch (error) {
|
|
console.warn('[Analytics] screen failed', name, error);
|
|
}
|
|
},
|
|
reset: () => {
|
|
try {
|
|
client?.reset();
|
|
} catch (error) {
|
|
console.warn('[Analytics] reset failed', error);
|
|
}
|
|
},
|
|
};
|
|
|
|
export const Analytics = safeAnalytics;
|
|
|
|
export const useSafeAnalytics = (): SafeAnalytics => safeAnalytics;
|