react-native-kochava-measurement
Version:
A lightweight and easy to integrate SDK, providing first-class integration with Kochava’s installation attribution and analytics platform.
606 lines (539 loc) • 22.4 kB
text/typescript
//
// KochavaMeasurement (ReactNative)
//
// Copyright (c) 2018 - 2024 Kochava, Inc. All rights reserved.
//
// Imports
import { NativeModules, NativeEventEmitter } from 'react-native';
// Native Measurement Instance.
const { RNKochavaMeasurement } = NativeModules;
const RNKochavaMeasurementEvent = RNKochavaMeasurement != null ? new NativeEventEmitter(NativeModules.RNKochavaMeasurement) : null;
//
// Log Levels
//
// Defaults to Info
//
export enum KochavaMeasurementLogLevel {
None = "none",
Error = "error",
Warn = "warn",
Info = "info",
Debug = "debug",
Trace = "trace"
}
//
// Standard Event Types
//
// For samples and expected usage see: https://support.kochava.com/reference-information/post-install-event-examples/
//
export enum KochavaMeasurementEventType {
Achievement = "Achievement",
AddToCart = "Add to Cart",
AddToWishList = "Add to Wish List",
CheckoutStart = "Checkout Start",
LevelComplete = "Level Complete",
Purchase = "Purchase",
Rating = "Rating",
RegistrationComplete = "Registration Complete",
Search = "Search",
TutorialComplete = "Tutorial Complete",
View = "View",
AdView = "Ad View",
PushReceived = "Push Received",
PushOpened = "Push Opened",
ConsentGranted = "Consent Granted",
Deeplink = "_Deeplink",
AdClick = "Ad Click",
StartTrial = "Start Trial",
Subscribe = "Subscribe"
}
//
// Kochava Measurement Event
//
export class KochavaMeasurementEvent {
_eventName: string;
_eventData: any = {};
_iosAppStoreReceiptBase64String: string | null = null;
_androidGooglePlayReceiptData: string | null = null;
_androidGooglePlayReceiptSignature:string | null = null;
// Constructor
constructor(eventName: string) {
this._eventName = eventName;
}
// Send the event.
send(): void {
KochavaMeasurement.instance.sendEventWithEvent(this);
}
// Set a custom key/value on the event where the type of the value is a string.
setCustomStringValue(key: string, value: string): void {
if(key && value && typeof(value) === "string") {
this._eventData[key] = value;
}
}
// Set a custom key/value on the event where the type of the value is a boolean.
setCustomBoolValue(key: string, value: boolean): void {
if(key && value != null && typeof(value) === "boolean") {
this._eventData[key] = value;
}
}
// Set a custom key/value on the event where the type of the value is a number.
setCustomNumberValue(key: string, value: number): void {
if(key && value != null && typeof(value) === "number") {
this._eventData[key] = value;
}
}
// (Internal) Set a custom key/value on the event where the type of the value is a dictionary.
_setCustomDictionaryValue(key: string, value: object): void {
if(key && value != null && typeof(value) === "object") {
this._eventData[key] = value;
}
}
// (Android Only) Set the receipt from the Android Google Play Store.
setAndroidGooglePlayReceipt(data: string, signature: string): void {
if(data && typeof(data) === "string" && signature && typeof(signature) === "string") {
this._androidGooglePlayReceiptData = data;
this._androidGooglePlayReceiptSignature = signature;
}
}
// (iOS Only) Set the receipt from the iOS Apple App Store.
setIosAppStoreReceipt(base64String: string): void {
if(base64String && typeof(base64String) === "string") {
this._iosAppStoreReceiptBase64String = base64String;
}
}
//
// Standard Event Parameters.
//
setAction(value: string): void { this.setCustomStringValue("action", value); }
setBackground(value: boolean): void { this.setCustomBoolValue("background", value); }
setCheckoutAsGuest(value: string): void { this.setCustomStringValue("checkout_as_guest", value); }
setCompleted(value: boolean): void { this.setCustomBoolValue("completed", value); }
setContentId(value: string): void { this.setCustomStringValue("content_id", value); }
setContentType(value: string): void { this.setCustomStringValue("content_type", value); }
setCurrency(value: string): void { this.setCustomStringValue("currency", value); }
setDate(value: string): void { this.setCustomStringValue("date", value); }
setDescription(value: string): void { this.setCustomStringValue("description", value); }
setDestination(value: string): void { this.setCustomStringValue("destination", value); }
setDuration(value: number): void { this.setCustomNumberValue("duration", value); }
setEndDate(value: string): void { this.setCustomStringValue("end_date", value); }
setItemAddedFrom(value: string): void { this.setCustomStringValue("item_added_from", value); }
setLevel(value: string): void { this.setCustomStringValue("level", value); }
setMaxRatingValue(value: number): void { this.setCustomNumberValue("max_rating_value", value); }
setName(value: string): void { this.setCustomStringValue("name", value); }
setOrderId(value: string): void { this.setCustomStringValue("order_id", value); }
setOrigin(value: string): void { this.setCustomStringValue("origin", value); }
setPayload(value: object): void { this._setCustomDictionaryValue("payload", value); }
setPrice(value: number): void { this.setCustomNumberValue("price", value); }
setQuantity(value: number): void { this.setCustomNumberValue("quantity", value); }
setRatingValue(value: number): void { this.setCustomNumberValue("rating_value", value); }
setReceiptId(value: string): void { this.setCustomStringValue("receipt_id", value); }
setReferralFrom(value: string): void { this.setCustomStringValue("referral_from", value); }
setRegistrationMethod(value: string): void { this.setCustomStringValue("registration_method", value); }
setResults(value: string): void { this.setCustomStringValue("results", value); }
setScore(value: string): void { this.setCustomStringValue("score", value); }
setSearchTerm(value: string): void { this.setCustomStringValue("search_term", value); }
setSource(value: string): void { this.setCustomStringValue("source", value); }
setSpatialX(value: number): void { this.setCustomNumberValue("spatial_x", value); }
setSpatialY(value: number): void { this.setCustomNumberValue("spatial_y", value); }
setSpatialZ(value: number): void { this.setCustomNumberValue("spatial_z", value); }
setStartDate(value: string): void { this.setCustomStringValue("start_date", value); }
setSuccess(value: string): void { this.setCustomStringValue("success", value); }
setUri(value: string): void { this.setCustomStringValue("uri", value); }
setUserId(value: string): void { this.setCustomStringValue("user_id", value); }
setUserName(value: string): void { this.setCustomStringValue("user_name", value); }
setValidated(value: string): void { this.setCustomStringValue("validated", value); }
//
// Ad LTV Event Parameters
//
setAdCampaignId(value: string): void { this.setCustomStringValue("ad_campaign_id", value); }
setAdCampaignName(value: string): void { this.setCustomStringValue("ad_campaign_name", value); }
setAdDeviceType(value: string): void { this.setCustomStringValue("device_type", value); }
setAdGroupId(value: string): void { this.setCustomStringValue("ad_group_id", value); }
setAdGroupName(value: string): void { this.setCustomStringValue("ad_group_name", value); }
setAdMediationName(value: string): void { this.setCustomStringValue("ad_mediation_name", value); }
setAdNetworkName(value: string): void { this.setCustomStringValue("ad_network_name", value); }
setAdPlacement(value: string): void { this.setCustomStringValue("placement", value); }
setAdSize(value: string): void { this.setCustomStringValue("ad_size", value); }
setAdType(value: string): void { this.setCustomStringValue("ad_type", value); }
// Return all the event info in the form to pass down to the native layer.
getData(): object {
return {
"name": this._eventName,
"data": this._eventData,
"iosAppStoreReceiptBase64String": this._iosAppStoreReceiptBase64String,
"androidGooglePlayReceiptData": this._androidGooglePlayReceiptData,
"androidGooglePlayReceiptSignature": this._androidGooglePlayReceiptSignature
};
}
}
//
// Kochava Measurement Install Attribution Result
//
export class KochavaMeasurementInstallAttribution {
retrieved: boolean;
raw: object;
attributed: boolean;
firstInstall: boolean;
// Constructor
constructor(serializedData: string | null) {
if(serializedData == null) {
this.retrieved = false;
this.raw = {};
this.attributed = false;
this.firstInstall = false;
} else {
var data = JSON.parse(serializedData);
this.retrieved = data["retrieved"] ?? false;
this.raw = data["raw"] ?? {};
this.attributed = data["attributed"] ?? false;
this.firstInstall = data["firstInstall"] ?? false;
}
}
}
//
// Kochava Measurement Deeplink Result
//
export class KochavaMeasurementDeeplink {
destination: string;
raw: object;
// Constructor
constructor(serializedData: string | null) {
if(serializedData == null) {
this.destination = "";
this.raw = {};
} else {
var data = JSON.parse(serializedData);
this.destination = data["destination"] ?? "";
this.raw = data["raw"] ?? {};
}
}
}
//
// Kochava Measurement Init Result
//
export class KochavaMeasurementInit {
consentGdprApplies: boolean;
// Constructor
constructor(serializedData: string | null) {
if(serializedData == null) {
this.consentGdprApplies = false;
} else {
var data = JSON.parse(serializedData);
this.consentGdprApplies = data["consentGdprApplies"] ?? false;
}
}
}
//
// Kochava Measurement Init Completed
//
type KochavaMeasurementInitCompletedListener = (init: KochavaMeasurementInit) => void;
//
// Kochava Measurement SDK
//
// A lightweight and easy to integrate SDK, providing first-class integration with Kochava’s installation attribution and analytics platform.
// Getting Started: https://support.kochava.com/sdk-integration/reactnative-sdk-integration/
//
export class KochavaMeasurement {
// Singleton Instance
static instance: KochavaMeasurement = new KochavaMeasurement();
// Internal State
_registeredAndroidAppGuid: string | null = null;
_registeredIosAppGuid: string | null = null;
_registeredPartnerName: string | null = null;
// Callback handler
_initCompletedListener: KochavaMeasurementInitCompletedListener | null = null;
_initCompletedListenerSubscription = RNKochavaMeasurementEvent != null ? RNKochavaMeasurementEvent.addListener("KochavaMeasurementInitCompleted", (event) => {
if(this._initCompletedListener == null) {
return;
}
this._initCompletedListener(new KochavaMeasurementInit(event))
}) : null;
// Reserved function, only use if directed to by your Client Success Manager.
executeAdvancedInstruction(name: string, value: string): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.executeAdvancedInstruction(name, value);
}
// Set the log level. This should be set prior to starting the SDK.
setLogLevel(logLevel: KochavaMeasurementLogLevel): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.setLogLevel(logLevel);
}
// Set the sleep state.
setSleep(sleep: boolean): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.setSleep(sleep);
}
// Set if app level advertising tracking should be limited.
setAppLimitAdTracking(appLimitAdTracking: boolean): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.setAppLimitAdTracking(appLimitAdTracking);
}
// Register a custom device identifier for install attribution.
registerCustomDeviceIdentifier(name: string, value: string | null): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.registerCustomDeviceIdentifier(name, value);
}
// Register a custom value to be included in SDK payloads.
registerCustomStringValue(name: string, value: string | null): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.registerCustomStringValue(name, value);
}
// Register a custom value to be included in SDK payloads.
registerCustomBoolValue(name: string, value: boolean | null): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.registerCustomBoolValue(name, value);
}
// Register a custom value to be included in SDK payloads.
registerCustomNumberValue(name: string, value: number | null): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.registerCustomNumberValue(name, value);
}
// Register an Identity Link that allows linking different identities together in the form of key and value pairs.
registerIdentityLink(name: string, value: string): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.registerIdentityLink(name, value);
}
// (Android Only) Enable the Instant App feature by setting the instant app guid.
enableAndroidInstantApps(instantAppGuid: string): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.enableAndroidInstantApps(instantAppGuid);
}
// (iOS Only) Enable App Clips by setting the Container App Group Identifier for App Clips data migration.
enableIosAppClips(containerAppGroupIdentifier: string): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.enableIosAppClips(containerAppGroupIdentifier);
}
// (iOS Only) Enable App Tracking Transparency.
enableIosAtt(): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.enableIosAtt();
}
// (iOS Only) Set the amount of time in seconds to wait for App Tracking Transparency Authorization. Default 30 seconds.
setIosAttAuthorizationWaitTime(waitTime: number): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.setIosAttAuthorizationWaitTime(waitTime);
}
// (iOS Only) Set if the SDK should automatically request App Tracking Transparency Authorization on start. Default true.
setIosAttAuthorizationAutoRequest(autoRequest: boolean): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.setIosAttAuthorizationAutoRequest(autoRequest);
}
// Register a privacy profile, creating or overwriting an existing pofile.
registerPrivacyProfile(name: string, keys: string[]): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.registerPrivacyProfile(name, JSON.stringify(keys ?? []));
}
// Enable or disable an existing privacy profile.
setPrivacyProfileEnabled(name: string, enabled: boolean): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.setPrivacyProfileEnabled(name, enabled);
}
// Set the init completed callback listener.
setInitCompletedListener(initCompletedListener: KochavaMeasurementInitCompletedListener | null): void {
if(RNKochavaMeasurement == null) {
return;
}
this._initCompletedListener = initCompletedListener;
RNKochavaMeasurement.setInitCompletedListener(initCompletedListener != null);
}
// Set if consent has been explicitly opted in or out by the user.
setIntelligentConsentGranted(granted: boolean): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.setIntelligentConsentGranted(granted);
}
// Return if the SDK is currently started.
getStarted(): Promise<boolean> {
if(RNKochavaMeasurement == null) {
return Promise.resolve(false);
}
return RNKochavaMeasurement.getStarted();
}
// Register the Android App GUID. Do this prior to calling Start.
registerAndroidAppGuid(androidAppGuid: string): void {
this._registeredAndroidAppGuid = androidAppGuid;
}
// Register the iOS App GUID. Do this prior to calling Start.
registerIosAppGuid(iosAppGuid: string): void {
this._registeredIosAppGuid = iosAppGuid;
}
// Register your Partner Name. Do this prior to calling Start.
//
// NOTE: Only use this method if directed to by your Client Success Manager.
registerPartnerName(partnerName: string): void {
this._registeredPartnerName = partnerName;
}
// Start the SDK with the previously registered App GUID or Partner Name.
start(): void {
if(RNKochavaMeasurement == null) {
console.log("KVA/Measurement: ERROR: Attempting to start the SDK on an unsupported platform.");
return;
}
let wrapper = {
name: "ReactNative",
version: "3.0.0",
build_date: "2024-12-12T18:45:54Z"
};
RNKochavaMeasurement.executeAdvancedInstruction("wrapper", JSON.stringify(wrapper));
console.log("----PEPPERONI----")
RNKochavaMeasurement.start(this._registeredAndroidAppGuid, this._registeredIosAppGuid, this._registeredPartnerName);
}
// Shut down the SDK and optionally delete all local SDK data.
//
// NOTE: Care should be taken when using this method as deleting the SDK data will make it reset back to a first install state.
shutdown(deleteData: boolean): void {
if(RNKochavaMeasurement == null) {
return;
}
this._registeredAndroidAppGuid = null;
this._registeredIosAppGuid = null;
this._registeredPartnerName = null;
RNKochavaMeasurement.shutdown(deleteData);
}
// Return the Kochava Device ID.
retrieveInstallId(): Promise<string> {
if(RNKochavaMeasurement == null) {
return Promise.resolve("");
}
return RNKochavaMeasurement.retrieveInstallId();
}
// Retrieve install attribution data from the server.
retrieveInstallAttribution(): Promise<KochavaMeasurementInstallAttribution> {
return new Promise(function(resolve, reject) {
if(RNKochavaMeasurement == null) {
return resolve(new KochavaMeasurementInstallAttribution(null));
}
RNKochavaMeasurement.retrieveInstallAttribution().then((value: string) => {
resolve(new KochavaMeasurementInstallAttribution(value));
}).catch((error) => {
reject(error)
});
});
}
// Process a launch deeplink using the default 10 second timeout.
processDeeplink(path: string): Promise<KochavaMeasurementDeeplink> {
return new Promise(function(resolve, reject) {
if(RNKochavaMeasurement == null) {
return resolve(new KochavaMeasurementDeeplink(null));
}
RNKochavaMeasurement.processDeeplink(path).then((value: string) => {
resolve(new KochavaMeasurementDeeplink(value));
}).catch((error) => {
reject(error)
});
});
}
// Process a launch deeplink using a custom timeout in seconds.
processDeeplinkWithOverrideTimeout(path: string, timeout: number): Promise<KochavaMeasurementDeeplink> {
return new Promise(function(resolve, reject) {
if(RNKochavaMeasurement == null) {
return resolve(new KochavaMeasurementDeeplink(null));
}
RNKochavaMeasurement.processDeeplinkWithOverrideTimeout(path, timeout).then((value: string) => {
resolve(new KochavaMeasurementDeeplink(value));
}).catch((error) => {
reject(error)
});
});
}
// Registers a default parameter on every event.
registerDefaultEventStringParameter(name: string, value: string | null): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.registerDefaultEventStringParameter(name, value);
}
// Registers a default parameter on every event.
registerDefaultEventBoolParameter(name: string, value: boolean | null): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.registerDefaultEventBoolParameter(name, value);
}
// Registers a default parameter on every event.
registerDefaultEventNumberParameter(name: string, value: number | null): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.registerDefaultEventNumberParameter(name, value);
}
// Registers a default user_id value on every event.
registerDefaultEventUserId(value: string | null): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.registerDefaultEventUserId(value);
}
// Send an event.
sendEvent(name: string): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.sendEvent(name);
}
// Send an event with string data.
sendEventWithString(name: string, data: string): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.sendEventWithString(name, data);
}
// Send an event with dictionary data.
sendEventWithDictionary(name: string, data: object): void {
if(RNKochavaMeasurement == null) {
return;
}
RNKochavaMeasurement.sendEventWithDictionary(name, JSON.stringify(data ?? {}));
}
// (Internal) Send an event object (Called via Event.send()).
sendEventWithEvent(event: KochavaMeasurementEvent): void {
if(RNKochavaMeasurement == null) {
return;
}
if(event == null) {
return;
}
RNKochavaMeasurement.sendEventWithEvent(JSON.stringify(event.getData()));
}
// Build and return an event using a Standard Event Type.
buildEventWithEventType(type: KochavaMeasurementEventType): KochavaMeasurementEvent {
return new KochavaMeasurementEvent(type);
}
// Build and return an event using a custom name.
buildEventWithEventName(name: string): KochavaMeasurementEvent {
return new KochavaMeasurementEvent(name);
}
}