kv-test-ang 1.0.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.
@@ -0,0 +1,1649 @@
1
+ import * as i0 from '@angular/core';
2
+ import { Injectable, NgModule } from '@angular/core';
3
+ import { __awaiter } from 'tslib';
4
+
5
+ /*
6
+ Authored by Brett Barinaga on 11/17/21.
7
+ Copyright (c) Kochava, Inc. All rights reserved.
8
+ */
9
+ const uuidv4 = () => {
10
+ return (`${1e7}-${1e3}-${4e3}-${8e3}-${1e11}`).replace(/[018]/g, (c) => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
11
+ };
12
+ // returns the number of milliseconds elapsed since January 1, 1970
13
+ const getCurrTimeMS = () => Math.floor(Date.now());
14
+ // returns the number of seconds elapsed since January 1, 1970
15
+ const getCurrTimeSec = () => Math.floor(Date.now() / 1000);
16
+ const formatTime = (num) => {
17
+ if (num < 10 && num % 10 <= 9)
18
+ return "0" + num.toFixed(1).toString();
19
+ else
20
+ return num.toFixed(1).toString();
21
+ };
22
+ const getMsTime = () => {
23
+ const date = new Date();
24
+ return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}:${date.getMilliseconds()}`;
25
+ };
26
+
27
+ /*
28
+ Authored by Brett Barinaga on 11/17/21.
29
+ Copyright (c) Kochava, Inc. All rights reserved.
30
+ */
31
+ var Level;
32
+ (function (Level) {
33
+ Level["Off"] = "Off";
34
+ Level["Error"] = "Error";
35
+ Level["Warn"] = "Warn";
36
+ Level["Info"] = "Info";
37
+ Level["Debug"] = "Debug";
38
+ Level["Trace"] = "Trace";
39
+ })(Level || (Level = {}));
40
+ class Logger {
41
+ constructor() {
42
+ if (Logger.instance)
43
+ return;
44
+ this.levelPrio = {
45
+ Off: 0,
46
+ Error: 1,
47
+ Warn: 2,
48
+ Info: 3,
49
+ Debug: 4,
50
+ Trace: 5,
51
+ };
52
+ this.currLevel = Level.Info;
53
+ this.logObjects = false;
54
+ this.logsFilteredOut = {
55
+ Off: false,
56
+ Error: false,
57
+ Warn: false,
58
+ Info: false,
59
+ Debug: false,
60
+ Trace: false,
61
+ Diag: false,
62
+ };
63
+ Logger.instance = this;
64
+ }
65
+ setLogLevel(input) {
66
+ const levelStr = input[0].toUpperCase() + input.substring(1).toLowerCase();
67
+ const key = levelStr;
68
+ const level = Level[key];
69
+ if (level !== undefined && level !== null) {
70
+ this.currLevel = level;
71
+ }
72
+ else {
73
+ console.log(`Invalid logLevel ${level} passed in, defaulting to info.`);
74
+ this.currLevel = Level.Info;
75
+ }
76
+ }
77
+ getLogLevel() {
78
+ return this.currLevel.toString();
79
+ }
80
+ setLogObjects(enable) {
81
+ this.logObjects = enable;
82
+ }
83
+ disableLogType(input) {
84
+ const levelStr = input[0].toUpperCase() + input.substring(1).toLowerCase();
85
+ const key = levelStr;
86
+ this.logsFilteredOut[key] = true;
87
+ }
88
+ error(msg, ...args) {
89
+ this.print(Level.Error, msg, ...args);
90
+ }
91
+ warn(msg, ...args) {
92
+ this.print(Level.Warn, msg, ...args);
93
+ }
94
+ info(msg, ...args) {
95
+ this.print(Level.Info, msg, ...args);
96
+ }
97
+ debug(msg, ...args) {
98
+ this.print(Level.Debug, msg, ...args);
99
+ }
100
+ trace(msg, ...args) {
101
+ this.print(Level.Trace, msg, ...args);
102
+ }
103
+ diagInfo(msg, ...args) {
104
+ if (!this.logsFilteredOut.Diag)
105
+ this.print(Level.Info, "Kochava Diagnostic - " + msg, ...args);
106
+ }
107
+ diagDebug(msg, ...args) {
108
+ if (!this.logsFilteredOut.Diag)
109
+ this.print(Level.Debug, "Kochava Diagnostic - " + msg, ...args);
110
+ }
111
+ print(lvl, msg, ...args) {
112
+ if (this.levelPrio[this.currLevel.toString()] >= this.levelPrio[lvl.toString()] &&
113
+ !this.logsFilteredOut[lvl.toString()]) {
114
+ try {
115
+ const obj = JSON.parse(args[0]);
116
+ if (this.logObjects && obj) {
117
+ console.log(`KVA :: ${getMsTime()} ${lvl.toString()}:`, msg, obj);
118
+ }
119
+ else {
120
+ console.log(`KVA :: ${getMsTime()} ${lvl.toString()}:`, msg, ...args);
121
+ }
122
+ }
123
+ catch (_a) {
124
+ console.log(`KVA :: ${getMsTime()} ${lvl.toString()}:`, msg, ...args);
125
+ }
126
+ }
127
+ }
128
+ }
129
+ const Log = new Logger();
130
+
131
+ const sendRequest = (payload, endpoint) => __awaiter(void 0, void 0, void 0, function* () {
132
+ try {
133
+ const headers = new Headers();
134
+ headers.append("Content-Type", "application/json");
135
+ Log.trace(`Request ${payload.nt_id} being sent to: `, endpoint);
136
+ const resp = yield fetch(endpoint, {
137
+ method: "POST",
138
+ headers: headers,
139
+ body: JSON.stringify(payload),
140
+ });
141
+ return yield resp.text();
142
+ }
143
+ catch (e) {
144
+ Log.error("Error in post request", e);
145
+ return "";
146
+ }
147
+ });
148
+ const wasRespSuccess = (success) => success === "1" || success === 1 || success === true;
149
+
150
+ /*
151
+ Authored by Brett Barinaga on 11/17/21.
152
+ Copyright (c) Kochava, Inc. All rights reserved.
153
+ */
154
+ const getPackageName = () => `com.${window.location.hostname}.web`;
155
+ const getLanguage = () => (navigator) ? navigator.language : "";
156
+ const getDeviceWidth = () => (window) ? window.screen.availWidth : 0;
157
+ const getDeviceHeight = () => (window) ? window.screen.availHeight : 0;
158
+ const getDeviceOrientation = () => (window) ? window.innerWidth < window.innerHeight
159
+ ? "portrait" : "landscape" : "";
160
+ const getBaseDomain = () => {
161
+ try {
162
+ const regexResult = window.location.host.match(/[^.]*\.[^.]*$/);
163
+ if (regexResult)
164
+ return regexResult[0];
165
+ return "";
166
+ }
167
+ catch (err) {
168
+ return window.location.host;
169
+ }
170
+ };
171
+ const getPageName = () => {
172
+ let page = "";
173
+ if (window.location) {
174
+ page = window.location.pathname.substring(1);
175
+ page = page.replace(/\/+$/, "");
176
+ }
177
+ return page === "" ? "/" : page;
178
+ };
179
+ const getUrlParameter = (name) => {
180
+ if (!window.location || !window.location.search) {
181
+ return "";
182
+ }
183
+ name = name.replace(/[[]/, "\\[").replace(/[\]]/, "\\]");
184
+ const regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
185
+ const results = regex.exec(window.location.search);
186
+ return results === null
187
+ ? ""
188
+ : decodeURIComponent(results[1].replace(/\+/g, " "));
189
+ };
190
+
191
+ /*
192
+ Authored by Brett Barinaga on 11/17/21.
193
+ Copyright (c) Kochava, Inc. All rights reserved.
194
+ */
195
+ const constructPayload = (action, instance, originalNtId) => {
196
+ let nt_id = `${instance.kochavaSession}-${instance.kochavaSessionCount}-${uuidv4()}`;
197
+ if (originalNtId) {
198
+ Log.debug("Persisted call found with nt_id:", originalNtId);
199
+ nt_id = originalNtId;
200
+ }
201
+ return {
202
+ action: action,
203
+ kochava_app_id: instance.appGuid,
204
+ kochava_device_id: instance.kochavaDeviceId,
205
+ sdk_version: instance.version,
206
+ sdk_protocol: "17",
207
+ nt_id: nt_id,
208
+ init_token: (instance.kochavaConfig.config.init_token) || undefined,
209
+ };
210
+ };
211
+ const constructCommonData = (instance) => {
212
+ const currTime = getCurrTimeMS();
213
+ let uptime = (currTime - instance.startTimeMS) / 1000;
214
+ if (uptime < 0.0)
215
+ uptime = 0.0;
216
+ return {
217
+ starttime: instance.startTimeMS / 1000,
218
+ uptime: uptime,
219
+ usertime: currTime / 1000,
220
+ };
221
+ };
222
+
223
+ const constructPreStart$1 = (instance, eventName, eventData) => {
224
+ const preStart = {
225
+ action: "event",
226
+ sdk_version: instance.version,
227
+ sdk_protocol: "17",
228
+ data: {
229
+ event_name: eventName,
230
+ event_data: eventData,
231
+ device_orientation: getDeviceOrientation(),
232
+ disp_w: getDeviceWidth(),
233
+ disp_h: getDeviceHeight(),
234
+ },
235
+ };
236
+ if (instance.kochavaConfig)
237
+ preStart.init_token = (instance.kochavaConfig.config.init_token) || undefined;
238
+ return preStart;
239
+ };
240
+ const constructPostStart$1 = (instance, preStartBody) => {
241
+ const postStartBody = {
242
+ kochava_app_id: instance.appGuid,
243
+ kochava_device_id: instance.kochavaDeviceId,
244
+ nt_id: `${instance.kochavaSession}-${instance.kochavaSessionCount}-${uuidv4()}`,
245
+ };
246
+ postStartBody.data = Object.assign(Object.assign({}, constructCommonData(instance)), preStartBody.data);
247
+ instance.customValues.forEach((custom) => {
248
+ if (!custom.isDeviceId) {
249
+ const customKey = Object.keys(custom.data)[0];
250
+ if (instance.kochavaConfig.privacy) {
251
+ let keyAllowed = false;
252
+ for (const allowed of instance.kochavaConfig.privacy.allow_custom_ids) {
253
+ if (customKey === allowed) {
254
+ keyAllowed = true;
255
+ }
256
+ }
257
+ if (keyAllowed)
258
+ postStartBody.data = Object.assign(Object.assign({}, custom.data), postStartBody.data);
259
+ }
260
+ }
261
+ });
262
+ return postStartBody;
263
+ };
264
+ const build$3 = (instance, preStartBody, postStartBody) => {
265
+ const payload = Object.assign(Object.assign({}, preStartBody), postStartBody);
266
+ Log.debug("Event Payload", JSON.stringify(payload));
267
+ if (instance.kochavaConfig.privacy) {
268
+ instance.kochavaConfig.privacy.deny_datapoints.forEach(denyPoint => {
269
+ for (const point in payload.data) {
270
+ const key = point;
271
+ if (key === denyPoint)
272
+ delete payload.data[key];
273
+ }
274
+ for (const point in payload) {
275
+ const key = point;
276
+ if (key === denyPoint)
277
+ delete payload[key];
278
+ }
279
+ });
280
+ }
281
+ return payload;
282
+ };
283
+ const send$3 = (instance, preStartBody, postStartBody) => __awaiter(void 0, void 0, void 0, function* () {
284
+ const payload = build$3(instance, preStartBody, postStartBody);
285
+ const respStr = yield sendRequest(payload, (instance.overrideUrls.event) ?
286
+ instance.overrideUrls.event : instance.kochavaConfig.networking.urls.event);
287
+ let resp;
288
+ let success = false;
289
+ try {
290
+ Log.trace("Event Response string:", respStr);
291
+ resp = JSON.parse(respStr);
292
+ Log.debug("Event Response:", respStr);
293
+ success = wasRespSuccess(resp.success);
294
+ }
295
+ catch (e) {
296
+ Log.error("Error parsing Event Response", e);
297
+ success = false;
298
+ }
299
+ if (success) {
300
+ Log.info("Event success!");
301
+ return true;
302
+ }
303
+ Log.error("Event failed!");
304
+ return false;
305
+ });
306
+
307
+ const constructPreStart = (instance, idLink) => {
308
+ const preStart = {
309
+ action: "identityLink",
310
+ sdk_version: instance.version,
311
+ sdk_protocol: "17",
312
+ data: {
313
+ identity_link: Object.assign({}, idLink),
314
+ },
315
+ };
316
+ if (instance.kochavaConfig)
317
+ preStart.init_token = (instance.kochavaConfig.config.init_token) || undefined;
318
+ return preStart;
319
+ };
320
+ const constructPostStart = (instance, preStartBody) => {
321
+ const postStartBody = {
322
+ kochava_app_id: instance.appGuid,
323
+ kochava_device_id: instance.kochavaDeviceId,
324
+ nt_id: `${instance.kochavaSession}-${instance.kochavaSessionCount}-${uuidv4()}`,
325
+ };
326
+ postStartBody.data = Object.assign(Object.assign({}, preStartBody.data), constructCommonData(instance));
327
+ return postStartBody;
328
+ };
329
+ const build$2 = (instance, job) => {
330
+ const payload = Object.assign(Object.assign({}, job.preStartBody), job.postStartBody);
331
+ Log.debug("IdentityLink Payload", JSON.stringify(payload));
332
+ Log.diagDebug(`IdentityLink to be sent as stand alone`);
333
+ if (instance.kochavaConfig.privacy) {
334
+ instance.kochavaConfig.privacy.deny_datapoints.forEach(denyPoint => {
335
+ for (const point in payload.data) {
336
+ const key = point;
337
+ if (key === denyPoint)
338
+ delete payload.data[key];
339
+ }
340
+ for (const point in payload) {
341
+ const key = point;
342
+ if (key === denyPoint)
343
+ delete payload[key];
344
+ }
345
+ });
346
+ }
347
+ return payload;
348
+ };
349
+ const send$2 = (instance, job) => __awaiter(void 0, void 0, void 0, function* () {
350
+ const payload = build$2(instance, job);
351
+ const respStr = yield sendRequest(payload, (instance.overrideUrls.identityLink) ?
352
+ instance.overrideUrls.identityLink : instance.kochavaConfig.networking.urls.identityLink);
353
+ let resp;
354
+ let success = false;
355
+ try {
356
+ Log.trace("IdentityLink Response string:", respStr);
357
+ resp = JSON.parse(respStr);
358
+ Log.debug("IdentityLink Response:", respStr);
359
+ success = wasRespSuccess(resp.success);
360
+ }
361
+ catch (e) {
362
+ Log.error("Error parsing IdentityLink Response", e);
363
+ success = false;
364
+ }
365
+ if (success) {
366
+ Log.info("IdentityLink success!");
367
+ return true;
368
+ }
369
+ Log.error("IdentityLink failed!");
370
+ return false;
371
+ });
372
+
373
+ /*
374
+ Authored by Brett Barinaga on 11/17/21.
375
+ Copyright (c) Kochava, Inc. All rights reserved.
376
+ */
377
+ const setCookie = (name, value) => {
378
+ let expires = "";
379
+ const date = new Date();
380
+ date.setTime(date.getTime() + 3650 * 24 * 60 * 60 * 1000);
381
+ expires = `; expires=${date.toUTCString()}`;
382
+ document.cookie =
383
+ name +
384
+ "=" +
385
+ (value || "") +
386
+ expires +
387
+ "; path=/;domain=" +
388
+ getBaseDomain();
389
+ };
390
+ const getCookie = (name) => {
391
+ const nameEQ = name + "=";
392
+ const charArray = document.cookie.split(';');
393
+ for (let i = 0; i < charArray.length; i++) {
394
+ let char = charArray[i];
395
+ while (char.charAt(0) === " ")
396
+ char = char.substring(1, char.length);
397
+ if (char.indexOf(nameEQ) === 0)
398
+ return char.substring(nameEQ.length, char.length);
399
+ }
400
+ return "";
401
+ };
402
+ const deleteCookie = (name) => {
403
+ if (getCookie(name)) {
404
+ const path = "/";
405
+ const domain = getBaseDomain();
406
+ document.cookie = name + "=" +
407
+ ((path) ? ";path=" + path : "") +
408
+ ((domain) ? ";domain=" + domain : "") +
409
+ ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
410
+ }
411
+ };
412
+
413
+ /*
414
+ Authored by Brett Barinaga on 11/17/21.
415
+ Copyright (c) Kochava, Inc. All rights reserved.
416
+ */
417
+ const MAX_STORED_IDLINKS = 10;
418
+ var PersistKey;
419
+ (function (PersistKey) {
420
+ PersistKey["LastKvinit"] = "com.kochava.tracker.LastKvinit";
421
+ PersistKey["EventQueue"] = "com.kochava.tracker.EventQueue";
422
+ PersistKey["IdLinkQueue"] = "com.kochava.tracker.IdLinkQueue";
423
+ PersistKey["DeviceId"] = "com.kochava.tracker.DeviceId";
424
+ PersistKey["InstallId"] = "com.kochava.tracker.InstallId";
425
+ PersistKey["FirstStartDate"] = "com.kochava.tracker.FirstStartDate";
426
+ PersistKey["InstallSentDate"] = "com.kochava.tracker.InstallSentDate";
427
+ PersistKey["KvinitSentDate"] = "com.kochava.tracker.KvinitSentDate";
428
+ PersistKey["SessionCount"] = "com.kochava.tracker.SessionCount";
429
+ PersistKey["IdentityLinks"] = "com.kochava.tracker.IdentityLinks";
430
+ PersistKey["OverrideAppId"] = "com.kochava.tracker.OverrideAppId";
431
+ PersistKey["OverrideDeviceId"] = "com.kochava.tracker.OverrideDeviceId";
432
+ PersistKey["OldKvid"] = "kv_id";
433
+ })(PersistKey || (PersistKey = {}));
434
+ const storedKeys = [
435
+ PersistKey.LastKvinit,
436
+ PersistKey.EventQueue,
437
+ PersistKey.IdLinkQueue,
438
+ PersistKey.DeviceId,
439
+ PersistKey.InstallId,
440
+ PersistKey.FirstStartDate,
441
+ PersistKey.InstallSentDate,
442
+ PersistKey.KvinitSentDate,
443
+ PersistKey.SessionCount,
444
+ PersistKey.IdentityLinks,
445
+ PersistKey.OverrideAppId,
446
+ PersistKey.OverrideDeviceId,
447
+ ];
448
+ const checkInstallIdChange = (inputId, useCookies) => {
449
+ const persistedInstallId = readAndUpdatePersistedValue(PersistKey.InstallId, useCookies);
450
+ // if the input is empty, we don't need to change
451
+ if (!inputId)
452
+ return false;
453
+ // if the persistedId is empty, we will need to change
454
+ if (!persistedInstallId) {
455
+ updatePersistedValue(PersistKey.InstallId, inputId, useCookies);
456
+ return true;
457
+ }
458
+ // if the inputId and persistedId are the same, we dont need to change
459
+ if (inputId === persistedInstallId)
460
+ return false;
461
+ // at this point both inputId and persistedInstallId exist and are not equal,
462
+ // so we must need to change
463
+ updatePersistedValue(PersistKey.InstallId, inputId, useCookies);
464
+ return true;
465
+ };
466
+ const addToPersistedEventQueue = (job) => {
467
+ const persistedQueueStr = localStorage.getItem(PersistKey.EventQueue);
468
+ const persistedQueue = JSON.parse(persistedQueueStr) || [];
469
+ persistedQueue.push(job);
470
+ localStorage.setItem(PersistKey.EventQueue, JSON.stringify(persistedQueue));
471
+ };
472
+ const removeFromEventPersistedQueue = (job) => {
473
+ const persistedQueueStr = localStorage.getItem(PersistKey.EventQueue);
474
+ const persistedQueue = JSON.parse(persistedQueueStr) || [];
475
+ const queueWithJobRemoved = persistedQueue.filter(persistedJob => {
476
+ return persistedJob.id !== job.id;
477
+ });
478
+ localStorage.setItem(PersistKey.EventQueue, JSON.stringify(queueWithJobRemoved));
479
+ };
480
+ const updateOrAddPersistedIdLinkQueue = (job) => {
481
+ const idLinkKey = Object.keys(job.idLink)[0];
482
+ const persistedQueueStr = localStorage.getItem(PersistKey.IdLinkQueue);
483
+ const persistedQueue = JSON.parse(persistedQueueStr) || [];
484
+ let updated = false;
485
+ for (const persistedJob of persistedQueue) {
486
+ const persistedKey = Object.keys(persistedJob.idLink)[0];
487
+ // if the key is already there, update it
488
+ if (idLinkKey === persistedKey) {
489
+ persistedJob.idLink[idLinkKey] = job.idLink[idLinkKey];
490
+ updated = true;
491
+ }
492
+ }
493
+ // if the key is new, add it
494
+ if (!updated)
495
+ persistedQueue.push(job);
496
+ localStorage.setItem(PersistKey.IdLinkQueue, JSON.stringify(persistedQueue));
497
+ };
498
+ const removeFromIdLinkPersistedQueue = (job) => {
499
+ const persistedQueueStr = localStorage.getItem(PersistKey.IdLinkQueue);
500
+ const persistedQueue = JSON.parse(persistedQueueStr) || [];
501
+ const queueWithJobRemoved = persistedQueue.filter(persistedJob => {
502
+ return persistedJob.id !== job.id;
503
+ });
504
+ localStorage.setItem(PersistKey.IdLinkQueue, JSON.stringify(queueWithJobRemoved));
505
+ };
506
+ const addPersistedIdLinks = (key, value, useCookies) => {
507
+ const persistedIdLinksStr = localStorage.getItem(PersistKey.IdentityLinks);
508
+ const persistedIdLinks = JSON.parse(persistedIdLinksStr) || {};
509
+ const storedSoFar = Object.keys(persistedIdLinks);
510
+ if (storedSoFar.length > MAX_STORED_IDLINKS) {
511
+ Log.debug("Maximum stored idLinks reached, most recent idLink will not be stored.");
512
+ return;
513
+ }
514
+ persistedIdLinks[key] = value;
515
+ updatePersistedValue(PersistKey.IdentityLinks, JSON.stringify(persistedIdLinks), useCookies);
516
+ };
517
+ const checkDuplicateIdLink = (key, value) => {
518
+ const persistedIdLinksStr = localStorage.getItem(PersistKey.IdentityLinks);
519
+ if (persistedIdLinksStr) {
520
+ const persistedIdLinks = JSON.parse(persistedIdLinksStr) || {};
521
+ for (const persistedKey in persistedIdLinks) {
522
+ if (key === persistedKey && persistedIdLinks[persistedKey] === value) {
523
+ return true;
524
+ }
525
+ }
526
+ }
527
+ return false;
528
+ };
529
+ const getPersistedIdentityLinks = () => {
530
+ const persistedIdLinksStr = localStorage.getItem(PersistKey.IdentityLinks);
531
+ if (persistedIdLinksStr) {
532
+ return JSON.parse(persistedIdLinksStr);
533
+ }
534
+ return undefined;
535
+ };
536
+ const readAndUpdateUTM = (appGuid, useCookies) => {
537
+ const storageName = appGuid + "_click";
538
+ const urlValue = getUrlParameter("ko_click_id");
539
+ const storageValue = localStorage.getItem(storageName);
540
+ let cookieValue = "";
541
+ if (useCookies)
542
+ cookieValue = getCookie(storageName);
543
+ if (urlValue) {
544
+ localStorage.setItem(storageName, urlValue);
545
+ if (useCookies)
546
+ setCookie(storageName, urlValue);
547
+ }
548
+ else if (storageValue) {
549
+ if (useCookies)
550
+ setCookie(storageName, urlValue);
551
+ }
552
+ return (urlValue) ? urlValue :
553
+ (storageValue) ? storageValue :
554
+ (cookieValue) ? cookieValue : "";
555
+ };
556
+ const readAndUpdatePersistedValue = (key, useCookie) => {
557
+ const urlValue = getUrlParameter(key);
558
+ const storageValue = localStorage.getItem(key);
559
+ let cookieValue = "";
560
+ if (useCookie)
561
+ cookieValue = getCookie(key);
562
+ if (urlValue) {
563
+ updatePersistedValue(key, urlValue, useCookie);
564
+ }
565
+ else if (storageValue) {
566
+ updatePersistedValue(key, storageValue, useCookie);
567
+ }
568
+ else if (cookieValue) {
569
+ updatePersistedValue(key, storageValue, useCookie);
570
+ }
571
+ return (urlValue) ? urlValue :
572
+ (storageValue) ? storageValue :
573
+ (cookieValue) ? cookieValue : "";
574
+ };
575
+ const updatePersistedValue = (key, value, useCookie) => {
576
+ localStorage.setItem(key, value);
577
+ if (useCookie)
578
+ setCookie(key, value);
579
+ };
580
+ const deletePersistedValue = (item) => {
581
+ localStorage.removeItem(item);
582
+ deleteCookie(item);
583
+ };
584
+ const deleteAllPersisted = () => storedKeys.forEach(item => deletePersistedValue(item));
585
+ const readAndUpdateDeviceId = (useCookie) => {
586
+ let storedDeviceId = readAndUpdatePersistedValue(PersistKey.DeviceId, useCookie);
587
+ if (!storedDeviceId) {
588
+ const kvId = `KB${getCurrTimeSec()}T${uuidv4()}`;
589
+ storedDeviceId = kvId.replace(/-/g, "");
590
+ }
591
+ updatePersistedValue(PersistKey.DeviceId, storedDeviceId, useCookie);
592
+ return storedDeviceId;
593
+ };
594
+ const readAndUpdateSessionCount = (useCookie) => {
595
+ const storedSessionCount = readAndUpdatePersistedValue(PersistKey.SessionCount, useCookie);
596
+ let sessionCount = 1;
597
+ if (storedSessionCount) {
598
+ sessionCount = parseInt(storedSessionCount);
599
+ sessionCount++;
600
+ }
601
+ updatePersistedValue(PersistKey.SessionCount, sessionCount.toString(), useCookie);
602
+ return sessionCount;
603
+ };
604
+
605
+ function jobIsEventJob(obj) {
606
+ return 'eventName' in obj;
607
+ }
608
+ function jobIsIdLinkJob(obj) {
609
+ return 'idLink' in obj;
610
+ }
611
+ class JobQueue {
612
+ constructor() {
613
+ this.eventQueue = [];
614
+ this.idLinkQueue = [];
615
+ this.processing = false;
616
+ this.stopped = false;
617
+ this.paused = false;
618
+ }
619
+ start(instance) {
620
+ return __awaiter(this, void 0, void 0, function* () {
621
+ this.eventQueue = JSON.parse(localStorage.getItem(PersistKey.EventQueue)) || [];
622
+ this.idLinkQueue = JSON.parse(localStorage.getItem(PersistKey.IdLinkQueue)) || [];
623
+ this.updateEventJobs(instance);
624
+ this.updateIdLinkJobs(instance);
625
+ Log.trace("Starting Event Queue", JSON.parse(JSON.stringify(this.eventQueue)));
626
+ Log.trace("Starting IdLink Queue", JSON.parse(JSON.stringify(this.idLinkQueue)));
627
+ this.stopped = false;
628
+ this.paused = false;
629
+ yield this.dequeueJob(instance);
630
+ });
631
+ }
632
+ stop() {
633
+ this.stopped = true;
634
+ if (this.timeOut)
635
+ clearTimeout(this.timeOut);
636
+ this.processing = false;
637
+ }
638
+ pause() {
639
+ this.paused = true;
640
+ }
641
+ enqueueEvent(instance, args) {
642
+ return __awaiter(this, void 0, void 0, function* () {
643
+ const eventName = args[0];
644
+ const eventData = args[1];
645
+ const eventPreStartBody = constructPreStart$1(instance, eventName, eventData);
646
+ if (instance.installDone && instance.kvinitDone) {
647
+ const postStartBody = constructPostStart$1(instance, eventPreStartBody);
648
+ const newJob = {
649
+ id: uuidv4(),
650
+ queuedBeforeStart: false,
651
+ preStartBody: eventPreStartBody,
652
+ postStartBody,
653
+ retries: 0,
654
+ eventName,
655
+ };
656
+ this.eventQueue.push(newJob);
657
+ addToPersistedEventQueue(newJob);
658
+ yield this.dequeueJob(instance);
659
+ return;
660
+ }
661
+ const newEventJob = {
662
+ id: uuidv4(),
663
+ queuedBeforeStart: true,
664
+ preStartBody: eventPreStartBody,
665
+ postStartBody: undefined,
666
+ retries: 0,
667
+ eventName,
668
+ };
669
+ this.eventQueue.push(newEventJob);
670
+ addToPersistedEventQueue(newEventJob);
671
+ });
672
+ }
673
+ enqueueIdLink(instance, idLink) {
674
+ return __awaiter(this, void 0, void 0, function* () {
675
+ const idLinkPreStartBody = constructPreStart(instance, idLink);
676
+ if (instance.installDone && instance.kvinitDone) {
677
+ const postStartBody = constructPostStart(instance, idLinkPreStartBody);
678
+ const newJob = {
679
+ id: uuidv4(),
680
+ queuedBeforeStart: false,
681
+ preStartBody: idLinkPreStartBody,
682
+ postStartBody,
683
+ retries: 0,
684
+ idLink,
685
+ };
686
+ updateOrAddPersistedIdLinkQueue(newJob);
687
+ this.idLinkQueue.push(newJob);
688
+ yield this.dequeueJob(instance);
689
+ return;
690
+ }
691
+ const newJob = {
692
+ id: uuidv4(),
693
+ queuedBeforeStart: true,
694
+ preStartBody: idLinkPreStartBody,
695
+ postStartBody: undefined,
696
+ retries: 0,
697
+ idLink,
698
+ };
699
+ updateOrAddPersistedIdLinkQueue(newJob);
700
+ this.idLinkQueue.push(newJob);
701
+ });
702
+ }
703
+ dequeueJob(instance) {
704
+ return __awaiter(this, void 0, void 0, function* () {
705
+ // If queue is busy, prev job not finished
706
+ if (this.processing)
707
+ return false;
708
+ // If the queue is paused, do not dequeue a new job
709
+ if (this.paused)
710
+ return false;
711
+ // If the queue is stopped do not dequeue a new job
712
+ if (this.stopped) {
713
+ return false;
714
+ }
715
+ // Prioritize sending identityLinks first
716
+ // Remove first job from queue
717
+ const idLinkJob = this.idLinkQueue.shift();
718
+ if (idLinkJob) {
719
+ // handle idlinkjob
720
+ Log.trace("Dequeued Job: ", idLinkJob);
721
+ this.processing = true;
722
+ const result = yield this.processJob(instance, idLinkJob);
723
+ if (this.stopped) {
724
+ return true;
725
+ }
726
+ this.processing = false;
727
+ // If the job succeeded, dequeue the next job
728
+ if (result) {
729
+ removeFromIdLinkPersistedQueue(idLinkJob);
730
+ return yield this.dequeueJob(instance);
731
+ }
732
+ }
733
+ const eventJob = this.eventQueue.shift();
734
+ if (eventJob) {
735
+ //handle eventJob
736
+ Log.trace("Dequeued Job: ", eventJob);
737
+ // Process the job
738
+ this.processing = true;
739
+ const result = yield this.processJob(instance, eventJob);
740
+ if (this.stopped) {
741
+ return true;
742
+ }
743
+ this.processing = false;
744
+ // If the job succeeded, dequeue the next job
745
+ if (result) {
746
+ removeFromEventPersistedQueue(eventJob);
747
+ return yield this.dequeueJob(instance);
748
+ }
749
+ }
750
+ // If neither queue had a job, break out of recursion
751
+ if (!idLinkJob && !eventJob)
752
+ return false;
753
+ return true;
754
+ });
755
+ }
756
+ processJob(instance, job) {
757
+ return __awaiter(this, void 0, void 0, function* () {
758
+ if (jobIsEventJob(job)) {
759
+ for (const denyName of instance.kochavaConfig.privacy.deny_event_names) {
760
+ if (denyName === job.eventName) {
761
+ Log.debug(`Denied event_name ${denyName}, dropping request.`);
762
+ return true;
763
+ }
764
+ }
765
+ }
766
+ else if (jobIsIdLinkJob(job)) {
767
+ for (const denyIdLinkKey of instance.kochavaConfig.privacy.deny_identity_links) {
768
+ if (denyIdLinkKey === Object.keys(job.idLink)[0]) {
769
+ Log.debug(`Denied identity_link ${denyIdLinkKey}, dropping request.`);
770
+ return true;
771
+ }
772
+ }
773
+ }
774
+ let success = false;
775
+ do {
776
+ success = yield this.attemptJob(instance, job);
777
+ // If our job succeeded
778
+ if (success) {
779
+ // Job Done
780
+ Log.trace("Job processed successfully:", job);
781
+ return true;
782
+ }
783
+ // If it didnt succeed, but we our queue isnt stopped
784
+ if (!this.stopped) {
785
+ //retry the job
786
+ const retryWaterfall = instance.kochavaConfig.networking.retry_waterfall;
787
+ const retryIndex = (job.retries > retryWaterfall.length - 1) ?
788
+ retryWaterfall.length - 1 : job.retries;
789
+ const retrySec = retryWaterfall[retryIndex];
790
+ Log.error(`Job failed, attempting again in ${retrySec} seconds`);
791
+ yield new Promise(resolve => this.timeOut = setTimeout(resolve, retrySec * 1000));
792
+ job.retries++;
793
+ }
794
+ } while (!success && !this.stopped);
795
+ // Job Canceled
796
+ return true;
797
+ });
798
+ }
799
+ attemptJob(instance, job) {
800
+ return __awaiter(this, void 0, void 0, function* () {
801
+ if (job.preStartBody.action === "event")
802
+ return yield send$3(instance, job.preStartBody, job.postStartBody);
803
+ else if (job.preStartBody.action === "identityLink")
804
+ return yield send$2(instance, job);
805
+ else {
806
+ Log.warn("Invalid action in job from jobqueue, cancelling.");
807
+ return true;
808
+ }
809
+ });
810
+ }
811
+ updateEventJobs(instance) {
812
+ for (const job of this.eventQueue) {
813
+ if (job.queuedBeforeStart) {
814
+ job.postStartBody = constructPostStart$1(instance, job.preStartBody);
815
+ }
816
+ }
817
+ updatePersistedValue(PersistKey.EventQueue, JSON.stringify(this.eventQueue), false);
818
+ }
819
+ updateIdLinkJobs(instance) {
820
+ for (const job of this.idLinkQueue) {
821
+ if (job.queuedBeforeStart) {
822
+ job.postStartBody = constructPostStart(instance, job.preStartBody);
823
+ }
824
+ }
825
+ updatePersistedValue(PersistKey.IdLinkQueue, JSON.stringify(this.idLinkQueue), false);
826
+ }
827
+ }
828
+
829
+ /*
830
+ Authored by Brett Barinaga on 11/17/21.
831
+ Copyright (c) Kochava, Inc. All rights reserved.
832
+ */
833
+ const DEFAULTS = {
834
+ general: {
835
+ // DO NOT DEFAULT
836
+ app_id_override: "",
837
+ // DO NOT DEFAULT
838
+ device_id_override: "",
839
+ },
840
+ config: {
841
+ init_token: "",
842
+ refresh_minimum: 60,
843
+ },
844
+ install: {
845
+ // DO NOT DEFAULT
846
+ resend_id: "",
847
+ updates_enabled: true,
848
+ },
849
+ networking: {
850
+ urls: {
851
+ init: "https://kvinit-prod.api.kochava.com/track/kvinit",
852
+ install: "https://web-sdk.control.kochava.com/track/json/",
853
+ event: "https://web-sdk.control.kochava.com/track/json/",
854
+ identityLink: "https://web-sdk.control.kochava.com/v1/cpi/identityLink.php"
855
+ },
856
+ retry_waterfall: [7, 30, 300, 1800],
857
+ },
858
+ privacy: {
859
+ allow_custom_ids: [],
860
+ deny_datapoints: [],
861
+ deny_event_names: [],
862
+ deny_identity_links: [],
863
+ },
864
+ };
865
+
866
+ let timeOut$1;
867
+ let canceled$1 = false;
868
+ const build$1 = (instance) => {
869
+ const payload = constructPayload("init", instance);
870
+ payload.build_date = instance.buildDate;
871
+ payload.data = constructKvinitData(instance);
872
+ Log.debug("Kvinit Payload", JSON.stringify(payload));
873
+ return payload;
874
+ };
875
+ const cancelRetries$1 = () => {
876
+ canceled$1 = true;
877
+ clearTimeout(timeOut$1);
878
+ };
879
+ const send$1 = (instance, retryWaterfall, retries = 0) => __awaiter(void 0, void 0, void 0, function* () {
880
+ canceled$1 = false;
881
+ const payload = build$1(instance);
882
+ let success = false;
883
+ let resp;
884
+ do {
885
+ Log.trace("Kvinit endpoint:", instance.kochavaConfig.networking.urls.init);
886
+ const sendTime = getCurrTimeMS() - instance.startTimeMS;
887
+ Log.diagDebug(`Sending kvinit at ${formatTime(sendTime / 1000)} seconds`);
888
+ const respStr = yield sendRequest(payload, (instance.overrideUrls.init) ?
889
+ instance.overrideUrls.init : instance.kochavaConfig.networking.urls.init);
890
+ const respTime = getCurrTimeMS() - instance.startTimeMS;
891
+ Log.diagDebug(`Completed kvinit at ${formatTime(respTime / 1000)}
892
+ seconds with a network duration of ${formatTime((respTime - sendTime) / 1000)} seconds`);
893
+ if (canceled$1) {
894
+ Log.trace("Can no longer retry kvinit, cancelling.");
895
+ return false;
896
+ }
897
+ try {
898
+ resp = JSON.parse(respStr);
899
+ Log.debug("Kvinit Response:", resp);
900
+ success = wasRespSuccess(resp.success);
901
+ }
902
+ catch (e) {
903
+ Log.error("Error parsing Kvinit Response", e);
904
+ success = false;
905
+ }
906
+ if (success) {
907
+ Log.info("Kvinit success!");
908
+ updatePersistedValue(PersistKey.LastKvinit, JSON.stringify(resp), instance.useCookies);
909
+ return success;
910
+ }
911
+ if (!canceled$1) {
912
+ // retry kvinit
913
+ const retryIndex = (retries > retryWaterfall.length - 1) ? retryWaterfall.length - 1 : retries;
914
+ const retrySec = retryWaterfall[retryIndex];
915
+ Log.error(`Kvinit failed, attempting again in ${retrySec} seconds`);
916
+ yield new Promise(resolve => { timeOut$1 = setTimeout(resolve, retrySec * 1000); });
917
+ retries++;
918
+ }
919
+ } while (!success && !canceled$1);
920
+ });
921
+ const applyKvinitResp = (instance, resp) => {
922
+ if (resp.general) {
923
+ if (resp.general.device_id_override) {
924
+ Log.trace(`Device_id override found, going from ${instance.kochavaDeviceId} to
925
+ ${resp.general.device_id_override}`);
926
+ instance.kochavaConfig.general.device_id_override = resp.general.device_id_override;
927
+ instance.kochavaDeviceId = resp.general.device_id_override;
928
+ updatePersistedValue(PersistKey.OverrideDeviceId, resp.general.device_id_override, instance.useCookies);
929
+ }
930
+ if (resp.general.app_id_override) {
931
+ Log.trace(`App_id override found, going from ${instance.appGuid} to
932
+ ${resp.general.app_id_override}`);
933
+ instance.kochavaConfig.general.app_id_override = resp.general.app_id_override;
934
+ instance.appGuid = resp.general.app_id_override;
935
+ updatePersistedValue(PersistKey.OverrideAppId, resp.general.app_id_override, instance.useCookies);
936
+ }
937
+ }
938
+ if (resp.config) {
939
+ instance.kochavaConfig.config = {
940
+ init_token: resp.config.init_token || DEFAULTS.config.init_token,
941
+ refresh_minimum: (resp.config.refresh_minimum !== undefined &&
942
+ resp.config.refresh_minimum !== null) ? resp.config.refresh_minimum :
943
+ DEFAULTS.config.refresh_minimum,
944
+ };
945
+ }
946
+ if (resp.install) {
947
+ if (resp.install.resend_id) {
948
+ instance.kochavaConfig.install.resend_id = resp.install.resend_id;
949
+ }
950
+ instance.kochavaConfig.install.updates_enabled =
951
+ resp.install.updates_enabled || DEFAULTS.install.updates_enabled;
952
+ }
953
+ if (resp.networking) {
954
+ instance.kochavaConfig.networking.retry_waterfall =
955
+ resp.networking.retry_waterfall || DEFAULTS.networking.retry_waterfall;
956
+ instance.retryWaterfall =
957
+ instance.kochavaConfig.networking.retry_waterfall;
958
+ if (resp.networking.urls) {
959
+ instance.kochavaConfig.networking.urls = {
960
+ init: resp.networking.urls.init || DEFAULTS.networking.urls.init,
961
+ install: resp.networking.urls.install || DEFAULTS.networking.urls.install,
962
+ event: resp.networking.urls.event || DEFAULTS.networking.urls.event,
963
+ identityLink: resp.networking.urls.identityLink || DEFAULTS.networking.urls.identityLink,
964
+ };
965
+ }
966
+ }
967
+ if (resp.privacy) {
968
+ instance.kochavaConfig.privacy = {
969
+ allow_custom_ids: resp.privacy.allow_custom_ids || DEFAULTS.privacy.allow_custom_ids,
970
+ deny_datapoints: resp.privacy.deny_datapoints || DEFAULTS.privacy.deny_datapoints,
971
+ deny_event_names: resp.privacy.deny_event_names || DEFAULTS.privacy.deny_event_names,
972
+ deny_identity_links: resp.privacy.deny_identity_links || DEFAULTS.privacy.deny_identity_links,
973
+ };
974
+ }
975
+ };
976
+ const constructKvinitData = (instance) => {
977
+ const currTime = Math.floor(Date.now() / 1000);
978
+ let uptime = (currTime - instance.startTimeMS) / 1000;
979
+ if (uptime < 0.0)
980
+ uptime = 0.0;
981
+ return {
982
+ package: getPackageName(),
983
+ platform: "web",
984
+ starttime: instance.startTimeMS / 1000,
985
+ uptime,
986
+ usertime: currTime,
987
+ };
988
+ };
989
+
990
+ let timeOut;
991
+ let canceled = false;
992
+ const build = (instance) => {
993
+ const payload = constructPayload("install", instance);
994
+ instance.installStarted = true;
995
+ payload.data = constructInstallData(instance);
996
+ Log.debug("Install Payload", JSON.stringify(payload));
997
+ if (instance.kochavaConfig.privacy) {
998
+ instance.kochavaConfig.privacy.deny_datapoints.forEach(denyPoint => {
999
+ for (const point in payload.data) {
1000
+ const key = point;
1001
+ if (key === denyPoint)
1002
+ delete payload.data[key];
1003
+ }
1004
+ for (const point in payload) {
1005
+ const key = point;
1006
+ if (key === denyPoint)
1007
+ delete payload[key];
1008
+ }
1009
+ });
1010
+ }
1011
+ return payload;
1012
+ };
1013
+ const cancelRetries = () => {
1014
+ canceled = true;
1015
+ clearTimeout(timeOut);
1016
+ };
1017
+ const send = (instance, payload, retries = 0) => __awaiter(void 0, void 0, void 0, function* () {
1018
+ canceled = false;
1019
+ let success = false;
1020
+ let resp;
1021
+ do {
1022
+ const sendTime = getCurrTimeMS() - instance.startTimeMS;
1023
+ Log.diagDebug(`Sending install at ${formatTime(sendTime / 1000)} seconds`);
1024
+ const respStr = yield sendRequest(payload, (instance.overrideUrls.install) ?
1025
+ instance.overrideUrls.install : instance.kochavaConfig.networking.urls.install);
1026
+ const respTime = getCurrTimeMS() - instance.startTimeMS;
1027
+ Log.diagDebug(`Completed install at ${new Date().toLocaleTimeString()}
1028
+ seconds with a network duration of ${formatTime((respTime - sendTime) / 1000)} seconds`);
1029
+ if (canceled) {
1030
+ Log.trace("Can no longer retry install, cancelling.");
1031
+ return false;
1032
+ }
1033
+ try {
1034
+ Log.trace("Install Response string:", respStr);
1035
+ resp = JSON.parse(respStr);
1036
+ Log.debug("Install Response:", respStr);
1037
+ success = wasRespSuccess(resp.success);
1038
+ }
1039
+ catch (e) {
1040
+ Log.error("Error parsing Install Response", e);
1041
+ success = false;
1042
+ }
1043
+ if (success) {
1044
+ Log.info("Install success!");
1045
+ return success;
1046
+ }
1047
+ if (!canceled) {
1048
+ const retryWaterfall = instance.kochavaConfig.networking.retry_waterfall;
1049
+ const retryIndex = (retries > retryWaterfall.length - 1) ? retryWaterfall.length - 1 : retries;
1050
+ const retrySec = retryWaterfall[retryIndex];
1051
+ Log.error(`Install failed, attempting again in ${retrySec} seconds`);
1052
+ yield new Promise(resolve => { timeOut = setTimeout(resolve, retrySec * 1000); });
1053
+ retries++;
1054
+ }
1055
+ } while (!success && !canceled);
1056
+ });
1057
+ const onSuccess = (instance) => {
1058
+ instance.kochavaInstallDate = getCurrTimeMS();
1059
+ updatePersistedValue(PersistKey.InstallSentDate, String(instance.kochavaInstallDate), instance.useCookies);
1060
+ };
1061
+ const constructInstallData = (instance) => {
1062
+ const currTime = Math.floor(Date.now() / 1000);
1063
+ let uptime = (currTime - instance.startTimeMS) / 1000;
1064
+ if (uptime < 0.0)
1065
+ uptime = 0.0;
1066
+ let returnObj = {
1067
+ starttime: instance.startTimeMS / 1000,
1068
+ uptime: uptime,
1069
+ usertime: determineInstallUserTime(instance, currTime),
1070
+ device_orientation: getDeviceOrientation(),
1071
+ package: getPackageName(),
1072
+ disp_w: getDeviceWidth(),
1073
+ disp_h: getDeviceHeight(),
1074
+ language: getLanguage(),
1075
+ };
1076
+ if (instance.utm) {
1077
+ returnObj = Object.assign(Object.assign({}, returnObj), { conversion_data: { utm_source: instance.utm } });
1078
+ }
1079
+ if (instance.customValues.length > 0)
1080
+ returnObj.device_ids = {};
1081
+ instance.customValues.forEach((custom) => {
1082
+ const customKey = Object.keys(custom.data)[0];
1083
+ if (instance.kochavaConfig.privacy) {
1084
+ let keyAllowed = false;
1085
+ for (const allowed of instance.kochavaConfig.privacy.allow_custom_ids) {
1086
+ if (customKey === allowed) {
1087
+ keyAllowed = true;
1088
+ }
1089
+ }
1090
+ if (keyAllowed) {
1091
+ if (custom.isDeviceId)
1092
+ returnObj.device_ids = Object.assign(Object.assign({}, returnObj.device_ids), custom.data);
1093
+ else
1094
+ returnObj = Object.assign(Object.assign({}, custom.data), returnObj);
1095
+ }
1096
+ }
1097
+ });
1098
+ // add the persisted identityLinks
1099
+ const persistedIdLinks = getPersistedIdentityLinks();
1100
+ if (persistedIdLinks) {
1101
+ returnObj.identity_link = {};
1102
+ for (const key in persistedIdLinks) {
1103
+ let includeKey = true;
1104
+ for (const denyIdLinkKey of instance.kochavaConfig.privacy.deny_identity_links) {
1105
+ if (denyIdLinkKey === key) {
1106
+ Log.debug(`Denied identity_link ${denyIdLinkKey}, dropping from install.`);
1107
+ includeKey = false;
1108
+ }
1109
+ }
1110
+ if (includeKey)
1111
+ returnObj.identity_link[key] = persistedIdLinks[key];
1112
+ }
1113
+ }
1114
+ return returnObj;
1115
+ };
1116
+ const determineInstallUserTime = (instance, currTime) => {
1117
+ const firstStartStr = readAndUpdatePersistedValue(PersistKey.FirstStartDate, instance.useCookies);
1118
+ if (firstStartStr) {
1119
+ const firstStart = JSON.parse(firstStartStr);
1120
+ // If its been 30 days since the sdk started
1121
+ if ((currTime - firstStart) > 2592000) {
1122
+ return currTime;
1123
+ }
1124
+ return firstStart;
1125
+ }
1126
+ return currTime;
1127
+ };
1128
+
1129
+ /*
1130
+ Authored by Brett Barinaga on 11/17/21.
1131
+ Copyright (c) Kochava, Inc. All rights reserved.
1132
+ */
1133
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
1134
+ if (kind === "a" && !f)
1135
+ throw new TypeError("Private accessor was defined without a getter");
1136
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
1137
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
1138
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1139
+ };
1140
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
1141
+ if (kind === "m")
1142
+ throw new TypeError("Private method is not writable");
1143
+ if (kind === "a" && !f)
1144
+ throw new TypeError("Private accessor was defined without a setter");
1145
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
1146
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
1147
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1148
+ };
1149
+ var _Kochava_instances, _Kochava_instance, _Kochava_jobQueue, _Kochava_resetInstance, _Kochava_initInstance, _Kochava_checkFirstLaunchAndMigrate, _Kochava_checkPersistedKvinit, _Kochava_checkPersistedState, _Kochava_printStartupMsgs, _Kochava_beginStart, _Kochava_performNewKvinit, _Kochava_checkResendId, _Kochava_performInstall;
1150
+ class Kochava {
1151
+ // User will use the below factories instead of directly calling
1152
+ // the constructor
1153
+ constructor() {
1154
+ _Kochava_instances.add(this);
1155
+ _Kochava_instance.set(this, void 0);
1156
+ _Kochava_jobQueue.set(this, void 0);
1157
+ __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_resetInstance).call(this);
1158
+ __classPrivateFieldSet(this, _Kochava_jobQueue, new JobQueue(), "f");
1159
+ }
1160
+ // ============================= PUBLIC =============================== //
1161
+ static create() {
1162
+ return new Kochava();
1163
+ }
1164
+ static createForNode() {
1165
+ const kochava = new Kochava();
1166
+ kochava.executeAdvancedInstruction("wrapper", JSON.stringify({ name: "Node", version: "" }));
1167
+ return kochava;
1168
+ }
1169
+ static createForReact() {
1170
+ const kochava = new Kochava();
1171
+ kochava.executeAdvancedInstruction("wrapper", JSON.stringify({ name: "React", version: "" }));
1172
+ return kochava;
1173
+ }
1174
+ static createForVue() {
1175
+ const kochava = new Kochava();
1176
+ kochava.executeAdvancedInstruction("wrapper", JSON.stringify({ name: "Vue", version: "" }));
1177
+ return kochava;
1178
+ }
1179
+ static createForAngular() {
1180
+ const kochava = new Kochava();
1181
+ kochava.executeAdvancedInstruction("wrapper", JSON.stringify({ name: "Angular", version: "1.0.0" }));
1182
+ return kochava;
1183
+ }
1184
+ /*
1185
+ Set if the SDK should also store persisted values in cookie storage.
1186
+ - Not all values can be persisted in cookies, such as event/idlink queues
1187
+ due to size constraints.
1188
+ - true = yes use cookies
1189
+ - no = no don't use cookies
1190
+ - defaults to false
1191
+ */
1192
+ useCookies(condition = false) {
1193
+ __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies = condition;
1194
+ }
1195
+ /*
1196
+ - Set whether the sdk shouldn't automatically send a page or should.
1197
+ - true = no auto page
1198
+ - false = yes auto page
1199
+ - defaults to false
1200
+ */
1201
+ disableAutoPage(condition = false) {
1202
+ __classPrivateFieldGet(this, _Kochava_instance, "f").disableAutoPage = condition;
1203
+ }
1204
+ /*
1205
+ The primary means for starting the sdk.
1206
+ Responsibilites:
1207
+ - Checks for migrations.
1208
+ - Creates the sdk instance.
1209
+ - Checks for persisted state.
1210
+ - Determines and sends kvinit.
1211
+ - Determines and sends install.
1212
+ - Optionally enqueues an auto_page.
1213
+ - Starts the job queue.
1214
+ */
1215
+ startWithAppGuid(appGuid) {
1216
+ if (!appGuid) {
1217
+ Log.error(`Invalid appGuid ${appGuid}, start failed.`);
1218
+ return;
1219
+ }
1220
+ if (!__classPrivateFieldGet(this, _Kochava_instance, "f"))
1221
+ __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_resetInstance).call(this);
1222
+ if (__classPrivateFieldGet(this, _Kochava_instance, "f").started) {
1223
+ Log.warn("Kochava SDK already started.");
1224
+ return;
1225
+ }
1226
+ Log.diagDebug(`Host called API: Start With App Guid ${appGuid}`);
1227
+ __classPrivateFieldGet(this, _Kochava_instance, "f").started = true;
1228
+ __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_checkFirstLaunchAndMigrate).call(this);
1229
+ __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_initInstance).call(this, appGuid);
1230
+ if (!__classPrivateFieldGet(this, _Kochava_instance, "f").disableAutoPage)
1231
+ this.sendPageEvent();
1232
+ __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_checkPersistedState).call(this);
1233
+ __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_checkPersistedKvinit).call(this);
1234
+ __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_printStartupMsgs).call(this, appGuid);
1235
+ __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_beginStart).call(this);
1236
+ }
1237
+ /*
1238
+ Primary means for stopping the sdk.
1239
+ Will optionally delete all persisted data, and will shutdown the
1240
+ sdk and job queue.
1241
+ */
1242
+ shutdown(deleteData) {
1243
+ Log.diagDebug(`Host called API: Shutdown and ${deleteData ? "delete data" : "keep data"}`);
1244
+ if (deleteData) {
1245
+ Log.debug("Deleting persisted values");
1246
+ deleteAllPersisted();
1247
+ }
1248
+ if (!__classPrivateFieldGet(this, _Kochava_instance, "f").started) {
1249
+ Log.warn("SDK already shutdown.");
1250
+ }
1251
+ Log.info("SDK shutting down.");
1252
+ cancelRetries$1();
1253
+ cancelRetries();
1254
+ __classPrivateFieldGet(this, _Kochava_jobQueue, "f").stop();
1255
+ // wipe whatever was previously in the queue
1256
+ __classPrivateFieldSet(this, _Kochava_jobQueue, new JobQueue(), "f");
1257
+ __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_resetInstance).call(this);
1258
+ }
1259
+ /*
1260
+ Changes the current logLevel.
1261
+ Options include:
1262
+ - Off :: No logging whatsoever
1263
+ - Error :: Only critical errors
1264
+ - Warn :: Only critical errors and non-critical warnings
1265
+ - Info :: High-level sdk behavior logs (default)
1266
+ - Debug :: More in-depth sdk behavior logs and payload logs
1267
+ - Trace :: Everything, granular detail
1268
+ */
1269
+ setLogLevel(logLevel) {
1270
+ Log.diagDebug(`Host called API: Set Log Level ${logLevel}`);
1271
+ Log.setLogLevel(logLevel);
1272
+ }
1273
+ /*
1274
+ Used internally, for special SDK behavior not utilized by a client.
1275
+ Examples include:
1276
+ - urls :: purposefully changing an endpoint for testing
1277
+ - wrapper :: overwriting the version of a wrapper
1278
+ several more ...
1279
+ */
1280
+ executeAdvancedInstruction(key, valueStr, callback) {
1281
+ Log.diagDebug(`Host called API: Execute Advanced Instruction ${key}`);
1282
+ switch (key) {
1283
+ case "wrapper":
1284
+ {
1285
+ const wrapperVersion = JSON.parse(valueStr);
1286
+ if (!__classPrivateFieldGet(this, _Kochava_instance, "f").version)
1287
+ __classPrivateFieldGet(this, _Kochava_instance, "f").version = "WebTracker 3.0.0";
1288
+ switch (wrapperVersion.name) {
1289
+ case "Angular":
1290
+ __classPrivateFieldGet(this, _Kochava_instance, "f").version += ` (${wrapperVersion.name} ${wrapperVersion.version})`;
1291
+ break;
1292
+ default:
1293
+ __classPrivateFieldGet(this, _Kochava_instance, "f").version += ` (${wrapperVersion.name})`;
1294
+ break;
1295
+ }
1296
+ }
1297
+ break;
1298
+ case "urls":
1299
+ {
1300
+ const overrideUrls = JSON.parse(valueStr);
1301
+ if (overrideUrls.init)
1302
+ __classPrivateFieldGet(this, _Kochava_instance, "f").overrideUrls.init = overrideUrls.init;
1303
+ if (overrideUrls.event)
1304
+ __classPrivateFieldGet(this, _Kochava_instance, "f").overrideUrls.event = overrideUrls.event;
1305
+ if (overrideUrls.install)
1306
+ __classPrivateFieldGet(this, _Kochava_instance, "f").overrideUrls.install = overrideUrls.install;
1307
+ if (overrideUrls.identityLink)
1308
+ __classPrivateFieldGet(this, _Kochava_instance, "f").overrideUrls.identityLink = overrideUrls.identityLink;
1309
+ }
1310
+ break;
1311
+ case "urlsRestore":
1312
+ {
1313
+ const restoreUrls = JSON.parse(valueStr);
1314
+ for (const url of restoreUrls) {
1315
+ if (url === "init")
1316
+ __classPrivateFieldGet(this, _Kochava_instance, "f").overrideUrls.init = DEFAULTS.networking.urls.init;
1317
+ if (url === "event")
1318
+ __classPrivateFieldGet(this, _Kochava_instance, "f").overrideUrls.event = DEFAULTS.networking.urls.event;
1319
+ if (url === "install")
1320
+ __classPrivateFieldGet(this, _Kochava_instance, "f").overrideUrls.install =
1321
+ DEFAULTS.networking.urls.install;
1322
+ if (url === "identityLink")
1323
+ __classPrivateFieldGet(this, _Kochava_instance, "f").overrideUrls.identityLink =
1324
+ DEFAULTS.networking.urls.identityLink;
1325
+ }
1326
+ }
1327
+ break;
1328
+ case "logFilter":
1329
+ {
1330
+ const disabled = JSON.parse(valueStr);
1331
+ disabled.forEach((level) => Log.disableLogType(level));
1332
+ }
1333
+ break;
1334
+ case "getInstance":
1335
+ {
1336
+ const currInstance = JSON.stringify(__classPrivateFieldGet(this, _Kochava_instance, "f"));
1337
+ callback(currInstance);
1338
+ Log.debug(`capturing instance: ${valueStr}`);
1339
+ }
1340
+ break;
1341
+ case "logObjects":
1342
+ Log.setLogObjects(JSON.parse(valueStr));
1343
+ break;
1344
+ default:
1345
+ break;
1346
+ }
1347
+ }
1348
+ /*
1349
+ Builds and enqueues a kochava event. Must include an event_name string,
1350
+ with optional event_data as either another string or object.
1351
+ */
1352
+ sendEvent(name, data) {
1353
+ Log.diagDebug(`Host called API: Send Event`);
1354
+ if (!name) {
1355
+ Log.warn("Invalid event name, ignoring call.");
1356
+ return;
1357
+ }
1358
+ __classPrivateFieldGet(this, _Kochava_jobQueue, "f").enqueueEvent(__classPrivateFieldGet(this, _Kochava_instance, "f"), [name, data]);
1359
+ }
1360
+ /*
1361
+ Wraps the sendEvent call with predefined data specific to page events.
1362
+ */
1363
+ sendPageEvent(pageName, additionalData) {
1364
+ if (pageName)
1365
+ this.sendEvent("page", Object.assign({ page_name: pageName }, additionalData));
1366
+ else
1367
+ this.sendEvent("page", Object.assign({ page_name: getPageName() }, additionalData));
1368
+ }
1369
+ /*
1370
+ - Registers new identity links with the sdk, either to be sent out with
1371
+ the install, or standalone.
1372
+ - Will update an identity link if its key already exists in storage.
1373
+ - A max of 10 identity links are currently allowed to be stored
1374
+ at any one time.
1375
+ */
1376
+ registerIdentityLink(name, identifier) {
1377
+ Log.diagDebug(`Host called API: Register Identity Link ${name}`);
1378
+ if (!name || !identifier) {
1379
+ Log.warn("Invalid identity link, ignoring call.");
1380
+ return;
1381
+ }
1382
+ if (checkDuplicateIdLink(name, identifier)) {
1383
+ Log.debug("Duplicate Identity Link found, ignoring.");
1384
+ return;
1385
+ }
1386
+ const idLink = {};
1387
+ idLink[name] = identifier;
1388
+ addPersistedIdLinks(name, identifier, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1389
+ if (__classPrivateFieldGet(this, _Kochava_instance, "f").installStarted || __classPrivateFieldGet(this, _Kochava_instance, "f").installDone) {
1390
+ // it will be sent standalone
1391
+ __classPrivateFieldGet(this, _Kochava_jobQueue, "f").enqueueIdLink(__classPrivateFieldGet(this, _Kochava_instance, "f"), idLink);
1392
+ }
1393
+ // will be sent in install
1394
+ }
1395
+ // Allows the client to attach arbitrary data to certain payloads.
1396
+ registerCustomValue(name, value) {
1397
+ Log.diagDebug(`Host called API: Register Custom Value ${name}`);
1398
+ if (!name || !value) {
1399
+ Log.warn("Invalid custom value, ignoring call.");
1400
+ return;
1401
+ }
1402
+ const dataToAdorn = {};
1403
+ dataToAdorn[name] = value;
1404
+ __classPrivateFieldGet(this, _Kochava_instance, "f").customValues.push({ data: dataToAdorn, isDeviceId: false });
1405
+ }
1406
+ // Allows the client to attach arbitrary identifiers to go out in the install.
1407
+ registerCustomDeviceIdentifier(name, value) {
1408
+ Log.diagDebug(`Host called API: Register Custom Device Identifier ${name}`);
1409
+ if (!name || !value) {
1410
+ Log.warn("Invalid custom device identifier, ignoring call.");
1411
+ return;
1412
+ }
1413
+ const dataToAdorn = {};
1414
+ dataToAdorn[name] = value;
1415
+ __classPrivateFieldGet(this, _Kochava_instance, "f").customValues.push({ data: dataToAdorn, isDeviceId: true });
1416
+ }
1417
+ /*
1418
+ Returns whether or not the sdk is in a "started" state.
1419
+ This basically amounts to if start has been called,
1420
+ not if kvinit is done or the queue is started.
1421
+ Likewise, shutdown will set "started" to false;
1422
+ */
1423
+ getStarted() {
1424
+ return __classPrivateFieldGet(this, _Kochava_instance, "f").started;
1425
+ }
1426
+ /*
1427
+ Returns the current kochavaDeviceId, or "" if called too early.
1428
+ */
1429
+ getDeviceId() {
1430
+ Log.diagDebug(`Host called API: Get Kochava Device Id`);
1431
+ if (__classPrivateFieldGet(this, _Kochava_instance, "f").started)
1432
+ return __classPrivateFieldGet(this, _Kochava_instance, "f").kochavaDeviceId;
1433
+ else
1434
+ return "";
1435
+ }
1436
+ /*
1437
+ Puts the sdk in a "sleep" state. This will stop the sdk from dequeuing
1438
+ new jobs and retrying failed jobs. Different than shutdown, because the
1439
+ current state is not destroyed.
1440
+ */
1441
+ setSleep(sleep) {
1442
+ Log.diagDebug(`Host called API: Sleep ${sleep ? "Stop" : "Start"}`);
1443
+ if (sleep && !__classPrivateFieldGet(this, _Kochava_instance, "f").sleep) {
1444
+ // only pause if it was running
1445
+ __classPrivateFieldGet(this, _Kochava_instance, "f").sleep = sleep;
1446
+ __classPrivateFieldGet(this, _Kochava_jobQueue, "f").pause();
1447
+ }
1448
+ else if (!sleep && __classPrivateFieldGet(this, _Kochava_instance, "f").sleep) {
1449
+ // only resume queueing if it was paused
1450
+ __classPrivateFieldGet(this, _Kochava_instance, "f").sleep = sleep;
1451
+ __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_beginStart).call(this);
1452
+ }
1453
+ }
1454
+ }
1455
+ _Kochava_instance = new WeakMap(), _Kochava_jobQueue = new WeakMap(), _Kochava_instances = new WeakSet(), _Kochava_resetInstance = function _Kochava_resetInstance() {
1456
+ __classPrivateFieldSet(this, _Kochava_instance, {
1457
+ appGuid: "",
1458
+ started: false,
1459
+ installStarted: false,
1460
+ kvinitDone: false,
1461
+ installDone: false,
1462
+ disableAutoPage: false,
1463
+ useCookies: false,
1464
+ sleep: false,
1465
+ version: "",
1466
+ buildDate: "",
1467
+ overrideUrls: {
1468
+ init: "",
1469
+ install: "",
1470
+ event: "",
1471
+ identityLink: "",
1472
+ },
1473
+ customValues: [],
1474
+ kochavaSession: "",
1475
+ retryWaterfall: [],
1476
+ startTimeMS: 0,
1477
+ utm: "",
1478
+ kochavaDeviceId: "",
1479
+ kochavaInstallId: "",
1480
+ kochavaSessionCount: -1,
1481
+ kochavaInstallDate: -1,
1482
+ kochavaConfig: undefined,
1483
+ }, "f");
1484
+ }, _Kochava_initInstance = function _Kochava_initInstance(appGuid) {
1485
+ // init instance with defaults
1486
+ __classPrivateFieldGet(this, _Kochava_instance, "f").appGuid = appGuid;
1487
+ __classPrivateFieldGet(this, _Kochava_instance, "f").disableAutoPage = __classPrivateFieldGet(this, _Kochava_instance, "f").disableAutoPage || false;
1488
+ __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies = __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies || false;
1489
+ __classPrivateFieldGet(this, _Kochava_instance, "f").version = __classPrivateFieldGet(this, _Kochava_instance, "f").version || "WebTracker 3.0.0";
1490
+ __classPrivateFieldGet(this, _Kochava_instance, "f").buildDate = "kbd: 3/31/2022, 11:47:52 AM";
1491
+ __classPrivateFieldGet(this, _Kochava_instance, "f").kochavaSession = uuidv4().substring(0, 5);
1492
+ __classPrivateFieldGet(this, _Kochava_instance, "f").startTimeMS = getCurrTimeMS();
1493
+ __classPrivateFieldGet(this, _Kochava_instance, "f").retryWaterfall = [7, 30, 300, 1800];
1494
+ __classPrivateFieldGet(this, _Kochava_instance, "f").kochavaConfig = JSON.parse(JSON.stringify(DEFAULTS));
1495
+ }, _Kochava_checkFirstLaunchAndMigrate = function _Kochava_checkFirstLaunchAndMigrate() {
1496
+ // If this is our first launch ever, set it in persistence.
1497
+ if (!readAndUpdatePersistedValue(PersistKey.FirstStartDate, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies)) {
1498
+ updatePersistedValue(PersistKey.FirstStartDate, String(getCurrTimeSec()), __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1499
+ /*
1500
+ On a first launch of the v3 sdk, we need to migrate old persisted kv_id
1501
+ from v2.2, v2.3, and v2.5
1502
+ */
1503
+ // perform migration
1504
+ const oldKvId = readAndUpdatePersistedValue(PersistKey.OldKvid, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1505
+ if (oldKvId) {
1506
+ updatePersistedValue(PersistKey.DeviceId, oldKvId, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1507
+ updatePersistedValue(PersistKey.InstallSentDate, JSON.stringify(getCurrTimeSec()), __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1508
+ }
1509
+ }
1510
+ }, _Kochava_checkPersistedKvinit = function _Kochava_checkPersistedKvinit() {
1511
+ // check if persisted kvinit
1512
+ let persistedKvinit = {};
1513
+ const persistedKvinitStr = readAndUpdatePersistedValue(PersistKey.LastKvinit, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1514
+ if (persistedKvinitStr) {
1515
+ persistedKvinit = JSON.parse(persistedKvinitStr);
1516
+ if (persistedKvinit) {
1517
+ // if persisted kvinit, apply it
1518
+ Log.trace("Found persisted kvinit.", persistedKvinit);
1519
+ applyKvinitResp(__classPrivateFieldGet(this, _Kochava_instance, "f"), persistedKvinit);
1520
+ Log.trace("KochavaConfig after persistedKvinit:", JSON.parse(JSON.stringify(__classPrivateFieldGet(this, _Kochava_instance, "f").kochavaConfig)));
1521
+ }
1522
+ }
1523
+ // check refresh minimum too
1524
+ const persistedKvinitDateStr = readAndUpdatePersistedValue(PersistKey.KvinitSentDate, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1525
+ if (persistedKvinitDateStr) {
1526
+ const lastKvinitDate = JSON.parse(persistedKvinitDateStr);
1527
+ if (lastKvinitDate) {
1528
+ const refreshMin = __classPrivateFieldGet(this, _Kochava_instance, "f").kochavaConfig.config.refresh_minimum;
1529
+ if (getCurrTimeSec() - lastKvinitDate < refreshMin)
1530
+ __classPrivateFieldGet(this, _Kochava_instance, "f").kvinitDone = true;
1531
+ }
1532
+ }
1533
+ }, _Kochava_checkPersistedState = function _Kochava_checkPersistedState() {
1534
+ __classPrivateFieldGet(this, _Kochava_instance, "f").installDone =
1535
+ readAndUpdatePersistedValue(PersistKey.InstallSentDate, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies).length > 0;
1536
+ __classPrivateFieldGet(this, _Kochava_instance, "f").kochavaInstallId = readAndUpdatePersistedValue(PersistKey.InstallId, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1537
+ __classPrivateFieldGet(this, _Kochava_instance, "f").kochavaDeviceId = readAndUpdateDeviceId(__classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1538
+ __classPrivateFieldGet(this, _Kochava_instance, "f").kochavaSessionCount = readAndUpdateSessionCount(__classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1539
+ __classPrivateFieldGet(this, _Kochava_instance, "f").utm = readAndUpdateUTM(__classPrivateFieldGet(this, _Kochava_instance, "f").appGuid, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1540
+ }, _Kochava_printStartupMsgs = function _Kochava_printStartupMsgs(appGuid) {
1541
+ Log.diagInfo(`Started SDK ${__classPrivateFieldGet(this, _Kochava_instance, "f").version}
1542
+ published ${__classPrivateFieldGet(this, _Kochava_instance, "f").buildDate}`);
1543
+ Log.diagInfo(`The log level is set to ${Log.getLogLevel()}`);
1544
+ Log.diagDebug(`This ${!__classPrivateFieldGet(this, _Kochava_instance, "f").installDone ? "is" : "is not"} the first tracker SDK launch`);
1545
+ Log.diagDebug(`The kochava device id is ${__classPrivateFieldGet(this, _Kochava_instance, "f").kochavaDeviceId}`);
1546
+ Log.diagDebug(`The kochava app GUID provided was ${appGuid}`);
1547
+ }, _Kochava_beginStart = function _Kochava_beginStart() {
1548
+ return __awaiter(this, void 0, void 0, function* () {
1549
+ // if we need to send a new kvinit, send it
1550
+ if (!__classPrivateFieldGet(this, _Kochava_instance, "f").kvinitDone) {
1551
+ Log.diagDebug(`A new kvinit will be sent`);
1552
+ yield __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_performNewKvinit).call(this);
1553
+ }
1554
+ else {
1555
+ Log.diagDebug(`A new kvinit will not be sent`);
1556
+ }
1557
+ // if the install_id changed and thus a new install must go out
1558
+ if (__classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_checkResendId).call(this))
1559
+ __classPrivateFieldGet(this, _Kochava_instance, "f").installDone = false;
1560
+ Log.diagDebug(`The install ${__classPrivateFieldGet(this, _Kochava_instance, "f").installDone ? "has already" : "has not yet"} been sent`);
1561
+ if (__classPrivateFieldGet(this, _Kochava_instance, "f").sleep)
1562
+ return;
1563
+ if (!__classPrivateFieldGet(this, _Kochava_instance, "f").installDone) {
1564
+ yield __classPrivateFieldGet(this, _Kochava_instances, "m", _Kochava_performInstall).call(this);
1565
+ }
1566
+ if (__classPrivateFieldGet(this, _Kochava_instance, "f").kvinitDone && __classPrivateFieldGet(this, _Kochava_instance, "f").installDone) {
1567
+ yield __classPrivateFieldGet(this, _Kochava_jobQueue, "f").start(__classPrivateFieldGet(this, _Kochava_instance, "f"));
1568
+ }
1569
+ });
1570
+ }, _Kochava_performNewKvinit = function _Kochava_performNewKvinit() {
1571
+ return __awaiter(this, void 0, void 0, function* () {
1572
+ __classPrivateFieldGet(this, _Kochava_instance, "f").kvinitDone = yield send$1(__classPrivateFieldGet(this, _Kochava_instance, "f"), __classPrivateFieldGet(this, _Kochava_instance, "f").retryWaterfall);
1573
+ updatePersistedValue(PersistKey.KvinitSentDate, String(getCurrTimeSec()), __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1574
+ // if new kvinit, apply it
1575
+ let newKvinit = {};
1576
+ const newKvinitStr = readAndUpdatePersistedValue(PersistKey.LastKvinit, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1577
+ if (newKvinitStr) {
1578
+ newKvinit = JSON.parse(newKvinitStr);
1579
+ }
1580
+ applyKvinitResp(__classPrivateFieldGet(this, _Kochava_instance, "f"), newKvinit);
1581
+ Log.trace("KochavaConfig after new Kvinit:", JSON.parse(JSON.stringify(__classPrivateFieldGet(this, _Kochava_instance, "f").kochavaConfig)));
1582
+ });
1583
+ }, _Kochava_checkResendId = function _Kochava_checkResendId() {
1584
+ let resendId = "";
1585
+ if (__classPrivateFieldGet(this, _Kochava_instance, "f").kochavaConfig.install) {
1586
+ resendId = __classPrivateFieldGet(this, _Kochava_instance, "f").kochavaConfig.install.resend_id;
1587
+ }
1588
+ const needsNewInstall = checkInstallIdChange(resendId, __classPrivateFieldGet(this, _Kochava_instance, "f").useCookies);
1589
+ if (needsNewInstall) {
1590
+ Log.debug(`resend_id ${resendId} found, forcing new install`);
1591
+ }
1592
+ return needsNewInstall;
1593
+ }, _Kochava_performInstall = function _Kochava_performInstall() {
1594
+ return __awaiter(this, void 0, void 0, function* () {
1595
+ const request = build(__classPrivateFieldGet(this, _Kochava_instance, "f"));
1596
+ __classPrivateFieldGet(this, _Kochava_instance, "f").installDone = yield send(__classPrivateFieldGet(this, _Kochava_instance, "f"), request);
1597
+ if (!__classPrivateFieldGet(this, _Kochava_instance, "f").installDone)
1598
+ return;
1599
+ // If the install succeeded, remove all idLink that were passed to it
1600
+ onSuccess(__classPrivateFieldGet(this, _Kochava_instance, "f"));
1601
+ updatePersistedValue(PersistKey.IdLinkQueue, JSON.stringify(__classPrivateFieldGet(this, _Kochava_jobQueue, "f").idLinkQueue), false);
1602
+ });
1603
+ };
1604
+ // Only here for generic Web integration
1605
+ window.kochava = Kochava.create();
1606
+
1607
+ class KochavaAngularService {
1608
+ constructor() {
1609
+ this.kochava = Kochava.createForAngular();
1610
+ }
1611
+ }
1612
+ KochavaAngularService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.1", ngImport: i0, type: KochavaAngularService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1613
+ KochavaAngularService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "13.3.1", ngImport: i0, type: KochavaAngularService, providedIn: 'root' });
1614
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.1", ngImport: i0, type: KochavaAngularService, decorators: [{
1615
+ type: Injectable,
1616
+ args: [{
1617
+ providedIn: 'root'
1618
+ }]
1619
+ }], ctorParameters: function () { return []; } });
1620
+
1621
+ class KochavaAngularModule {
1622
+ static forRoot() {
1623
+ return {
1624
+ ngModule: KochavaAngularModule,
1625
+ providers: [KochavaAngularService],
1626
+ };
1627
+ }
1628
+ }
1629
+ KochavaAngularModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "13.3.1", ngImport: i0, type: KochavaAngularModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
1630
+ KochavaAngularModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "13.3.1", ngImport: i0, type: KochavaAngularModule });
1631
+ KochavaAngularModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "13.3.1", ngImport: i0, type: KochavaAngularModule, imports: [[]] });
1632
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "13.3.1", ngImport: i0, type: KochavaAngularModule, decorators: [{
1633
+ type: NgModule,
1634
+ args: [{
1635
+ declarations: [],
1636
+ imports: [],
1637
+ }]
1638
+ }] });
1639
+
1640
+ /*
1641
+ * Public API Surface of kochava-angular
1642
+ */
1643
+
1644
+ /**
1645
+ * Generated bundle index. Do not edit.
1646
+ */
1647
+
1648
+ export { KochavaAngularModule, KochavaAngularService };
1649
+ //# sourceMappingURL=kv-test-ang.mjs.map