@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/client.ts ADDED
@@ -0,0 +1,1087 @@
1
+ // The KissMyApps app client, with no React Native in it: the app's storage, device and
2
+ // network come in through `Environment`, so the same code runs in tests and in Node.
3
+ // The Android and iOS SDKs follow the same rules; see integrations/analytics-mobile.
4
+
5
+ import {
6
+ INSTALL_PATH,
7
+ OPEN_PATH,
8
+ deepLinkFrom,
9
+ deviceKey,
10
+ httpsLink,
11
+ installBody,
12
+ openBody,
13
+ parseAnswer,
14
+ within,
15
+ } from './attribution'
16
+ import type { AttributionInfo, AttributionRequest, DeepLink } from './attribution'
17
+
18
+ export const SDK_VERSION = '1.1.0'
19
+ export const DEFAULT_ENDPOINT = 'https://events.kissmyapps.dev'
20
+
21
+ export type Properties = Record<string, unknown>
22
+
23
+ /** AsyncStorage, MMKV or anything with the same two methods. */
24
+ export interface Storage {
25
+ getItem(key: string): Promise<string | null> | string | null
26
+ setItem(key: string, value: string): Promise<void> | void
27
+ }
28
+
29
+ export interface DeviceInfo {
30
+ platform: 'ios' | 'android'
31
+ os_name: string
32
+ os_version: string
33
+ device_type: 'mobile' | 'tablet'
34
+ device_model?: string
35
+ screen_width: number
36
+ screen_height: number
37
+ timezone: string
38
+ language: string
39
+ }
40
+
41
+ export interface ClientOptions {
42
+ /** The project's client key, kma_pk_live_… or kma_pk_test_…. */
43
+ key: string
44
+ endpoint?: string
45
+ /** The app's version, such as 2.4.0, and build number, such as 120. */
46
+ appVersion?: string
47
+ build?: string
48
+ /** A session ends after this long in the background or without events. Default 30. */
49
+ sessionTimeoutMinutes?: number
50
+ /** How often queued events are sent while the app is open. Default 10. */
51
+ flushIntervalSeconds?: number
52
+ /** The most events kept while offline; the oldest go first. Default 1000. */
53
+ maxQueue?: number
54
+ /** Record installs, updates, opens and backgrounding. Default true. */
55
+ trackLifecycle?: boolean
56
+ /**
57
+ * Match the install to the link that brought it on the first launch, and report links that
58
+ * open the app. Default true. Nothing is matched until attribution is on for the project.
59
+ */
60
+ attribution?: boolean
61
+ /**
62
+ * iPhone only: on the first launch, read a `kma:` click ID that the smart link's page put on
63
+ * the clipboard. Turn it on only with "Clipboard handoff for iPhone" on in the console:
64
+ * iOS asks the person before an app reads what another app copied. Default false.
65
+ */
66
+ clipboardHandoff?: boolean
67
+ debug?: boolean
68
+ }
69
+
70
+ export interface RevenueOptions {
71
+ /** Your product or plan, such as annual_plan. */
72
+ productId?: string
73
+ /**
74
+ * The payment's ID at the store, such as StoreKit's transaction ID or Google Play's order
75
+ * ID. The same payment reported by the app and by a RevenueCat or Adapty webhook with the
76
+ * same ID counts once.
77
+ */
78
+ transactionId?: string
79
+ /** The event's name. Default purchase, or refund for a negative amount. */
80
+ event?: string
81
+ /** More properties for the event. The kma_ revenue properties always win. */
82
+ properties?: Properties
83
+ }
84
+
85
+ export interface Environment {
86
+ storage: Storage | null
87
+ device(): DeviceInfo
88
+ fetch: (url: string, init: RequestInit) => Promise<Pick<Response, 'ok' | 'status' | 'text'>>
89
+ sdk: string
90
+ now?: () => number
91
+ log?: (message: string) => void
92
+ /** The link that opened the app, such as Linking.getInitialURL(). */
93
+ initialLink?: () => Promise<string | null>
94
+ /** What the optional native module reads: device key, install referrer, Apple Ads token, if any. */
95
+ attributionInfo?: (request: AttributionRequest) => Promise<AttributionInfo | null>
96
+ }
97
+
98
+ /** The first launch's install call, kept until it gets an answer and resent as it was. */
99
+ interface PendingInstall {
100
+ /** When app_installed was queued. */
101
+ at: number
102
+ anonymousId: string
103
+ sessionId: string
104
+ /** The first link that opened the app on the first launch, before the call went out. */
105
+ link?: string
106
+ /** Calls made so far, one per launch. */
107
+ tries: number
108
+ /** What the device gave on the first try, without the Apple Ads token, which expires. */
109
+ info?: AttributionInfo
110
+ /** False when reading the install referrer timed out: the next try reads it again. */
111
+ infoComplete?: boolean
112
+ }
113
+
114
+ /** This launch's install call: links wait for its answer before they go to the open call. */
115
+ type InstallPhase = 'none' | 'waiting' | 'answered' | 'failed'
116
+
117
+ interface Session {
118
+ id: string
119
+ started: number
120
+ last: number
121
+ firstScreen?: string
122
+ }
123
+
124
+ interface State {
125
+ anonymousId: string
126
+ userId: string | null
127
+ traits: Properties | null
128
+ session: Session | null
129
+ optedOut: boolean
130
+ version?: string
131
+ build?: string
132
+ install?: PendingInstall | null
133
+ }
134
+
135
+ export interface QueuedEvent {
136
+ name: string
137
+ insert_id: string
138
+ time: string
139
+ screen?: string
140
+ properties: Properties
141
+ user_id: string | null
142
+ anonymous_id: string
143
+ session_id: string
144
+ session_started_at: string
145
+ }
146
+
147
+ export const EVENT_NAME = /^[A-Za-z][A-Za-z0-9_.:-]{0,79}$/
148
+ const KEY = /^kma_pk_(live|test)_[A-Za-z0-9]{20,64}$/
149
+ const BATCH_SIZE = 50
150
+ const FLUSH_AT = 30
151
+ const HEARTBEAT_MS = 60_000
152
+ const MAX_PROPERTIES_BYTES = 32_000
153
+ // The first launch's call, then at most three more launches.
154
+ const INSTALL_TRIES = 4
155
+ // A link handed over twice this close together, by Linking and by the app, counts once.
156
+ const SAME_LINK_MS = 3000
157
+ // As the iOS SDK: the opening link has 1.5 seconds to arrive before the install call goes.
158
+ const INITIAL_LINK_WAIT_MS = 1500
159
+ // The native module waits up to 10 seconds for Google Play's install referrer.
160
+ const NATIVE_WAIT_MS = 12_000
161
+ const FLUSH_WAIT_MS = 5000
162
+ // The properties a payment event carries; reports read revenue from them.
163
+ const REVENUE_KEYS = ['kma_revenue', 'kma_currency', 'kma_product_id', 'kma_transaction_id']
164
+ const MAX_REVENUE = 1e9
165
+ const CURRENCY = /^[A-Za-z]{3}$/
166
+
167
+ /** A product or transaction ID as reports keep it: text of 1 to 200 characters. */
168
+ function revenueId(value: unknown): string | undefined {
169
+ const id = typeof value === 'string' ? value.trim() : ''
170
+ return id && id.length <= 200 ? id : undefined
171
+ }
172
+
173
+ export function uuid(): string {
174
+ // Hermes has no crypto.randomUUID; a polyfill may add it.
175
+ const random = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto
176
+ if (random?.randomUUID) return random.randomUUID()
177
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
178
+ const r = (Math.random() * 16) | 0
179
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
180
+ })
181
+ }
182
+
183
+ export class KmaClient {
184
+ readonly options: ClientOptions & { endpoint: string }
185
+ private readonly env: Environment
186
+ private readonly storageKey: string
187
+ private state: State
188
+ private queue: QueuedEvent[] = []
189
+ private screenName: string | null = null
190
+ private foregroundAt = 0
191
+ private loaded = false
192
+ private readonly waiting: (() => void)[] = []
193
+ private flushTimer: ReturnType<typeof setTimeout> | null = null
194
+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null
195
+ private saveTimer: ReturnType<typeof setTimeout> | null = null
196
+ private inflight: Promise<void> | null = null
197
+ private failures = 0
198
+ private lastSent = 0
199
+ private identityPending = false
200
+ private inForeground = false
201
+ private firstLaunch = false
202
+ private stopped = false
203
+ private launched = false
204
+ // This launch is the first launch: its first link goes with the install call.
205
+ private firstLaunchNow = false
206
+ private installRunning = false
207
+ // This launch's try is on its way (one try per launch).
208
+ private installSent = false
209
+ private installPhase: InstallPhase = 'none'
210
+ private linksBeforeLaunch: { url: string; at: number }[] = []
211
+ private waitingLinks: { url: string; at: number }[] = []
212
+ private readonly recentLinks = new Map<string, number>()
213
+ private deviceKeyRead: string | null | undefined
214
+ private deepLinkHandler: ((link: DeepLink) => void) | null = null
215
+ private heldDeepLink: DeepLink | null = null
216
+ private readonly initialLink: Promise<string | null>
217
+ /** Settles once saved state is read and the launch is recorded. */
218
+ readonly ready: Promise<void>
219
+
220
+ constructor(options: ClientOptions, env: Environment) {
221
+ if (!KEY.test(options.key ?? '')) {
222
+ throw new Error('KissMyApps: init needs a client key that starts with kma_pk_')
223
+ }
224
+ this.options = {
225
+ ...options,
226
+ endpoint: (options.endpoint ?? DEFAULT_ENDPOINT).replace(/\/+$/, ''),
227
+ }
228
+ this.env = env
229
+ this.storageKey = `kma:${options.key.slice(-8)}`
230
+ this.state = {
231
+ anonymousId: uuid(),
232
+ userId: null,
233
+ traits: null,
234
+ session: null,
235
+ optedOut: false,
236
+ }
237
+ this.ready = this.load()
238
+ const opening =
239
+ env.initialLink && options.attribution !== false
240
+ ? within(
241
+ Promise.resolve().then(() => env.initialLink?.() ?? null),
242
+ INITIAL_LINK_WAIT_MS,
243
+ null,
244
+ )
245
+ : Promise.resolve(null)
246
+ // Routed before the install call reads it, so the opening link goes with the install.
247
+ this.initialLink = opening.then((url) => {
248
+ if (url) this.handleDeepLink(url)
249
+ return url
250
+ })
251
+ }
252
+
253
+ // Public API ---------------------------------------------------------------------------
254
+
255
+ /** Records something a person did. */
256
+ track(name: string, properties: Properties = {}): void {
257
+ this.whenLoaded(() => {
258
+ if (this.stopped || this.state.optedOut) return
259
+ if (!EVENT_NAME.test(name)) {
260
+ this.warn(
261
+ `"${name}" is not a valid event name: use letters, numbers and _ . : - (up to 80).`,
262
+ )
263
+ return
264
+ }
265
+ this.enqueue(name, properties, this.ensureSession())
266
+ })
267
+ }
268
+
269
+ /**
270
+ * Records a payment: the amount in major units (9.99, not 999), negative for a refund, and
271
+ * its ISO 4217 currency code. Sent as a purchase (or refund) event with kma_revenue and
272
+ * kma_currency. An amount or currency that is not valid sends nothing (a warning in debug).
273
+ */
274
+ revenue(amount: number, currency: string, options: RevenueOptions = {}): void {
275
+ if (
276
+ typeof amount !== 'number' ||
277
+ !Number.isFinite(amount) ||
278
+ amount === 0 ||
279
+ Math.abs(amount) > MAX_REVENUE
280
+ ) {
281
+ return this.warn(
282
+ 'revenue needs an amount that is not 0 and at most 1,000,000,000 either way (negative for a refund).',
283
+ )
284
+ }
285
+ const code = typeof currency === 'string' ? currency.trim() : ''
286
+ if (!CURRENCY.test(code)) {
287
+ return this.warn(
288
+ `revenue needs a three-letter currency code such as USD, not "${String(currency)}".`,
289
+ )
290
+ }
291
+ const { productId, transactionId, event, properties } = options ?? {}
292
+ const values: Properties =
293
+ properties && typeof properties === 'object' && !Array.isArray(properties)
294
+ ? { ...properties }
295
+ : {}
296
+ for (const field of REVENUE_KEYS) delete values[field]
297
+ values.kma_revenue = amount
298
+ values.kma_currency = code.toUpperCase()
299
+ const product = revenueId(productId)
300
+ const transaction = revenueId(transactionId)
301
+ if (product) values.kma_product_id = product
302
+ else if (productId != null) this.warn('productId must be 1 to 200 characters; it was left out.')
303
+ if (transaction) values.kma_transaction_id = transaction
304
+ else if (transactionId != null)
305
+ this.warn('transactionId must be 1 to 200 characters; it was left out.')
306
+ this.track(event || (amount > 0 ? 'purchase' : 'refund'), values)
307
+ }
308
+
309
+ /** Records a screen view; later events carry the screen's name. */
310
+ screen(name: string, properties: Properties = {}): void {
311
+ const screen = String(name ?? '')
312
+ .trim()
313
+ .slice(0, 300)
314
+ if (!screen) return this.warn('screen needs a name.')
315
+ this.whenLoaded(() => {
316
+ if (this.stopped || this.state.optedOut) return
317
+ const previous = this.screenName
318
+ this.screenName = screen
319
+ const session = this.ensureSession()
320
+ if (!session.firstScreen) {
321
+ session.firstScreen = screen
322
+ this.save()
323
+ }
324
+ this.enqueue(
325
+ 'screen_viewed',
326
+ { name: screen, ...(previous ? { previous } : {}), ...properties },
327
+ session,
328
+ )
329
+ })
330
+ }
331
+
332
+ /** Ties this install to your own user ID, with optional traits such as email, name or plan. */
333
+ identify(userId: string | number, traits?: Properties): void {
334
+ const id = String(userId ?? '').trim()
335
+ if (!id || id.length > 200) return this.warn('identify needs a user ID of 1 to 200 characters.')
336
+ this.whenLoaded(() => {
337
+ if (this.stopped || this.state.optedOut) return
338
+ this.state.userId = id
339
+ if (traits) this.state.traits = { ...(this.state.traits ?? {}), ...this.clean(traits) }
340
+ this.identityPending = true
341
+ this.save()
342
+ this.scheduleFlush(0)
343
+ })
344
+ }
345
+
346
+ /** Updates traits for the current person without changing who they are. */
347
+ setTraits(traits: Properties): void {
348
+ this.whenLoaded(() => {
349
+ if (this.stopped || this.state.optedOut) return
350
+ this.state.traits = { ...(this.state.traits ?? {}), ...this.clean(traits) }
351
+ this.identityPending = true
352
+ this.save()
353
+ this.scheduleFlush(0)
354
+ })
355
+ }
356
+
357
+ /** Forgets the user, for example on sign out: what follows is a new person and session. */
358
+ reset(): void {
359
+ this.whenLoaded(() => {
360
+ if (this.stopped || this.state.optedOut) return
361
+ void this.flush()
362
+ this.state.userId = null
363
+ this.state.traits = null
364
+ this.identityPending = false
365
+ this.state.anonymousId = uuid()
366
+ this.state.session = null
367
+ this.save()
368
+ if (this.inForeground) this.ensureSession()
369
+ })
370
+ }
371
+
372
+ /** Stops recording and drops anything not sent yet, until optIn. Remembered across launches. */
373
+ optOut(): void {
374
+ this.whenLoaded(() => {
375
+ this.state.optedOut = true
376
+ this.clearConsentData()
377
+ })
378
+ }
379
+
380
+ private clearConsentData(): void {
381
+ this.queue = []
382
+ this.state.userId = null
383
+ this.state.traits = null
384
+ this.identityPending = false
385
+ this.state.session = null
386
+ this.screenName = null
387
+ this.state.install = null
388
+ this.firstLaunch = false
389
+ this.linksBeforeLaunch = []
390
+ this.waitingLinks = []
391
+ this.recentLinks.clear()
392
+ this.heldDeepLink = null
393
+ this.installPhase = 'answered'
394
+ void this.writeNow()
395
+ }
396
+
397
+ optIn(): void {
398
+ this.whenLoaded(() => {
399
+ if (!this.state.optedOut) return
400
+ this.state.anonymousId = uuid()
401
+ this.state.optedOut = false
402
+ this.save()
403
+ })
404
+ }
405
+
406
+ /**
407
+ * Reports a link that opened the app, such as a Universal Link or App Link. Any https link
408
+ * is sent and KissMyApps decides whether it is one of the project's links; its deep link then
409
+ * goes to `onDeepLink`. Returns false when nothing is sent (not https, longer than 2,048
410
+ * characters, attribution off, opted out). The same link handed over twice within 3 seconds
411
+ * counts once, so Linking and the app may both report it.
412
+ */
413
+ handleDeepLink(url: string): boolean {
414
+ if (this.options.attribution === false || this.stopped) return false
415
+ const link = httpsLink(url)
416
+ if (!link) return false
417
+ if (this.loaded && this.state.optedOut) return false
418
+ const at = this.now()
419
+ this.whenLoaded(() => this.routeLink(link, at))
420
+ return true
421
+ }
422
+
423
+ /**
424
+ * Where deep links go: the deferred one after an install, and one each time a link opens the
425
+ * app. Each deep link is handed over once; one that arrives before a handler is set is held
426
+ * and handed to the next handler set. Pass null to stop.
427
+ */
428
+ onDeepLink(handler: ((link: DeepLink) => void) | null): void {
429
+ this.deepLinkHandler = handler
430
+ const held = this.heldDeepLink
431
+ if (handler && held) {
432
+ this.heldDeepLink = null
433
+ this.deliver(held)
434
+ }
435
+ }
436
+
437
+ getAnonymousId(): string {
438
+ return this.state.anonymousId
439
+ }
440
+
441
+ getUserId(): string | null {
442
+ return this.state.userId
443
+ }
444
+
445
+ getSessionId(): string | null {
446
+ return this.state.session?.id ?? null
447
+ }
448
+
449
+ /** Sends everything queued now. */
450
+ flush(): Promise<void> {
451
+ if (!this.loaded) return this.ready.then(() => this.flush())
452
+ if (this.inflight) return this.inflight
453
+ this.inflight = this.sendQueued().finally(() => {
454
+ this.inflight = null
455
+ })
456
+ return this.inflight
457
+ }
458
+
459
+ /** Stops timers; the client records nothing more. */
460
+ shutdown(): void {
461
+ this.stopped = true
462
+ this.inForeground = false
463
+ if (this.flushTimer) clearTimeout(this.flushTimer)
464
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer)
465
+ if (this.saveTimer) {
466
+ clearTimeout(this.saveTimer)
467
+ void this.writeNow()
468
+ }
469
+ }
470
+
471
+ // App lifecycle, called by the platform layer ------------------------------------------
472
+
473
+ /** The app came to the front. The first call is the launch. */
474
+ foreground(): void {
475
+ this.whenLoaded(() => {
476
+ if (this.stopped || this.inForeground) return
477
+ const launch = this.foregroundAt === 0
478
+ this.launched = true
479
+ this.inForeground = true
480
+ this.foregroundAt = this.now()
481
+ if (this.state.optedOut) return
482
+ const session = this.ensureSession()
483
+ const firstLaunch = launch && this.firstLaunch
484
+ if (this.options.trackLifecycle !== false) {
485
+ if (launch) this.recordInstallOrUpdate(session)
486
+ this.enqueue('app_opened', { from_background: !launch }, session)
487
+ }
488
+ if (launch) this.attributeLaunch(session, firstLaunch)
489
+ this.heartbeatTimer ??= setInterval(() => this.heartbeat(), HEARTBEAT_MS)
490
+ })
491
+ }
492
+
493
+ /** The app went to the background: record it and send what is queued while it can. */
494
+ background(): void {
495
+ this.whenLoaded(() => {
496
+ if (this.stopped || !this.inForeground) return
497
+ this.inForeground = false
498
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer)
499
+ this.heartbeatTimer = null
500
+ if (this.state.optedOut) return
501
+ const session = this.state.session
502
+ if (session && this.options.trackLifecycle !== false) {
503
+ const seconds = Math.round((this.now() - this.foregroundAt) / 1000)
504
+ this.enqueue('app_backgrounded', { seconds_in_foreground: Math.max(0, seconds) }, session)
505
+ }
506
+ if (session) session.last = this.now()
507
+ void this.writeNow()
508
+ void this.flush()
509
+ })
510
+ }
511
+
512
+ // State --------------------------------------------------------------------------------
513
+
514
+ private async load(): Promise<void> {
515
+ const storage = this.env.storage
516
+ if (!storage) this.warn('No storage was given, so each launch counts as a new install.')
517
+ let saved: Partial<State> | null = null
518
+ let queue: QueuedEvent[] = []
519
+ try {
520
+ const raw = await storage?.getItem(this.storageKey)
521
+ saved = raw ? (JSON.parse(raw) as Partial<State>) : null
522
+ const rawQueue = await storage?.getItem(`${this.storageKey}:queue`)
523
+ queue = rawQueue ? (JSON.parse(rawQueue) as QueuedEvent[]) : []
524
+ } catch {
525
+ saved = null
526
+ }
527
+ if (saved?.anonymousId) {
528
+ this.state = {
529
+ anonymousId: saved.anonymousId,
530
+ userId: saved.userId ?? null,
531
+ traits: saved.traits ?? null,
532
+ session: saved.session ?? null,
533
+ optedOut: saved.optedOut === true,
534
+ version: saved.version,
535
+ build: saved.build,
536
+ install: pendingInstall(saved.install),
537
+ }
538
+ }
539
+ // Nothing saved means a first launch, or the app's data was cleared.
540
+ this.firstLaunch = !saved?.anonymousId
541
+ this.queue = Array.isArray(queue) ? queue : []
542
+ this.identityPending = Boolean(this.state.traits)
543
+ if (this.state.optedOut) this.clearConsentData()
544
+ this.loaded = true
545
+ // What an earlier launch could not send goes now.
546
+ if (this.queue.length) this.scheduleFlush(0)
547
+ for (const run of this.waiting.splice(0)) run()
548
+ }
549
+
550
+ private whenLoaded(run: () => void): void {
551
+ if (this.loaded) run()
552
+ else this.waiting.push(run)
553
+ }
554
+
555
+ private recordInstallOrUpdate(session: Session): void {
556
+ const version = this.options.appVersion
557
+ const build = this.options.build
558
+ if (this.firstLaunch) {
559
+ this.enqueue('app_installed', this.clean({ version, build }), session)
560
+ } else if (
561
+ (version && this.state.version && version !== this.state.version) ||
562
+ (build && this.state.build && build !== this.state.build)
563
+ ) {
564
+ this.enqueue(
565
+ 'app_updated',
566
+ this.clean({
567
+ version,
568
+ build,
569
+ previous_version: this.state.version,
570
+ previous_build: this.state.build,
571
+ }),
572
+ session,
573
+ )
574
+ }
575
+ this.firstLaunch = false
576
+ this.state.version = version ?? this.state.version
577
+ this.state.build = build ?? this.state.build
578
+ this.save()
579
+ }
580
+
581
+ private save(): void {
582
+ if (this.saveTimer) return
583
+ this.saveTimer = setTimeout(() => {
584
+ this.saveTimer = null
585
+ void this.writeNow()
586
+ }, 250)
587
+ }
588
+
589
+ private async writeNow(): Promise<void> {
590
+ if (this.saveTimer) {
591
+ clearTimeout(this.saveTimer)
592
+ this.saveTimer = null
593
+ }
594
+ try {
595
+ await this.env.storage?.setItem(this.storageKey, JSON.stringify(this.state))
596
+ await this.env.storage?.setItem(`${this.storageKey}:queue`, JSON.stringify(this.queue))
597
+ } catch {
598
+ // Storage full or failing: the client keeps working in memory.
599
+ }
600
+ }
601
+
602
+ // Sessions and events -------------------------------------------------------------------
603
+
604
+ private now(): number {
605
+ return this.env.now?.() ?? Date.now()
606
+ }
607
+
608
+ private ensureSession(): Session {
609
+ const now = this.now()
610
+ const timeout = (this.options.sessionTimeoutMinutes ?? 30) * 60_000
611
+ let session = this.state.session
612
+ if (!session || now - session.last > timeout) {
613
+ session = { id: uuid(), started: now, last: now, firstScreen: this.screenName ?? undefined }
614
+ this.state.session = session
615
+ this.enqueue('session_started', {}, session)
616
+ } else {
617
+ session.last = now
618
+ }
619
+ return session
620
+ }
621
+
622
+ private enqueue(name: string, properties: Properties, session: Session): void {
623
+ this.queue.push({
624
+ name,
625
+ insert_id: uuid(),
626
+ time: new Date(this.now()).toISOString(),
627
+ screen: this.screenName ?? undefined,
628
+ properties: this.clean(properties),
629
+ user_id: this.state.userId,
630
+ anonymous_id: this.state.anonymousId,
631
+ session_id: session.id,
632
+ session_started_at: new Date(session.started).toISOString(),
633
+ })
634
+ const max = this.options.maxQueue ?? 1000
635
+ if (this.queue.length > max) this.queue.splice(0, this.queue.length - max)
636
+ this.save()
637
+ this.scheduleFlush(
638
+ this.queue.length >= FLUSH_AT ? 0 : (this.options.flushIntervalSeconds ?? 10) * 1000,
639
+ )
640
+ }
641
+
642
+ private clean(properties: Properties): Properties {
643
+ try {
644
+ const json = JSON.stringify(properties ?? {})
645
+ if (json.length > MAX_PROPERTIES_BYTES) {
646
+ this.warn('Event properties are over 32 KB and were dropped.')
647
+ return {}
648
+ }
649
+ const parsed = JSON.parse(json)
650
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
651
+ } catch {
652
+ return {}
653
+ }
654
+ }
655
+
656
+ // Sending ------------------------------------------------------------------------------
657
+
658
+ private context(session: Session | null): Properties {
659
+ const device = this.env.device()
660
+ return {
661
+ platform: device.platform,
662
+ sdk: this.env.sdk,
663
+ timezone: device.timezone,
664
+ language: device.language,
665
+ device_type: device.device_type,
666
+ device_model: device.device_model,
667
+ os_name: device.os_name,
668
+ os_version: device.os_version,
669
+ app_version: this.options.appVersion,
670
+ screen_width: Math.round(device.screen_width),
671
+ screen_height: Math.round(device.screen_height),
672
+ page_path: session?.firstScreen,
673
+ }
674
+ }
675
+
676
+ /** One request's body: queued events share a person and session; with none, a heartbeat. */
677
+ body(events: QueuedEvent[]): Properties {
678
+ const head = events[0]
679
+ const session = this.state.session
680
+ const sessionId = head?.session_id ?? session?.id
681
+ const startedAt =
682
+ head?.session_started_at ?? (session ? new Date(session.started).toISOString() : undefined)
683
+ const live = session?.id === sessionId ? session : null
684
+ const current = !head || head.anonymous_id === this.state.anonymousId
685
+ const userId = current ? this.state.userId : events[events.length - 1].user_id
686
+ const body: Properties = {
687
+ anonymous_id: head?.anonymous_id ?? this.state.anonymousId,
688
+ session: sessionId ? { id: sessionId, started_at: startedAt } : undefined,
689
+ sent_at: new Date(this.now()).toISOString(),
690
+ context: this.context(live),
691
+ events: events.map(({ name, insert_id, time, screen, properties, user_id }) => ({
692
+ name,
693
+ insert_id,
694
+ time,
695
+ ...(screen ? { screen } : {}),
696
+ properties,
697
+ user_id,
698
+ })),
699
+ }
700
+ if (userId) body.user_id = userId
701
+ if (current && this.state.traits) body.traits = this.state.traits
702
+ return JSON.parse(JSON.stringify(body))
703
+ }
704
+
705
+ private nextBatch(): QueuedEvent[] {
706
+ const head = this.queue[0]
707
+ if (!head) return []
708
+ const batch: QueuedEvent[] = []
709
+ for (const event of this.queue) {
710
+ if (
711
+ event.session_id !== head.session_id ||
712
+ event.anonymous_id !== head.anonymous_id ||
713
+ batch.length >= BATCH_SIZE
714
+ )
715
+ break
716
+ batch.push(event)
717
+ }
718
+ return batch
719
+ }
720
+
721
+ private async post(body: Properties, path = '/v1/events') {
722
+ return this.env.fetch(`${this.options.endpoint}${path}`, {
723
+ method: 'POST',
724
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${this.options.key}` },
725
+ body: JSON.stringify(body),
726
+ })
727
+ }
728
+
729
+ private async sendQueued(): Promise<void> {
730
+ while (!this.stopped && !this.state.optedOut) {
731
+ const batch = this.nextBatch()
732
+ if (!batch.length && !(this.identityPending && this.state.session)) return
733
+ const traitsSent = this.state.traits
734
+ const carriesIdentity = !batch.length || batch[0].anonymous_id === this.state.anonymousId
735
+ let response: Awaited<ReturnType<Environment['fetch']>>
736
+ try {
737
+ response = await this.post(this.body(batch))
738
+ } catch {
739
+ this.retryLater()
740
+ return
741
+ }
742
+ const refused =
743
+ response.status >= 400 &&
744
+ response.status < 500 &&
745
+ response.status !== 408 &&
746
+ response.status !== 429
747
+ if (!response.ok && !refused) {
748
+ this.retryLater()
749
+ return
750
+ }
751
+ if (refused)
752
+ this.warn(
753
+ `Events were refused (${response.status}): ${await response.text().catch(() => '')}`,
754
+ )
755
+ const sent = new Set(batch.map((event) => event.insert_id))
756
+ this.queue = this.queue.filter((event) => !sent.has(event.insert_id))
757
+ if (response.ok && carriesIdentity && this.state.traits === traitsSent) {
758
+ this.state.traits = null
759
+ this.identityPending = false
760
+ }
761
+ this.failures = 0
762
+ this.lastSent = this.now()
763
+ this.save()
764
+ }
765
+ }
766
+
767
+ private retryLater(): void {
768
+ this.failures += 1
769
+ this.scheduleFlush(Math.min(60_000, 1000 * 2 ** Math.min(this.failures, 6)), true)
770
+ }
771
+
772
+ private scheduleFlush(delay: number, replace = false): void {
773
+ if (this.stopped) return
774
+ if (this.flushTimer) {
775
+ if (delay > 0 && !replace) return
776
+ clearTimeout(this.flushTimer)
777
+ }
778
+ this.flushTimer = setTimeout(() => {
779
+ this.flushTimer = null
780
+ void this.flush()
781
+ }, delay)
782
+ }
783
+
784
+ /** Keeps an open app counted as online. */
785
+ private heartbeat(): void {
786
+ const session = this.state.session
787
+ if (this.stopped || this.state.optedOut || !this.inForeground || !session) return
788
+ session.last = this.now()
789
+ if (this.queue.length || this.identityPending) {
790
+ void this.flush()
791
+ return
792
+ }
793
+ if (this.now() - this.lastSent < HEARTBEAT_MS - 1000) return
794
+ this.post(this.body([]))
795
+ .then(() => {
796
+ this.lastSent = this.now()
797
+ })
798
+ .catch(() => undefined)
799
+ }
800
+
801
+ // Attribution ---------------------------------------------------------------------------
802
+
803
+ /** The launch: the first one queues the install call; links that came before it are routed. */
804
+ private attributeLaunch(session: Session, firstLaunch: boolean): void {
805
+ this.firstLaunch = false
806
+ const early = this.linksBeforeLaunch.splice(0)
807
+ if (this.options.attribution === false) return
808
+ // Without storage every launch looks like the first, so there is no install to match.
809
+ if (firstLaunch && this.env.storage) {
810
+ this.state.install = {
811
+ at: this.now(),
812
+ anonymousId: this.state.anonymousId,
813
+ sessionId: session.id,
814
+ tries: 0,
815
+ }
816
+ this.firstLaunchNow = true
817
+ this.save()
818
+ }
819
+ if (this.state.install) {
820
+ this.installPhase = 'waiting'
821
+ for (const link of early) this.routeLaunched(link.url, link.at)
822
+ void this.sendInstall()
823
+ } else {
824
+ for (const link of early) void this.sendOpen(link.url, link.at)
825
+ }
826
+ }
827
+
828
+ private routeLink(url: string, at: number): void {
829
+ if (this.stopped || this.state.optedOut) return
830
+ for (const [seen, when] of this.recentLinks) {
831
+ if (at - when >= SAME_LINK_MS) this.recentLinks.delete(seen)
832
+ }
833
+ if (this.recentLinks.has(url)) return
834
+ this.recentLinks.set(url, at)
835
+ if (!this.launched) {
836
+ if (this.linksBeforeLaunch.length < 10) this.linksBeforeLaunch.push({ url, at })
837
+ return
838
+ }
839
+ this.routeLaunched(url, at)
840
+ }
841
+
842
+ private routeLaunched(url: string, at: number): void {
843
+ const pending = this.state.install
844
+ if (pending && this.installPhase === 'waiting') {
845
+ // Only the first link of the first launch goes with the install call.
846
+ if (this.firstLaunchNow && !this.installSent && !pending.tries && !pending.link) {
847
+ pending.link = url
848
+ this.save()
849
+ } else if (this.waitingLinks.length < 10) {
850
+ // Sent once the install is matched; an open first would record an install of its own.
851
+ this.waitingLinks.push({ url, at })
852
+ }
853
+ return
854
+ }
855
+ if (pending && this.installPhase === 'failed') {
856
+ this.warn('The link was not sent: the install is matched first, on the next launch.')
857
+ return
858
+ }
859
+ void this.sendOpen(url, at)
860
+ }
861
+
862
+ /** The device's details; `complete` is false when the install referrer could not be read in time. */
863
+ private async readNative(
864
+ install: boolean,
865
+ clipboard: boolean,
866
+ ): Promise<{ info: AttributionInfo; complete: boolean }> {
867
+ const read = this.env.attributionInfo
868
+ if (!read) return { info: {}, complete: true }
869
+ const request = {
870
+ install,
871
+ clipboard: install && clipboard && this.options.clipboardHandoff === true,
872
+ }
873
+ const info = await within<AttributionInfo | null>(
874
+ Promise.resolve()
875
+ .then(() => read(request))
876
+ .then(
877
+ (answer) => (answer && typeof answer === 'object' ? answer : {}),
878
+ () => ({}),
879
+ ),
880
+ NATIVE_WAIT_MS,
881
+ null,
882
+ )
883
+ if (!info) return { info: {}, complete: false }
884
+ const key = deviceKey(info.deviceKey)
885
+ if (key) this.deviceKeyRead = key
886
+ return { info, complete: info.retryReferrer !== true }
887
+ }
888
+
889
+ /** The first try's details again; the Apple Ads token, and a referrer that timed out, are read anew. */
890
+ private async installInfo(
891
+ pending: PendingInstall,
892
+ ): Promise<{ info: AttributionInfo; complete: boolean }> {
893
+ const saved = pending.info
894
+ if (saved && pending.infoComplete && this.env.device().platform === 'android') {
895
+ return { info: saved, complete: true }
896
+ }
897
+ // The clipboard is read on the first try only.
898
+ const read = await this.readNative(true, !saved)
899
+ if (!saved) return read
900
+ return {
901
+ info: { ...read.info, ...definedOnly(saved), appleAdsToken: read.info.appleAdsToken },
902
+ complete: pending.infoComplete === true || read.complete,
903
+ }
904
+ }
905
+
906
+ /** The install call: once, on the first launch; again on the next launches if it failed. */
907
+ private async sendInstall(): Promise<void> {
908
+ if (this.installRunning) return
909
+ this.installRunning = true
910
+ try {
911
+ await this.initialLink
912
+ const first = this.state.install
913
+ if (!first) return this.installAnswered()
914
+ const { info, complete } = await this.installInfo(first)
915
+ // app_installed and its session reach the server first.
916
+ await within(this.flush(), FLUSH_WAIT_MS, undefined)
917
+ const pending = this.state.install
918
+ if (!pending) return this.installAnswered()
919
+ if (this.stopped || this.state.optedOut || this.installSent) return
920
+ this.installSent = true
921
+ pending.tries += 1
922
+ if (!pending.info || !pending.infoComplete) {
923
+ pending.info = savedInfo(info)
924
+ pending.infoComplete = complete
925
+ }
926
+ const device = this.env.device()
927
+ const body = installBody({
928
+ anonymousId: pending.anonymousId,
929
+ sessionId: pending.sessionId,
930
+ platform: device.platform,
931
+ installedAt: pending.at,
932
+ sdk: this.env.sdk,
933
+ // Not after a reset: the install belongs to the person who installed.
934
+ userId: pending.anonymousId === this.state.anonymousId ? this.state.userId : null,
935
+ appVersion: this.options.appVersion,
936
+ link: pending.link,
937
+ info,
938
+ clipboard: this.options.clipboardHandoff === true,
939
+ })
940
+ await this.writeNow()
941
+ let response: Awaited<ReturnType<Environment['fetch']>>
942
+ try {
943
+ if (this.state.install !== pending || this.state.optedOut) return
944
+ response = await this.post(body, INSTALL_PATH)
945
+ } catch {
946
+ if (this.state.install === pending) this.installFailed(pending, 'no connection')
947
+ return
948
+ }
949
+ if (this.state.install !== pending || this.state.optedOut) return
950
+ if (!response.ok && retryable(response.status)) {
951
+ return this.installFailed(pending, `status ${response.status}`)
952
+ }
953
+ // Answered: a refused body would be refused again, and an unreadable answer is still one.
954
+ this.state.install = null
955
+ void this.writeNow()
956
+ const answer = await response.text().catch(() => '')
957
+ if (response.ok) {
958
+ this.deliver(deepLinkFrom(parseAnswer(answer), httpsLink(pending.link)))
959
+ } else {
960
+ this.warn(`The install was refused (${response.status}): ${answer}`)
961
+ }
962
+ this.installAnswered()
963
+ } finally {
964
+ this.installRunning = false
965
+ }
966
+ }
967
+
968
+ /** Links that waited for the install's answer go to the open call now. */
969
+ private installAnswered(): void {
970
+ this.installPhase = 'answered'
971
+ for (const link of this.waitingLinks.splice(0)) void this.sendOpen(link.url, link.at)
972
+ }
973
+
974
+ private installFailed(pending: PendingInstall, reason: string): void {
975
+ if (pending.tries >= INSTALL_TRIES) {
976
+ this.state.install = null
977
+ this.warn(`The install could not be matched (${reason}); giving up.`)
978
+ this.installAnswered()
979
+ } else {
980
+ this.warn(`The install could not be matched yet (${reason}); trying again next launch.`)
981
+ this.installPhase = 'failed'
982
+ if (this.waitingLinks.splice(0).length) {
983
+ this.warn('Links that opened the app were not sent: the install is matched first.')
984
+ }
985
+ }
986
+ void this.writeNow()
987
+ }
988
+
989
+ /** The open call, for a link that opened the app after the install was matched. Not retried. */
990
+ private async sendOpen(url: string, at: number): Promise<void> {
991
+ if (this.stopped || this.state.optedOut) return
992
+ const session = this.ensureSession()
993
+ const anonymousId = this.state.anonymousId
994
+ const userId = this.state.userId
995
+ const key =
996
+ this.deviceKeyRead ?? deviceKey((await this.readNative(false, false)).info.deviceKey)
997
+ if (this.stopped || this.state.optedOut || anonymousId !== this.state.anonymousId) return
998
+ const body = openBody({
999
+ anonymousId,
1000
+ sessionId: session.id,
1001
+ platform: this.env.device().platform,
1002
+ url,
1003
+ openedAt: at,
1004
+ sdk: this.env.sdk,
1005
+ userId,
1006
+ appVersion: this.options.appVersion,
1007
+ deviceKey: key,
1008
+ })
1009
+ try {
1010
+ const response = await this.post(body, OPEN_PATH)
1011
+ const answer = await response.text().catch(() => '')
1012
+ if (this.state.optedOut || anonymousId !== this.state.anonymousId) return
1013
+ if (!response.ok) {
1014
+ this.warn(`The link was refused (${response.status}): ${answer}`)
1015
+ return
1016
+ }
1017
+ this.deliver(deepLinkFrom(parseAnswer(answer), url))
1018
+ } catch {
1019
+ this.warn('The link could not be sent: no connection.')
1020
+ }
1021
+ }
1022
+
1023
+ /** Hands a deep link to the handler; without one, the newest is held for the next handler. */
1024
+ private deliver(link: DeepLink | null): void {
1025
+ if (!link || this.stopped || this.state.optedOut) return
1026
+ const anonymousId = this.state.anonymousId
1027
+ const handler = this.deepLinkHandler
1028
+ if (!handler) {
1029
+ this.heldDeepLink = link
1030
+ return
1031
+ }
1032
+ // Later, so a handler set during a render or an effect runs after it.
1033
+ setTimeout(() => {
1034
+ try {
1035
+ if (!this.state.optedOut && anonymousId === this.state.anonymousId) handler(link)
1036
+ } catch (error) {
1037
+ this.warn(`onDeepLink threw: ${String(error)}`)
1038
+ }
1039
+ }, 0)
1040
+ }
1041
+
1042
+ private warn(message: string): void {
1043
+ if (this.options.debug) (this.env.log ?? console.warn)(`KissMyApps: ${message}`)
1044
+ }
1045
+ }
1046
+
1047
+ function retryable(status: number): boolean {
1048
+ return status >= 500 || status === 408 || status === 429 || status < 400
1049
+ }
1050
+
1051
+ function pendingInstall(value: unknown): PendingInstall | null {
1052
+ if (!value || typeof value !== 'object') return null
1053
+ const saved = value as Partial<PendingInstall>
1054
+ if (
1055
+ typeof saved.at !== 'number' ||
1056
+ typeof saved.anonymousId !== 'string' ||
1057
+ typeof saved.sessionId !== 'string'
1058
+ )
1059
+ return null
1060
+ const info = saved.info && typeof saved.info === 'object' ? savedInfo(saved.info) : undefined
1061
+ return {
1062
+ at: saved.at,
1063
+ anonymousId: saved.anonymousId,
1064
+ sessionId: saved.sessionId,
1065
+ link: typeof saved.link === 'string' ? saved.link : undefined,
1066
+ tries: typeof saved.tries === 'number' ? saved.tries : 0,
1067
+ info,
1068
+ infoComplete: info ? saved.infoComplete === true : undefined,
1069
+ }
1070
+ }
1071
+
1072
+ /** What is kept for the next tries: everything but the Apple Ads token, which expires. */
1073
+ function savedInfo(info: AttributionInfo): AttributionInfo {
1074
+ const kept: AttributionInfo = {}
1075
+ if (typeof info.deviceKey === 'string') kept.deviceKey = info.deviceKey
1076
+ if (typeof info.referrer === 'string') kept.referrer = info.referrer
1077
+ if (typeof info.referrerClickTs === 'number') kept.referrerClickTs = info.referrerClickTs
1078
+ if (typeof info.installBeginTs === 'number') kept.installBeginTs = info.installBeginTs
1079
+ if (typeof info.clipboardClick === 'string') kept.clipboardClick = info.clipboardClick
1080
+ return kept
1081
+ }
1082
+
1083
+ function definedOnly(info: AttributionInfo): AttributionInfo {
1084
+ return Object.fromEntries(
1085
+ Object.entries(info).filter(([, value]) => value !== undefined && value !== null),
1086
+ ) as AttributionInfo
1087
+ }