@kissmyappss/react-native 0.0.0-stage → 1.1.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/src/device.ts ADDED
@@ -0,0 +1,59 @@
1
+ // What React Native itself can tell about the device, with no native module to link.
2
+
3
+ import { Dimensions, NativeModules, Platform } from 'react-native'
4
+ import type { DeviceInfo } from './client'
5
+
6
+ function timezone(): string {
7
+ try {
8
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
9
+ } catch {
10
+ return 'UTC'
11
+ }
12
+ }
13
+
14
+ function language(): string {
15
+ const fromSettings: unknown =
16
+ Platform.OS === 'ios'
17
+ ? (NativeModules.SettingsManager?.settings?.AppleLocale ??
18
+ NativeModules.SettingsManager?.settings?.AppleLanguages?.[0])
19
+ : NativeModules.I18nManager?.localeIdentifier
20
+ if (typeof fromSettings === 'string' && fromSettings)
21
+ return fromSettings.replace(/_/g, '-').split('@')[0]
22
+ try {
23
+ return Intl.DateTimeFormat().resolvedOptions().locale || 'en'
24
+ } catch {
25
+ return 'en'
26
+ }
27
+ }
28
+
29
+ export function deviceInfo(): DeviceInfo {
30
+ const screen = Dimensions.get('screen')
31
+ const shortSide = Math.min(screen.width, screen.height)
32
+ const constants = (Platform.constants ?? {}) as Record<string, unknown>
33
+ if (Platform.OS === 'ios') {
34
+ const pad = Platform.isPad === true || constants.interfaceIdiom === 'pad'
35
+ return {
36
+ platform: 'ios',
37
+ os_name: pad ? 'iPadOS' : 'iOS',
38
+ os_version: String(constants.osVersion ?? Platform.Version),
39
+ device_type: pad ? 'tablet' : 'mobile',
40
+ device_model: pad ? 'iPad' : 'iPhone',
41
+ screen_width: screen.width,
42
+ screen_height: screen.height,
43
+ timezone: timezone(),
44
+ language: language(),
45
+ }
46
+ }
47
+ const model = typeof constants.Model === 'string' ? constants.Model : undefined
48
+ return {
49
+ platform: 'android',
50
+ os_name: 'Android',
51
+ os_version: String(constants.Release ?? Platform.Version),
52
+ device_type: shortSide >= 600 ? 'tablet' : 'mobile',
53
+ device_model: model,
54
+ screen_width: screen.width,
55
+ screen_height: screen.height,
56
+ timezone: timezone(),
57
+ language: language(),
58
+ }
59
+ }
package/src/index.ts ADDED
@@ -0,0 +1,163 @@
1
+ // KissMyApps analytics for React Native: sessions, installs, opens, screens and your own
2
+ // events, sent to your KissMyApps project, plus install attribution and deep links. Plain
3
+ // JavaScript; the optional native module KissMyAppsAttribution adds the device key, the
4
+ // Google Play install referrer and the Apple Ads token when it is linked.
5
+
6
+ import { AppState, Linking, NativeModules } from 'react-native'
7
+ import type { AttributionInfo, AttributionRequest, DeepLink } from './attribution'
8
+ import { httpsLink } from './attribution'
9
+ import { KmaClient, SDK_VERSION } from './client'
10
+ import type { ClientOptions, Properties, RevenueOptions, Storage } from './client'
11
+ import { deviceInfo } from './device'
12
+ import { navigationTracker } from './navigation'
13
+ import type { NavigationRefLike } from './navigation'
14
+
15
+ export { KmaClient, SDK_VERSION } from './client'
16
+ export type { ClientOptions, DeviceInfo, Properties, RevenueOptions, Storage } from './client'
17
+ export type { AttributionInfo, DeepLink } from './attribution'
18
+ export type { NavigationRefLike } from './navigation'
19
+
20
+ export interface InitOptions extends ClientOptions {
21
+ /** Where the SDK keeps its IDs and offline queue, such as AsyncStorage. */
22
+ storage?: Storage
23
+ /**
24
+ * Read the link that opened the app (Linking.getInitialURL) and links opened while it runs
25
+ * (Linking's `url` events). Default true. Turn it off to call handleDeepLink yourself.
26
+ */
27
+ deepLinks?: boolean
28
+ }
29
+
30
+ interface NativeAttribution {
31
+ getAttributionInfo(request: AttributionRequest): Promise<AttributionInfo | null>
32
+ /** Android: the activity was reopened from Recents, so its link is an old one. */
33
+ launchedFromHistory?(): Promise<boolean>
34
+ }
35
+
36
+ /** The link that opened the app, unless Android reopened the activity from Recents. */
37
+ async function openingLink(native: NativeAttribution | null): Promise<string | null> {
38
+ const url = await Linking.getInitialURL()
39
+ if (!url || !native?.launchedFromHistory) return url
40
+ const old = await native.launchedFromHistory().catch(() => false)
41
+ return old === true ? null : url
42
+ }
43
+
44
+ /** The optional native module, when the app has it linked (not in Expo Go). */
45
+ function nativeAttribution(): NativeAttribution | null {
46
+ const module: unknown = NativeModules.KissMyAppsAttribution
47
+ return module && typeof (module as NativeAttribution).getAttributionInfo === 'function'
48
+ ? (module as NativeAttribution)
49
+ : null
50
+ }
51
+
52
+ let client: KmaClient | null = null
53
+ let deepLinkHandler: ((link: DeepLink) => void) | null = null
54
+ // Calls made before init run once it is called.
55
+ const early: ((client: KmaClient) => void)[] = []
56
+
57
+ function call(run: (client: KmaClient) => void): void {
58
+ if (client) run(client)
59
+ else if (early.length < 100) early.push(run)
60
+ }
61
+
62
+ export const KissMyApps = {
63
+ /** Starts the SDK once, as early as possible, with the project's client key. */
64
+ init(options: InitOptions): KmaClient {
65
+ if (client) return client
66
+ const native = nativeAttribution()
67
+ // Linking is there in every React Native app; a test's stand-in may leave it out.
68
+ const links =
69
+ options.deepLinks !== false &&
70
+ options.attribution !== false &&
71
+ Boolean(Linking?.getInitialURL)
72
+ const started = new KmaClient(options, {
73
+ storage: options.storage ?? null,
74
+ device: deviceInfo,
75
+ fetch: (url, init) => fetch(url, init),
76
+ sdk: `kma-react-native/${SDK_VERSION}`,
77
+ initialLink: links ? () => openingLink(native) : undefined,
78
+ attributionInfo: native ? (request) => native.getAttributionInfo(request) : undefined,
79
+ })
80
+ client = started
81
+ if (deepLinkHandler) started.onDeepLink(deepLinkHandler)
82
+ if (AppState.currentState !== 'background') started.foreground()
83
+ AppState.addEventListener('change', (state) => {
84
+ if (state === 'active') started.foreground()
85
+ else if (state === 'background') started.background()
86
+ })
87
+ if (links) Linking.addEventListener?.('url', ({ url }) => started.handleDeepLink(url))
88
+ for (const run of early.splice(0)) run(started)
89
+ return started
90
+ },
91
+ /**
92
+ * Reports a link that opened the app. With `deepLinks` on (the default) the SDK already
93
+ * reads Linking, so call this only for links that reach the app another way. Returns false
94
+ * when the link is not sent (not an https link, attribution off, opted out).
95
+ */
96
+ handleDeepLink(url: string): boolean {
97
+ if (client) return client.handleDeepLink(url)
98
+ if (!httpsLink(url)) return false
99
+ call((kma) => kma.handleDeepLink(url))
100
+ return true
101
+ },
102
+ /**
103
+ * Where deep links go: the deferred one after an install, and one each time a link opens
104
+ * the app. Each is handed over once; one that arrives before a handler is set waits for it.
105
+ * Returns a function that removes the handler.
106
+ */
107
+ onDeepLink(handler: (link: DeepLink) => void): () => void {
108
+ deepLinkHandler = handler
109
+ client?.onDeepLink(handler)
110
+ return () => {
111
+ if (deepLinkHandler !== handler) return
112
+ deepLinkHandler = null
113
+ client?.onDeepLink(null)
114
+ }
115
+ },
116
+ track(name: string, properties?: Properties): void {
117
+ call((kma) => kma.track(name, properties))
118
+ },
119
+ /**
120
+ * Records a payment: the amount in major units (9.99, not 999), negative for a refund, and
121
+ * its ISO 4217 currency code, such as `revenue(9.99, 'USD', { transactionId })`.
122
+ */
123
+ revenue(amount: number, currency: string, options?: RevenueOptions): void {
124
+ call((kma) => kma.revenue(amount, currency, options))
125
+ },
126
+ screen(name: string, properties?: Properties): void {
127
+ call((kma) => kma.screen(name, properties))
128
+ },
129
+ identify(userId: string | number, traits?: Properties): void {
130
+ call((kma) => kma.identify(userId, traits))
131
+ },
132
+ setTraits(traits: Properties): void {
133
+ call((kma) => kma.setTraits(traits))
134
+ },
135
+ reset(): void {
136
+ call((kma) => kma.reset())
137
+ },
138
+ flush(): Promise<void> {
139
+ return client?.flush() ?? Promise.resolve()
140
+ },
141
+ optOut(): void {
142
+ call((kma) => kma.optOut())
143
+ },
144
+ optIn(): void {
145
+ call((kma) => kma.optIn())
146
+ },
147
+ getAnonymousId(): string | null {
148
+ return client?.getAnonymousId() ?? null
149
+ },
150
+ getSessionId(): string | null {
151
+ return client?.getSessionId() ?? null
152
+ },
153
+ }
154
+
155
+ /**
156
+ * Screen views from React Navigation:
157
+ * `<NavigationContainer ref={ref} {...trackNavigation(ref)}>`.
158
+ */
159
+ export function trackNavigation(ref: NavigationRefLike) {
160
+ return navigationTracker(ref, (name) => KissMyApps.screen(name))
161
+ }
162
+
163
+ export default KissMyApps
@@ -0,0 +1,18 @@
1
+ // Screen views from React Navigation, without depending on it: anything with
2
+ // getCurrentRoute(), such as the ref from createNavigationContainerRef(), works.
3
+
4
+ export interface NavigationRefLike {
5
+ getCurrentRoute(): { name: string } | undefined
6
+ }
7
+
8
+ /** Handlers for NavigationContainer's onReady and onStateChange that report each new screen. */
9
+ export function navigationTracker(ref: NavigationRefLike, onScreen: (name: string) => void) {
10
+ let last: string | undefined
11
+ const report = () => {
12
+ const name = ref.getCurrentRoute()?.name
13
+ if (!name || name === last) return
14
+ last = name
15
+ onScreen(name)
16
+ }
17
+ return { onReady: report, onStateChange: report }
18
+ }