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