coveo.analytics 2.28.16 → 2.28.17

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,3141 @@
1
+ /******************************************************************************
2
+ Copyright (c) Microsoft Corporation.
3
+
4
+ Permission to use, copy, modify, and/or distribute this software for any
5
+ purpose with or without fee is hereby granted.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
+ PERFORMANCE OF THIS SOFTWARE.
14
+ ***************************************************************************** */
15
+
16
+ function __rest(s, e) {
17
+ var t = {};
18
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
19
+ t[p] = s[p];
20
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
21
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
22
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
23
+ t[p[i]] = s[p[i]];
24
+ }
25
+ return t;
26
+ }
27
+
28
+ function __awaiter(thisArg, _arguments, P, generator) {
29
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
+ return new (P || (P = Promise))(function (resolve, reject) {
31
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
35
+ });
36
+ }
37
+
38
+ var EventType;
39
+ (function (EventType) {
40
+ EventType["search"] = "search";
41
+ EventType["click"] = "click";
42
+ EventType["custom"] = "custom";
43
+ EventType["view"] = "view";
44
+ EventType["collect"] = "collect";
45
+ })(EventType || (EventType = {}));
46
+
47
+ function hasWindow() {
48
+ return typeof window !== 'undefined';
49
+ }
50
+ function hasNavigator() {
51
+ return typeof navigator !== 'undefined';
52
+ }
53
+ function hasDocument() {
54
+ return typeof document !== 'undefined';
55
+ }
56
+ function hasLocalStorage() {
57
+ try {
58
+ return typeof localStorage !== 'undefined';
59
+ }
60
+ catch (error) {
61
+ return false;
62
+ }
63
+ }
64
+ function hasSessionStorage() {
65
+ try {
66
+ return typeof sessionStorage !== 'undefined';
67
+ }
68
+ catch (error) {
69
+ return false;
70
+ }
71
+ }
72
+ function hasCookieStorage() {
73
+ return hasNavigator() && navigator.cookieEnabled;
74
+ }
75
+
76
+ const eventTypesForDefaultValues = [EventType.click, EventType.custom, EventType.search, EventType.view];
77
+ const addDefaultValues = (eventType, payload) => {
78
+ return eventTypesForDefaultValues.indexOf(eventType) !== -1
79
+ ? Object.assign({ language: hasDocument() ? document.documentElement.lang : 'unknown', userAgent: hasNavigator() ? navigator.userAgent : 'unknown' }, payload) : payload;
80
+ };
81
+
82
+ class Cookie {
83
+ static set(name, value, expire) {
84
+ var domain, expirationDate, domainParts, host;
85
+ if (expire) {
86
+ expirationDate = new Date();
87
+ expirationDate.setTime(expirationDate.getTime() + expire);
88
+ }
89
+ host = window.location.hostname;
90
+ if (host.indexOf('.') === -1) {
91
+ writeCookie(name, value, expirationDate);
92
+ }
93
+ else {
94
+ domainParts = host.split('.');
95
+ domain = domainParts[domainParts.length - 2] + '.' + domainParts[domainParts.length - 1];
96
+ writeCookie(name, value, expirationDate, domain);
97
+ }
98
+ }
99
+ static get(name) {
100
+ var cookiePrefix = name + '=';
101
+ var cookieArray = document.cookie.split(';');
102
+ for (var i = 0; i < cookieArray.length; i++) {
103
+ var cookie = cookieArray[i];
104
+ cookie = cookie.replace(/^\s+/, '');
105
+ if (cookie.lastIndexOf(cookiePrefix, 0) === 0) {
106
+ return cookie.substring(cookiePrefix.length, cookie.length);
107
+ }
108
+ }
109
+ return null;
110
+ }
111
+ static erase(name) {
112
+ Cookie.set(name, '', -1);
113
+ }
114
+ }
115
+ function writeCookie(name, value, expirationDate, domain) {
116
+ document.cookie =
117
+ `${name}=${value}` +
118
+ (expirationDate ? `;expires=${expirationDate.toUTCString()}` : '') +
119
+ (domain ? `;domain=${domain}` : '') +
120
+ ';path=/;SameSite=Lax';
121
+ }
122
+
123
+ function getAvailableStorage() {
124
+ if (hasLocalStorage()) {
125
+ return localStorage;
126
+ }
127
+ if (hasCookieStorage()) {
128
+ return new CookieStorage();
129
+ }
130
+ if (hasSessionStorage()) {
131
+ return sessionStorage;
132
+ }
133
+ return new NullStorage();
134
+ }
135
+ class CookieStorage {
136
+ getItem(key) {
137
+ return Cookie.get(`${CookieStorage.prefix}${key}`);
138
+ }
139
+ removeItem(key) {
140
+ Cookie.erase(`${CookieStorage.prefix}${key}`);
141
+ }
142
+ setItem(key, data, expire) {
143
+ Cookie.set(`${CookieStorage.prefix}${key}`, data, expire);
144
+ }
145
+ }
146
+ CookieStorage.prefix = 'coveo_';
147
+ class CookieAndLocalStorage {
148
+ constructor() {
149
+ this.cookieStorage = new CookieStorage();
150
+ }
151
+ getItem(key) {
152
+ return localStorage.getItem(key) || this.cookieStorage.getItem(key);
153
+ }
154
+ removeItem(key) {
155
+ this.cookieStorage.removeItem(key);
156
+ localStorage.removeItem(key);
157
+ }
158
+ setItem(key, data) {
159
+ localStorage.setItem(key, data);
160
+ this.cookieStorage.setItem(key, data, 31556926000);
161
+ }
162
+ }
163
+ class NullStorage {
164
+ getItem(key) {
165
+ return null;
166
+ }
167
+ removeItem(key) {
168
+ }
169
+ setItem(key, data) {
170
+ }
171
+ }
172
+
173
+ const STORE_KEY = '__coveo.analytics.history';
174
+ const MAX_NUMBER_OF_HISTORY_ELEMENTS = 20;
175
+ const MIN_THRESHOLD_FOR_DUPLICATE_VALUE = 1000 * 60;
176
+ const MAX_VALUE_SIZE = 75;
177
+ class HistoryStore {
178
+ constructor(store) {
179
+ this.store = store || getAvailableStorage();
180
+ }
181
+ addElement(elem) {
182
+ elem.internalTime = new Date().getTime();
183
+ elem = this.cropQueryElement(this.stripEmptyQuery(elem));
184
+ let currentHistory = this.getHistoryWithInternalTime();
185
+ if (currentHistory != null) {
186
+ if (this.isValidEntry(elem)) {
187
+ this.setHistory([elem].concat(currentHistory));
188
+ }
189
+ }
190
+ else {
191
+ this.setHistory([elem]);
192
+ }
193
+ }
194
+ addElementAsync(elem) {
195
+ return __awaiter(this, void 0, void 0, function* () {
196
+ elem.internalTime = new Date().getTime();
197
+ elem = this.cropQueryElement(this.stripEmptyQuery(elem));
198
+ let currentHistory = yield this.getHistoryWithInternalTimeAsync();
199
+ if (currentHistory != null) {
200
+ if (this.isValidEntry(elem)) {
201
+ this.setHistory([elem].concat(currentHistory));
202
+ }
203
+ }
204
+ else {
205
+ this.setHistory([elem]);
206
+ }
207
+ });
208
+ }
209
+ getHistory() {
210
+ const history = this.getHistoryWithInternalTime();
211
+ return this.stripEmptyQueries(this.stripInternalTime(history));
212
+ }
213
+ getHistoryAsync() {
214
+ return __awaiter(this, void 0, void 0, function* () {
215
+ const history = yield this.getHistoryWithInternalTimeAsync();
216
+ return this.stripEmptyQueries(this.stripInternalTime(history));
217
+ });
218
+ }
219
+ getHistoryWithInternalTime() {
220
+ try {
221
+ const elements = this.store.getItem(STORE_KEY);
222
+ if (elements && typeof elements === 'string') {
223
+ return JSON.parse(elements);
224
+ }
225
+ else {
226
+ return [];
227
+ }
228
+ }
229
+ catch (e) {
230
+ return [];
231
+ }
232
+ }
233
+ getHistoryWithInternalTimeAsync() {
234
+ return __awaiter(this, void 0, void 0, function* () {
235
+ try {
236
+ const elements = yield this.store.getItem(STORE_KEY);
237
+ if (elements) {
238
+ return JSON.parse(elements);
239
+ }
240
+ else {
241
+ return [];
242
+ }
243
+ }
244
+ catch (e) {
245
+ return [];
246
+ }
247
+ });
248
+ }
249
+ setHistory(history) {
250
+ try {
251
+ this.store.setItem(STORE_KEY, JSON.stringify(history.slice(0, MAX_NUMBER_OF_HISTORY_ELEMENTS)));
252
+ }
253
+ catch (e) {
254
+ }
255
+ }
256
+ clear() {
257
+ try {
258
+ this.store.removeItem(STORE_KEY);
259
+ }
260
+ catch (e) {
261
+ }
262
+ }
263
+ getMostRecentElement() {
264
+ let currentHistory = this.getHistoryWithInternalTime();
265
+ if (Array.isArray(currentHistory)) {
266
+ const sorted = currentHistory.sort((first, second) => {
267
+ return (second.internalTime || 0) - (first.internalTime || 0);
268
+ });
269
+ return sorted[0];
270
+ }
271
+ return null;
272
+ }
273
+ cropQueryElement(part) {
274
+ if (part.name && part.value && part.name.toLowerCase() === 'query') {
275
+ part.value = part.value.slice(0, MAX_VALUE_SIZE);
276
+ }
277
+ return part;
278
+ }
279
+ isValidEntry(elem) {
280
+ let lastEntry = this.getMostRecentElement();
281
+ if (lastEntry && lastEntry.value == elem.value) {
282
+ return (elem.internalTime || 0) - (lastEntry.internalTime || 0) > MIN_THRESHOLD_FOR_DUPLICATE_VALUE;
283
+ }
284
+ return true;
285
+ }
286
+ stripInternalTime(history) {
287
+ if (Array.isArray(history)) {
288
+ return history.map((part) => {
289
+ const { name, time, value } = part;
290
+ return { name, time, value };
291
+ });
292
+ }
293
+ return [];
294
+ }
295
+ stripEmptyQuery(part) {
296
+ const { name, time, value } = part;
297
+ if (name && typeof value === 'string' && name.toLowerCase() === 'query' && value.trim() === '') {
298
+ return { name, time };
299
+ }
300
+ return part;
301
+ }
302
+ stripEmptyQueries(history) {
303
+ return history.map((part) => this.stripEmptyQuery(part));
304
+ }
305
+ }
306
+
307
+ var history = /*#__PURE__*/Object.freeze({
308
+ __proto__: null,
309
+ HistoryStore: HistoryStore,
310
+ MAX_NUMBER_OF_HISTORY_ELEMENTS: MAX_NUMBER_OF_HISTORY_ELEMENTS,
311
+ MAX_VALUE_SIZE: MAX_VALUE_SIZE,
312
+ MIN_THRESHOLD_FOR_DUPLICATE_VALUE: MIN_THRESHOLD_FOR_DUPLICATE_VALUE,
313
+ STORE_KEY: STORE_KEY,
314
+ default: HistoryStore
315
+ });
316
+
317
+ const enhanceViewEvent = (eventType, payload) => __awaiter(void 0, void 0, void 0, function* () {
318
+ if (eventType === EventType.view) {
319
+ yield addPageViewToHistory(payload.contentIdValue);
320
+ return Object.assign({ location: window.location.toString(), referrer: document.referrer, title: document.title }, payload);
321
+ }
322
+ return payload;
323
+ });
324
+ const addPageViewToHistory = (pageViewValue) => __awaiter(void 0, void 0, void 0, function* () {
325
+ const store = new HistoryStore();
326
+ const historyElement = {
327
+ name: 'PageView',
328
+ value: pageViewValue,
329
+ time: new Date().toISOString(),
330
+ };
331
+ yield store.addElementAsync(historyElement);
332
+ });
333
+
334
+ // Unique ID creation requires a high quality random # generator. In the browser we therefore
335
+ // require the crypto API and do not support built-in fallback to lower quality random number
336
+ // generators (like Math.random()).
337
+ let getRandomValues;
338
+ const rnds8 = new Uint8Array(16);
339
+ function rng() {
340
+ // lazy load so that environments that need to polyfill have a chance to do so
341
+ if (!getRandomValues) {
342
+ // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
343
+ getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
344
+
345
+ if (!getRandomValues) {
346
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
347
+ }
348
+ }
349
+
350
+ return getRandomValues(rnds8);
351
+ }
352
+
353
+ var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
354
+
355
+ function validate(uuid) {
356
+ return typeof uuid === 'string' && REGEX.test(uuid);
357
+ }
358
+
359
+ /**
360
+ * Convert array of 16 byte values to UUID string format of the form:
361
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
362
+ */
363
+
364
+ const byteToHex = [];
365
+
366
+ for (let i = 0; i < 256; ++i) {
367
+ byteToHex.push((i + 0x100).toString(16).slice(1));
368
+ }
369
+
370
+ function unsafeStringify(arr, offset = 0) {
371
+ // Note: Be careful editing this code! It's been tuned for performance
372
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
373
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
374
+ }
375
+
376
+ function parse(uuid) {
377
+ if (!validate(uuid)) {
378
+ throw TypeError('Invalid UUID');
379
+ }
380
+
381
+ let v;
382
+ const arr = new Uint8Array(16); // Parse ########-....-....-....-............
383
+
384
+ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
385
+ arr[1] = v >>> 16 & 0xff;
386
+ arr[2] = v >>> 8 & 0xff;
387
+ arr[3] = v & 0xff; // Parse ........-####-....-....-............
388
+
389
+ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
390
+ arr[5] = v & 0xff; // Parse ........-....-####-....-............
391
+
392
+ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
393
+ arr[7] = v & 0xff; // Parse ........-....-....-####-............
394
+
395
+ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
396
+ arr[9] = v & 0xff; // Parse ........-....-....-....-############
397
+ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
398
+
399
+ arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
400
+ arr[11] = v / 0x100000000 & 0xff;
401
+ arr[12] = v >>> 24 & 0xff;
402
+ arr[13] = v >>> 16 & 0xff;
403
+ arr[14] = v >>> 8 & 0xff;
404
+ arr[15] = v & 0xff;
405
+ return arr;
406
+ }
407
+
408
+ function stringToBytes(str) {
409
+ str = unescape(encodeURIComponent(str)); // UTF8 escape
410
+
411
+ const bytes = [];
412
+
413
+ for (let i = 0; i < str.length; ++i) {
414
+ bytes.push(str.charCodeAt(i));
415
+ }
416
+
417
+ return bytes;
418
+ }
419
+
420
+ const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
421
+ const URL$1 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
422
+ function v35(name, version, hashfunc) {
423
+ function generateUUID(value, namespace, buf, offset) {
424
+ var _namespace;
425
+
426
+ if (typeof value === 'string') {
427
+ value = stringToBytes(value);
428
+ }
429
+
430
+ if (typeof namespace === 'string') {
431
+ namespace = parse(namespace);
432
+ }
433
+
434
+ if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
435
+ throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
436
+ } // Compute hash of namespace and value, Per 4.3
437
+ // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
438
+ // hashfunc([...namespace, ... value])`
439
+
440
+
441
+ let bytes = new Uint8Array(16 + value.length);
442
+ bytes.set(namespace);
443
+ bytes.set(value, namespace.length);
444
+ bytes = hashfunc(bytes);
445
+ bytes[6] = bytes[6] & 0x0f | version;
446
+ bytes[8] = bytes[8] & 0x3f | 0x80;
447
+
448
+ if (buf) {
449
+ offset = offset || 0;
450
+
451
+ for (let i = 0; i < 16; ++i) {
452
+ buf[offset + i] = bytes[i];
453
+ }
454
+
455
+ return buf;
456
+ }
457
+
458
+ return unsafeStringify(bytes);
459
+ } // Function#name is not settable on some platforms (#270)
460
+
461
+
462
+ try {
463
+ generateUUID.name = name; // eslint-disable-next-line no-empty
464
+ } catch (err) {} // For CommonJS default export support
465
+
466
+
467
+ generateUUID.DNS = DNS;
468
+ generateUUID.URL = URL$1;
469
+ return generateUUID;
470
+ }
471
+
472
+ const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
473
+ var native = {
474
+ randomUUID
475
+ };
476
+
477
+ function v4(options, buf, offset) {
478
+ if (native.randomUUID && !buf && !options) {
479
+ return native.randomUUID();
480
+ }
481
+
482
+ options = options || {};
483
+ const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
484
+
485
+ rnds[6] = rnds[6] & 0x0f | 0x40;
486
+ rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
487
+
488
+ if (buf) {
489
+ offset = offset || 0;
490
+
491
+ for (let i = 0; i < 16; ++i) {
492
+ buf[offset + i] = rnds[i];
493
+ }
494
+
495
+ return buf;
496
+ }
497
+
498
+ return unsafeStringify(rnds);
499
+ }
500
+
501
+ // Adapted from Chris Veness' SHA1 code at
502
+ // http://www.movable-type.co.uk/scripts/sha1.html
503
+ function f(s, x, y, z) {
504
+ switch (s) {
505
+ case 0:
506
+ return x & y ^ ~x & z;
507
+
508
+ case 1:
509
+ return x ^ y ^ z;
510
+
511
+ case 2:
512
+ return x & y ^ x & z ^ y & z;
513
+
514
+ case 3:
515
+ return x ^ y ^ z;
516
+ }
517
+ }
518
+
519
+ function ROTL(x, n) {
520
+ return x << n | x >>> 32 - n;
521
+ }
522
+
523
+ function sha1(bytes) {
524
+ const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
525
+ const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
526
+
527
+ if (typeof bytes === 'string') {
528
+ const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
529
+
530
+ bytes = [];
531
+
532
+ for (let i = 0; i < msg.length; ++i) {
533
+ bytes.push(msg.charCodeAt(i));
534
+ }
535
+ } else if (!Array.isArray(bytes)) {
536
+ // Convert Array-like to Array
537
+ bytes = Array.prototype.slice.call(bytes);
538
+ }
539
+
540
+ bytes.push(0x80);
541
+ const l = bytes.length / 4 + 2;
542
+ const N = Math.ceil(l / 16);
543
+ const M = new Array(N);
544
+
545
+ for (let i = 0; i < N; ++i) {
546
+ const arr = new Uint32Array(16);
547
+
548
+ for (let j = 0; j < 16; ++j) {
549
+ arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];
550
+ }
551
+
552
+ M[i] = arr;
553
+ }
554
+
555
+ M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
556
+ M[N - 1][14] = Math.floor(M[N - 1][14]);
557
+ M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
558
+
559
+ for (let i = 0; i < N; ++i) {
560
+ const W = new Uint32Array(80);
561
+
562
+ for (let t = 0; t < 16; ++t) {
563
+ W[t] = M[i][t];
564
+ }
565
+
566
+ for (let t = 16; t < 80; ++t) {
567
+ W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
568
+ }
569
+
570
+ let a = H[0];
571
+ let b = H[1];
572
+ let c = H[2];
573
+ let d = H[3];
574
+ let e = H[4];
575
+
576
+ for (let t = 0; t < 80; ++t) {
577
+ const s = Math.floor(t / 20);
578
+ const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
579
+ e = d;
580
+ d = c;
581
+ c = ROTL(b, 30) >>> 0;
582
+ b = a;
583
+ a = T;
584
+ }
585
+
586
+ H[0] = H[0] + a >>> 0;
587
+ H[1] = H[1] + b >>> 0;
588
+ H[2] = H[2] + c >>> 0;
589
+ H[3] = H[3] + d >>> 0;
590
+ H[4] = H[4] + e >>> 0;
591
+ }
592
+
593
+ return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
594
+ }
595
+
596
+ const v5 = v35('v5', 0x50, sha1);
597
+ var uuidv5 = v5;
598
+
599
+ const libVersion = "2.28.17" ;
600
+
601
+ const getFormattedLocation = (location) => `${location.protocol}//${location.hostname}${location.pathname.indexOf('/') === 0 ? location.pathname : `/${location.pathname}`}${location.search}`;
602
+
603
+ const BasePluginEventTypes = {
604
+ pageview: 'pageview',
605
+ event: 'event',
606
+ };
607
+ class Plugin {
608
+ constructor({ client, uuidGenerator = v4 }) {
609
+ this.client = client;
610
+ this.uuidGenerator = uuidGenerator;
611
+ }
612
+ }
613
+ class BasePlugin extends Plugin {
614
+ constructor({ client, uuidGenerator = v4 }) {
615
+ super({ client, uuidGenerator });
616
+ this.actionData = {};
617
+ this.pageViewId = uuidGenerator();
618
+ this.nextPageViewId = this.pageViewId;
619
+ this.currentLocation = getFormattedLocation(window.location);
620
+ this.lastReferrer = hasDocument() ? document.referrer : '';
621
+ this.addHooks();
622
+ }
623
+ getApi(name) {
624
+ switch (name) {
625
+ case 'setAction':
626
+ return this.setAction;
627
+ default:
628
+ return null;
629
+ }
630
+ }
631
+ setAction(action, options) {
632
+ this.action = action;
633
+ this.actionData = options;
634
+ }
635
+ clearData() {
636
+ this.clearPluginData();
637
+ this.action = undefined;
638
+ this.actionData = {};
639
+ }
640
+ getLocationInformation(eventType, payload) {
641
+ return Object.assign({ hitType: eventType }, this.getNextValues(eventType, payload));
642
+ }
643
+ updateLocationInformation(eventType, payload) {
644
+ this.updateLocationForNextPageView(eventType, payload);
645
+ }
646
+ getDefaultContextInformation(eventType) {
647
+ const documentContext = {
648
+ title: hasDocument() ? document.title : '',
649
+ encoding: hasDocument() ? document.characterSet : 'UTF-8',
650
+ };
651
+ const screenContext = {
652
+ screenResolution: `${screen.width}x${screen.height}`,
653
+ screenColor: `${screen.colorDepth}-bit`,
654
+ };
655
+ const navigatorContext = {
656
+ language: navigator.language,
657
+ userAgent: navigator.userAgent,
658
+ };
659
+ const eventContext = {
660
+ time: Date.now(),
661
+ eventId: this.uuidGenerator(),
662
+ };
663
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, eventContext), screenContext), navigatorContext), documentContext);
664
+ }
665
+ updateLocationForNextPageView(eventType, payload) {
666
+ const { pageViewId, referrer, location } = this.getNextValues(eventType, payload);
667
+ this.lastReferrer = referrer;
668
+ this.pageViewId = pageViewId;
669
+ this.currentLocation = location;
670
+ if (eventType === BasePluginEventTypes.pageview) {
671
+ this.nextPageViewId = this.uuidGenerator();
672
+ this.hasSentFirstPageView = true;
673
+ }
674
+ }
675
+ getNextValues(eventType, payload) {
676
+ return {
677
+ pageViewId: eventType === BasePluginEventTypes.pageview ? this.nextPageViewId : this.pageViewId,
678
+ referrer: eventType === BasePluginEventTypes.pageview && this.hasSentFirstPageView
679
+ ? this.currentLocation
680
+ : this.lastReferrer,
681
+ location: eventType === BasePluginEventTypes.pageview
682
+ ? this.getCurrentLocationFromPayload(payload)
683
+ : this.currentLocation,
684
+ };
685
+ }
686
+ getCurrentLocationFromPayload(payload) {
687
+ if (!!payload.page) {
688
+ const removeStartingSlash = (page) => page.replace(/^\/?(.*)$/, '/$1');
689
+ const extractHostnamePart = (location) => location.split('/').slice(0, 3).join('/');
690
+ return `${extractHostnamePart(this.currentLocation)}${removeStartingSlash(payload.page)}`;
691
+ }
692
+ else {
693
+ return getFormattedLocation(window.location);
694
+ }
695
+ }
696
+ }
697
+
698
+ class CoveoLinkParam {
699
+ constructor(clientId, timestamp) {
700
+ if (!validate(clientId))
701
+ throw Error('Not a valid uuid');
702
+ this.clientId = clientId;
703
+ this.creationDate = Math.floor(timestamp / 1000);
704
+ }
705
+ toString() {
706
+ return this.clientId.replace(/-/g, '') + '.' + this.creationDate.toString();
707
+ }
708
+ get expired() {
709
+ const age = Math.floor(Date.now() / 1000) - this.creationDate;
710
+ return age < 0 || age > CoveoLinkParam.expirationTime;
711
+ }
712
+ validate(referrerString, referrerList) {
713
+ return !this.expired && this.matchReferrer(referrerString, referrerList);
714
+ }
715
+ matchReferrer(referrerString, referrerList) {
716
+ try {
717
+ const url = new URL(referrerString);
718
+ return referrerList.some((value) => {
719
+ const hostRegExp = new RegExp(value.replace(/\\/g, '\\\\').replace(/\./g, '\\.').replace(/\*/g, '.*') + '$');
720
+ return hostRegExp.test(url.host);
721
+ });
722
+ }
723
+ catch (error) {
724
+ return false;
725
+ }
726
+ }
727
+ static fromString(input) {
728
+ const parts = input.split('.');
729
+ if (parts.length !== 2) {
730
+ return null;
731
+ }
732
+ const [clientIdPart, creationDate] = parts;
733
+ if (clientIdPart.length !== 32 || isNaN(parseInt(creationDate))) {
734
+ return null;
735
+ }
736
+ const clientId = clientIdPart.substring(0, 8) +
737
+ '-' +
738
+ clientIdPart.substring(8, 12) +
739
+ '-' +
740
+ clientIdPart.substring(12, 16) +
741
+ '-' +
742
+ clientIdPart.substring(16, 20) +
743
+ '-' +
744
+ clientIdPart.substring(20, 32);
745
+ if (validate(clientId)) {
746
+ return new CoveoLinkParam(clientId, Number.parseInt(creationDate) * 1000);
747
+ }
748
+ else {
749
+ return null;
750
+ }
751
+ }
752
+ }
753
+ CoveoLinkParam.cvo_cid = 'cvo_cid';
754
+ CoveoLinkParam.expirationTime = 120;
755
+ class LinkPlugin extends Plugin {
756
+ constructor({ client, uuidGenerator = v4 }) {
757
+ super({ client, uuidGenerator });
758
+ }
759
+ getApi(name) {
760
+ switch (name) {
761
+ case 'decorate':
762
+ return this.decorate;
763
+ case 'acceptFrom':
764
+ return this.acceptFrom;
765
+ default:
766
+ return null;
767
+ }
768
+ }
769
+ decorate(urlString) {
770
+ return __awaiter(this, void 0, void 0, function* () {
771
+ if (!this.client.getCurrentVisitorId) {
772
+ throw new Error('Could not retrieve current clientId');
773
+ }
774
+ try {
775
+ const url = new URL(urlString);
776
+ const clientId = yield this.client.getCurrentVisitorId();
777
+ url.searchParams.set(CoveoLinkParam.cvo_cid, new CoveoLinkParam(clientId, Date.now()).toString());
778
+ return url.toString();
779
+ }
780
+ catch (error) {
781
+ throw new Error('Invalid URL provided');
782
+ }
783
+ });
784
+ }
785
+ acceptFrom(acceptedReferrers) {
786
+ this.client.setAcceptedLinkReferrers(acceptedReferrers);
787
+ }
788
+ }
789
+ LinkPlugin.Id = 'link';
790
+
791
+ const keysOf = Object.keys;
792
+ function isObject(o) {
793
+ return o !== null && typeof o === 'object' && !Array.isArray(o);
794
+ }
795
+
796
+ const ticketKeysMapping = {
797
+ id: 'svc_ticket_id',
798
+ subject: 'svc_ticket_subject',
799
+ description: 'svc_ticket_description',
800
+ category: 'svc_ticket_category',
801
+ productId: 'svc_ticket_product_id',
802
+ custom: 'svc_ticket_custom',
803
+ };
804
+ const ticketKeysMappingValues = keysOf(ticketKeysMapping).map((key) => ticketKeysMapping[key]);
805
+ const ticketSubKeysMatchGroup = [...ticketKeysMappingValues].join('|');
806
+ const ticketKeyRegex = new RegExp(`^(${ticketSubKeysMatchGroup}$)`);
807
+ const serviceActionsKeysMapping = {
808
+ svcAction: 'svc_action',
809
+ svcActionData: 'svc_action_data',
810
+ };
811
+ const convertTicketToMeasurementProtocol = (ticket) => {
812
+ return keysOf(ticket)
813
+ .filter((key) => ticket[key] !== undefined)
814
+ .reduce((mappedTicket, key) => {
815
+ const newKey = ticketKeysMapping[key] || key;
816
+ return Object.assign(Object.assign({}, mappedTicket), { [newKey]: ticket[key] });
817
+ }, {});
818
+ };
819
+ const isTicketKey = (key) => ticketKeyRegex.test(key);
820
+ const isServiceKey = [isTicketKey];
821
+
822
+ const productKeysMapping = {
823
+ id: 'id',
824
+ name: 'nm',
825
+ brand: 'br',
826
+ category: 'ca',
827
+ variant: 'va',
828
+ price: 'pr',
829
+ quantity: 'qt',
830
+ coupon: 'cc',
831
+ position: 'ps',
832
+ group: 'group',
833
+ };
834
+ const impressionKeysMapping = {
835
+ id: 'id',
836
+ name: 'nm',
837
+ brand: 'br',
838
+ category: 'ca',
839
+ variant: 'va',
840
+ position: 'ps',
841
+ price: 'pr',
842
+ group: 'group',
843
+ };
844
+ const productActionsKeysMapping = {
845
+ action: 'pa',
846
+ list: 'pal',
847
+ listSource: 'pls',
848
+ };
849
+ const transactionActionsKeysMapping = {
850
+ id: 'ti',
851
+ revenue: 'tr',
852
+ tax: 'tt',
853
+ shipping: 'ts',
854
+ coupon: 'tcc',
855
+ affiliation: 'ta',
856
+ step: 'cos',
857
+ option: 'col',
858
+ };
859
+ const coveoCommerceExtensionKeys = [
860
+ 'loyaltyCardId',
861
+ 'loyaltyTier',
862
+ 'thirdPartyPersona',
863
+ 'companyName',
864
+ 'favoriteStore',
865
+ 'storeName',
866
+ 'userIndustry',
867
+ 'userRole',
868
+ 'userDepartment',
869
+ 'businessUnit',
870
+ ];
871
+ const quoteActionsKeysMapping = {
872
+ id: 'quoteId',
873
+ affiliation: 'quoteAffiliation',
874
+ };
875
+ const reviewActionsKeysMapping = {
876
+ id: 'reviewId',
877
+ rating: 'reviewRating',
878
+ comment: 'reviewComment',
879
+ };
880
+ const commerceActionKeysMappingPerAction = {
881
+ add: productActionsKeysMapping,
882
+ bookmark_add: productActionsKeysMapping,
883
+ bookmark_remove: productActionsKeysMapping,
884
+ click: productActionsKeysMapping,
885
+ checkout: productActionsKeysMapping,
886
+ checkout_option: productActionsKeysMapping,
887
+ detail: productActionsKeysMapping,
888
+ impression: productActionsKeysMapping,
889
+ remove: productActionsKeysMapping,
890
+ refund: Object.assign(Object.assign({}, productActionsKeysMapping), transactionActionsKeysMapping),
891
+ purchase: Object.assign(Object.assign({}, productActionsKeysMapping), transactionActionsKeysMapping),
892
+ quickview: productActionsKeysMapping,
893
+ quote: Object.assign(Object.assign({}, productActionsKeysMapping), quoteActionsKeysMapping),
894
+ review: Object.assign(Object.assign({}, productActionsKeysMapping), reviewActionsKeysMapping),
895
+ };
896
+ const productKeysMappingValues = keysOf(productKeysMapping).map((key) => productKeysMapping[key]);
897
+ const impressionKeysMappingValues = keysOf(impressionKeysMapping).map((key) => impressionKeysMapping[key]);
898
+ const productActionsKeysMappingValues = keysOf(productActionsKeysMapping).map((key) => productActionsKeysMapping[key]);
899
+ const transactionActionsKeysMappingValues = keysOf(transactionActionsKeysMapping).map((key) => transactionActionsKeysMapping[key]);
900
+ const reviewKeysMappingValues = keysOf(reviewActionsKeysMapping).map((key) => reviewActionsKeysMapping[key]);
901
+ const quoteKeysMappingValues = keysOf(quoteActionsKeysMapping).map((key) => quoteActionsKeysMapping[key]);
902
+ const productSubKeysMatchGroup = [...productKeysMappingValues, 'custom'].join('|');
903
+ const impressionSubKeysMatchGroup = [...impressionKeysMappingValues, 'custom'].join('|');
904
+ const productPrefixMatchGroup = '(pr[0-9]+)';
905
+ const impressionPrefixMatchGroup = '(il[0-9]+pi[0-9]+)';
906
+ const productKeyRegex = new RegExp(`^${productPrefixMatchGroup}(${productSubKeysMatchGroup})$`);
907
+ const impressionKeyRegex = new RegExp(`^(${impressionPrefixMatchGroup}(${impressionSubKeysMatchGroup}))|(il[0-9]+nm)$`);
908
+ const productActionsKeyRegex = new RegExp(`^(${productActionsKeysMappingValues.join('|')})$`);
909
+ const transactionActionsKeyRegex = new RegExp(`^(${transactionActionsKeysMappingValues.join('|')})$`);
910
+ const customProductKeyRegex = new RegExp(`^${productPrefixMatchGroup}custom$`);
911
+ const customImpressionKeyRegex = new RegExp(`^${impressionPrefixMatchGroup}custom$`);
912
+ const coveoCommerceExtensionKeysRegex = new RegExp(`^(${[...coveoCommerceExtensionKeys, ...reviewKeysMappingValues, ...quoteKeysMappingValues].join('|')})$`);
913
+ const isProductKey = (key) => productKeyRegex.test(key);
914
+ const isImpressionKey = (key) => impressionKeyRegex.test(key);
915
+ const isProductActionsKey = (key) => productActionsKeyRegex.test(key);
916
+ const isTransactionActionsKeyRegex = (key) => transactionActionsKeyRegex.test(key);
917
+ const isCoveoCommerceExtensionKey = (key) => coveoCommerceExtensionKeysRegex.test(key);
918
+ const isCommerceKey = [
919
+ isImpressionKey,
920
+ isProductKey,
921
+ isProductActionsKey,
922
+ isTransactionActionsKeyRegex,
923
+ isCoveoCommerceExtensionKey,
924
+ ];
925
+ const isCustomCommerceKey = [customProductKeyRegex, customImpressionKeyRegex];
926
+
927
+ const globalParamKeysMapping = {
928
+ anonymizeIp: 'aip',
929
+ };
930
+ const eventKeysMapping = {
931
+ eventCategory: 'ec',
932
+ eventAction: 'ea',
933
+ eventLabel: 'el',
934
+ eventValue: 'ev',
935
+ page: 'dp',
936
+ visitorId: 'cid',
937
+ clientId: 'cid',
938
+ userId: 'uid',
939
+ currencyCode: 'cu',
940
+ };
941
+ const contextInformationMapping = {
942
+ hitType: 't',
943
+ pageViewId: 'pid',
944
+ encoding: 'de',
945
+ location: 'dl',
946
+ referrer: 'dr',
947
+ screenColor: 'sd',
948
+ screenResolution: 'sr',
949
+ title: 'dt',
950
+ userAgent: 'ua',
951
+ language: 'ul',
952
+ eventId: 'z',
953
+ time: 'tm',
954
+ };
955
+ const coveoExtensionsKeys = [
956
+ 'contentId',
957
+ 'contentIdKey',
958
+ 'contentType',
959
+ 'searchHub',
960
+ 'tab',
961
+ 'searchUid',
962
+ 'permanentId',
963
+ 'contentLocale',
964
+ 'trackingId',
965
+ ];
966
+ const baseMeasurementProtocolKeysMapping = Object.assign(Object.assign(Object.assign(Object.assign({}, globalParamKeysMapping), eventKeysMapping), contextInformationMapping), coveoExtensionsKeys.reduce((all, key) => (Object.assign(Object.assign({}, all), { [key]: key })), {}));
967
+
968
+ const measurementProtocolKeysMapping = Object.assign(Object.assign({}, baseMeasurementProtocolKeysMapping), serviceActionsKeysMapping);
969
+ const convertKeysToMeasurementProtocol = (params) => {
970
+ const keysMappingForAction = (!!params.action && commerceActionKeysMappingPerAction[params.action]) || {};
971
+ return keysOf(params).reduce((mappedKeys, key) => {
972
+ const newKey = keysMappingForAction[key] || measurementProtocolKeysMapping[key] || key;
973
+ return Object.assign(Object.assign({}, mappedKeys), { [newKey]: params[key] });
974
+ }, {});
975
+ };
976
+ const measurementProtocolKeysMappingValues = keysOf(measurementProtocolKeysMapping).map((key) => measurementProtocolKeysMapping[key]);
977
+ const isKnownMeasurementProtocolKey = (key) => measurementProtocolKeysMappingValues.indexOf(key) !== -1;
978
+ const isCustomKey = (key) => key === 'custom';
979
+ const isMeasurementProtocolKey = (key) => {
980
+ return [...isCommerceKey, ...isServiceKey, isKnownMeasurementProtocolKey, isCustomKey].some((test) => test(key));
981
+ };
982
+ const convertCustomMeasurementProtocolKeys = (data) => {
983
+ return keysOf(data).reduce((all, current) => {
984
+ const match = getFirstCustomMeasurementProtocolKeyMatch(current);
985
+ if (match) {
986
+ return Object.assign(Object.assign({}, all), convertCustomObject(match, data[current]));
987
+ }
988
+ else {
989
+ return Object.assign(Object.assign({}, all), { [current]: data[current] });
990
+ }
991
+ }, {});
992
+ };
993
+ const getFirstCustomMeasurementProtocolKeyMatch = (key) => {
994
+ let matchedKey = undefined;
995
+ [...isCustomCommerceKey].every((regex) => {
996
+ var _a;
997
+ matchedKey = (_a = regex.exec(key)) === null || _a === void 0 ? void 0 : _a[1];
998
+ return !Boolean(matchedKey);
999
+ });
1000
+ return matchedKey;
1001
+ };
1002
+ const convertCustomObject = (prefix, customData) => {
1003
+ return keysOf(customData).reduce((allCustom, currentCustomKey) => (Object.assign(Object.assign({}, allCustom), { [`${prefix}${currentCustomKey}`]: customData[currentCustomKey] })), {});
1004
+ };
1005
+
1006
+ class AnalyticsBeaconClient {
1007
+ constructor(opts) {
1008
+ this.opts = opts;
1009
+ }
1010
+ sendEvent(eventType, originalPayload) {
1011
+ return __awaiter(this, void 0, void 0, function* () {
1012
+ if (!this.isAvailable()) {
1013
+ throw new Error(`navigator.sendBeacon is not supported in this browser. Consider adding a polyfill like "sendbeacon-polyfill".`);
1014
+ }
1015
+ const { baseUrl, preprocessRequest } = this.opts;
1016
+ const paramsFragments = yield this.getQueryParamsForEventType(eventType);
1017
+ const { url, payload } = yield this.preProcessRequestAsPotentialJSONString(`${baseUrl}/analytics/${eventType}?${paramsFragments}`, originalPayload, preprocessRequest);
1018
+ const parsedRequestData = this.encodeForEventType(eventType, payload);
1019
+ const body = new Blob([parsedRequestData], {
1020
+ type: 'application/x-www-form-urlencoded',
1021
+ });
1022
+ navigator.sendBeacon(url, body);
1023
+ return;
1024
+ });
1025
+ }
1026
+ isAvailable() {
1027
+ return 'sendBeacon' in navigator;
1028
+ }
1029
+ deleteHttpCookieVisitorId() {
1030
+ return Promise.resolve();
1031
+ }
1032
+ preProcessRequestAsPotentialJSONString(originalURL, originalPayload, preprocessRequest) {
1033
+ return __awaiter(this, void 0, void 0, function* () {
1034
+ let returnedUrl = originalURL;
1035
+ let returnedPayload = originalPayload;
1036
+ if (preprocessRequest) {
1037
+ const processedRequest = yield preprocessRequest({ url: originalURL, body: JSON.stringify(originalPayload) }, 'analyticsBeacon');
1038
+ const { url: processedURL, body: processedBody } = processedRequest;
1039
+ returnedUrl = processedURL || originalURL;
1040
+ try {
1041
+ returnedPayload = JSON.parse(processedBody);
1042
+ }
1043
+ catch (e) {
1044
+ console.error('Unable to process the request body as a JSON string', e);
1045
+ }
1046
+ }
1047
+ return {
1048
+ payload: returnedPayload,
1049
+ url: returnedUrl,
1050
+ };
1051
+ });
1052
+ }
1053
+ encodeForEventType(eventType, payload) {
1054
+ return this.isEventTypeLegacy(eventType)
1055
+ ? this.encodeForLegacyType(eventType, payload)
1056
+ : this.encodeForFormUrlEncoded(Object.assign({ access_token: this.opts.token }, payload));
1057
+ }
1058
+ getQueryParamsForEventType(eventType) {
1059
+ return __awaiter(this, void 0, void 0, function* () {
1060
+ const { token, visitorIdProvider } = this.opts;
1061
+ const visitorId = yield visitorIdProvider.getCurrentVisitorId();
1062
+ return [
1063
+ token && this.isEventTypeLegacy(eventType) ? `access_token=${token}` : '',
1064
+ visitorId ? `visitorId=${visitorId}` : '',
1065
+ 'discardVisitInfo=true',
1066
+ ]
1067
+ .filter((p) => !!p)
1068
+ .join('&');
1069
+ });
1070
+ }
1071
+ isEventTypeLegacy(eventType) {
1072
+ return [EventType.click, EventType.custom, EventType.search, EventType.view].indexOf(eventType) !== -1;
1073
+ }
1074
+ encodeForLegacyType(eventType, payload) {
1075
+ return `${eventType}Event=${encodeURIComponent(JSON.stringify(payload))}`;
1076
+ }
1077
+ encodeForFormUrlEncoded(payload) {
1078
+ return Object.keys(payload)
1079
+ .filter((key) => !!payload[key])
1080
+ .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(this.encodeValue(payload[key]))}`)
1081
+ .join('&');
1082
+ }
1083
+ encodeValue(value) {
1084
+ return typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean'
1085
+ ? value
1086
+ : JSON.stringify(value);
1087
+ }
1088
+ }
1089
+
1090
+ class NoopAnalyticsClient {
1091
+ sendEvent(_, __) {
1092
+ return __awaiter(this, void 0, void 0, function* () {
1093
+ return Promise.resolve();
1094
+ });
1095
+ }
1096
+ deleteHttpCookieVisitorId() {
1097
+ return __awaiter(this, void 0, void 0, function* () {
1098
+ return Promise.resolve();
1099
+ });
1100
+ }
1101
+ }
1102
+
1103
+ const fetch$1 = window.fetch;
1104
+
1105
+ class AnalyticsFetchClient {
1106
+ constructor(opts) {
1107
+ this.opts = opts;
1108
+ }
1109
+ sendEvent(eventType, payload) {
1110
+ return __awaiter(this, void 0, void 0, function* () {
1111
+ const { baseUrl, visitorIdProvider, preprocessRequest } = this.opts;
1112
+ const visitorIdParam = this.shouldAppendVisitorId(eventType) ? yield this.getVisitorIdParam() : '';
1113
+ const defaultOptions = {
1114
+ url: `${baseUrl}/analytics/${eventType}${visitorIdParam}`,
1115
+ credentials: 'include',
1116
+ mode: 'cors',
1117
+ headers: this.getHeaders(),
1118
+ method: 'POST',
1119
+ body: JSON.stringify(payload),
1120
+ };
1121
+ const _a = Object.assign(Object.assign({}, defaultOptions), (preprocessRequest ? yield preprocessRequest(defaultOptions, 'analyticsFetch') : {})), { url } = _a, fetchData = __rest(_a, ["url"]);
1122
+ const response = yield fetch$1(url, fetchData);
1123
+ if (response.ok) {
1124
+ const visit = (yield response.json());
1125
+ if (visit.visitorId) {
1126
+ visitorIdProvider.setCurrentVisitorId(visit.visitorId);
1127
+ }
1128
+ return visit;
1129
+ }
1130
+ else {
1131
+ try {
1132
+ response.json();
1133
+ }
1134
+ catch (_b) {
1135
+ }
1136
+ console.error(`An error has occured when sending the "${eventType}" event.`, response, payload);
1137
+ throw new Error(`An error has occurred when sending the "${eventType}" event. Check the console logs for more details.`);
1138
+ }
1139
+ });
1140
+ }
1141
+ deleteHttpCookieVisitorId() {
1142
+ return __awaiter(this, void 0, void 0, function* () {
1143
+ const { baseUrl } = this.opts;
1144
+ const url = `${baseUrl}/analytics/visit`;
1145
+ yield fetch$1(url, { headers: this.getHeaders(), method: 'DELETE' });
1146
+ });
1147
+ }
1148
+ shouldAppendVisitorId(eventType) {
1149
+ return [EventType.click, EventType.custom, EventType.search, EventType.view].indexOf(eventType) !== -1;
1150
+ }
1151
+ getVisitorIdParam() {
1152
+ return __awaiter(this, void 0, void 0, function* () {
1153
+ const { visitorIdProvider } = this.opts;
1154
+ const visitorId = yield visitorIdProvider.getCurrentVisitorId();
1155
+ return visitorId ? `?visitor=${visitorId}` : '';
1156
+ });
1157
+ }
1158
+ getHeaders() {
1159
+ const { token } = this.opts;
1160
+ return Object.assign(Object.assign({}, (token ? { Authorization: `Bearer ${token}` } : {})), { 'Content-Type': `application/json` });
1161
+ }
1162
+ }
1163
+
1164
+ class BrowserRuntime {
1165
+ constructor(clientOptions, getUnprocessedRequests) {
1166
+ if (hasLocalStorage() && hasCookieStorage()) {
1167
+ this.storage = new CookieAndLocalStorage();
1168
+ }
1169
+ else if (hasLocalStorage()) {
1170
+ this.storage = localStorage;
1171
+ }
1172
+ else {
1173
+ console.warn('BrowserRuntime detected no valid storage available.', this);
1174
+ this.storage = new NullStorage();
1175
+ }
1176
+ this.client = new AnalyticsFetchClient(clientOptions);
1177
+ this.beaconClient = new AnalyticsBeaconClient(clientOptions);
1178
+ window.addEventListener('beforeunload', () => {
1179
+ const requests = getUnprocessedRequests();
1180
+ for (let { eventType, payload } of requests) {
1181
+ this.beaconClient.sendEvent(eventType, payload);
1182
+ }
1183
+ });
1184
+ }
1185
+ getClientDependingOnEventType(eventType) {
1186
+ return eventType === 'click' && this.beaconClient.isAvailable() ? this.beaconClient : this.client;
1187
+ }
1188
+ }
1189
+ class NodeJSRuntime {
1190
+ constructor(clientOptions, storage) {
1191
+ this.storage = storage || new NullStorage();
1192
+ this.client = new AnalyticsFetchClient(clientOptions);
1193
+ }
1194
+ getClientDependingOnEventType(eventType) {
1195
+ return this.client;
1196
+ }
1197
+ }
1198
+ class NoopRuntime {
1199
+ constructor() {
1200
+ this.storage = new NullStorage();
1201
+ this.client = new NoopAnalyticsClient();
1202
+ }
1203
+ getClientDependingOnEventType(eventType) {
1204
+ return this.client;
1205
+ }
1206
+ }
1207
+
1208
+ const API_KEY_PREFIX = 'xx';
1209
+ const isApiKey = (token) => (token === null || token === void 0 ? void 0 : token.startsWith(API_KEY_PREFIX)) || false;
1210
+
1211
+ const ReactNativeRuntimeWarning = `
1212
+ We've detected you're using React Native but have not provided the corresponding runtime,
1213
+ for an optimal experience please use the "coveo.analytics/react-native" subpackage.
1214
+ Follow the Readme on how to set it up: https://github.com/coveo/coveo.analytics.js#using-react-native
1215
+ `;
1216
+ function isReactNative() {
1217
+ return typeof navigator != 'undefined' && navigator.product == 'ReactNative';
1218
+ }
1219
+
1220
+ const doNotTrackValues = ['1', 1, 'yes', true];
1221
+ function doNotTrack() {
1222
+ return (hasNavigator() &&
1223
+ [
1224
+ navigator.globalPrivacyControl,
1225
+ navigator.doNotTrack,
1226
+ navigator.msDoNotTrack,
1227
+ window.doNotTrack,
1228
+ ].some((value) => doNotTrackValues.indexOf(value) !== -1));
1229
+ }
1230
+
1231
+ const Version = 'v15';
1232
+ const Endpoints = {
1233
+ default: 'https://analytics.cloud.coveo.com/rest/ua',
1234
+ production: 'https://analytics.cloud.coveo.com/rest/ua',
1235
+ hipaa: 'https://analyticshipaa.cloud.coveo.com/rest/ua',
1236
+ };
1237
+ function buildBaseUrl(endpoint = Endpoints.default, apiVersion = Version, isCustomEndpoint = false) {
1238
+ endpoint = endpoint.replace(/\/$/, '');
1239
+ if (isCustomEndpoint) {
1240
+ return `${endpoint}/${apiVersion}`;
1241
+ }
1242
+ const hasUARestEndpoint = endpoint.endsWith('/rest') || endpoint.endsWith('/rest/ua');
1243
+ return `${endpoint}${hasUARestEndpoint ? '' : '/rest'}/${apiVersion}`;
1244
+ }
1245
+ const COVEO_NAMESPACE = '38824e1f-37f5-42d3-8372-a4b8fa9df946';
1246
+ class CoveoAnalyticsClient {
1247
+ get defaultOptions() {
1248
+ return {
1249
+ endpoint: Endpoints.default,
1250
+ isCustomEndpoint: false,
1251
+ token: '',
1252
+ version: Version,
1253
+ beforeSendHooks: [],
1254
+ afterSendHooks: [],
1255
+ };
1256
+ }
1257
+ get version() {
1258
+ return libVersion;
1259
+ }
1260
+ constructor(opts) {
1261
+ this.acceptedLinkReferrers = [];
1262
+ if (!opts) {
1263
+ throw new Error('You have to pass options to this constructor');
1264
+ }
1265
+ this.options = Object.assign(Object.assign({}, this.defaultOptions), opts);
1266
+ this.visitorId = '';
1267
+ this.bufferedRequests = [];
1268
+ this.beforeSendHooks = [enhanceViewEvent, addDefaultValues].concat(this.options.beforeSendHooks);
1269
+ this.afterSendHooks = this.options.afterSendHooks;
1270
+ this.eventTypeMapping = {};
1271
+ const clientsOptions = {
1272
+ baseUrl: this.baseUrl,
1273
+ token: this.options.token,
1274
+ visitorIdProvider: this,
1275
+ preprocessRequest: this.options.preprocessRequest,
1276
+ };
1277
+ this.runtime = this.options.runtimeEnvironment || this.initRuntime(clientsOptions);
1278
+ if (doNotTrack()) {
1279
+ this.clear();
1280
+ this.runtime.storage = new NullStorage();
1281
+ }
1282
+ }
1283
+ initRuntime(clientsOptions) {
1284
+ if (hasWindow() && hasDocument()) {
1285
+ return new BrowserRuntime(clientsOptions, () => {
1286
+ const copy = [...this.bufferedRequests];
1287
+ this.bufferedRequests = [];
1288
+ return copy;
1289
+ });
1290
+ }
1291
+ else if (isReactNative()) {
1292
+ console.warn(ReactNativeRuntimeWarning);
1293
+ }
1294
+ return new NodeJSRuntime(clientsOptions);
1295
+ }
1296
+ get storage() {
1297
+ return this.runtime.storage;
1298
+ }
1299
+ determineVisitorId() {
1300
+ return __awaiter(this, void 0, void 0, function* () {
1301
+ try {
1302
+ return (this.extractClientIdFromLink(window.location.href) ||
1303
+ (yield this.storage.getItem('visitorId')) ||
1304
+ v4());
1305
+ }
1306
+ catch (err) {
1307
+ console.log('Could not get visitor ID from the current runtime environment storage. Using a random ID instead.', err);
1308
+ return v4();
1309
+ }
1310
+ });
1311
+ }
1312
+ getCurrentVisitorId() {
1313
+ return __awaiter(this, void 0, void 0, function* () {
1314
+ if (!this.visitorId) {
1315
+ const id = yield this.determineVisitorId();
1316
+ yield this.setCurrentVisitorId(id);
1317
+ }
1318
+ return this.visitorId;
1319
+ });
1320
+ }
1321
+ setCurrentVisitorId(visitorId) {
1322
+ return __awaiter(this, void 0, void 0, function* () {
1323
+ this.visitorId = visitorId;
1324
+ yield this.storage.setItem('visitorId', visitorId);
1325
+ });
1326
+ }
1327
+ setClientId(value, namespace) {
1328
+ return __awaiter(this, void 0, void 0, function* () {
1329
+ if (validate(value)) {
1330
+ this.setCurrentVisitorId(value.toLowerCase());
1331
+ }
1332
+ else {
1333
+ if (!namespace) {
1334
+ throw Error('Cannot generate uuid client id without a specific namespace string.');
1335
+ }
1336
+ this.setCurrentVisitorId(uuidv5(value, uuidv5(namespace, COVEO_NAMESPACE)));
1337
+ }
1338
+ });
1339
+ }
1340
+ getParameters(eventType, ...payload) {
1341
+ return __awaiter(this, void 0, void 0, function* () {
1342
+ return yield this.resolveParameters(eventType, ...payload);
1343
+ });
1344
+ }
1345
+ getPayload(eventType, ...payload) {
1346
+ return __awaiter(this, void 0, void 0, function* () {
1347
+ const parametersToSend = yield this.resolveParameters(eventType, ...payload);
1348
+ return yield this.resolvePayloadForParameters(eventType, parametersToSend);
1349
+ });
1350
+ }
1351
+ get currentVisitorId() {
1352
+ const visitorId = this.visitorId || this.storage.getItem('visitorId');
1353
+ if (typeof visitorId !== 'string') {
1354
+ this.setCurrentVisitorId(v4());
1355
+ }
1356
+ return this.visitorId;
1357
+ }
1358
+ set currentVisitorId(visitorId) {
1359
+ this.visitorId = visitorId;
1360
+ this.storage.setItem('visitorId', visitorId);
1361
+ }
1362
+ extractClientIdFromLink(urlString) {
1363
+ if (doNotTrack()) {
1364
+ return null;
1365
+ }
1366
+ try {
1367
+ const linkParam = new URL(urlString).searchParams.get(CoveoLinkParam.cvo_cid);
1368
+ if (linkParam == null) {
1369
+ return null;
1370
+ }
1371
+ const linker = CoveoLinkParam.fromString(linkParam);
1372
+ if (!linker || !hasDocument() || !linker.validate(document.referrer, this.acceptedLinkReferrers)) {
1373
+ return null;
1374
+ }
1375
+ return linker.clientId;
1376
+ }
1377
+ catch (error) {
1378
+ }
1379
+ return null;
1380
+ }
1381
+ resolveParameters(eventType, ...payload) {
1382
+ return __awaiter(this, void 0, void 0, function* () {
1383
+ const { variableLengthArgumentsNames = [], addVisitorIdParameter = false, usesMeasurementProtocol = false, addClientIdParameter = false, } = this.eventTypeMapping[eventType] || {};
1384
+ const processVariableArgumentNamesStep = (currentPayload) => variableLengthArgumentsNames.length > 0
1385
+ ? this.parseVariableArgumentsPayload(variableLengthArgumentsNames, currentPayload)
1386
+ : currentPayload[0];
1387
+ const addVisitorIdStep = (currentPayload) => __awaiter(this, void 0, void 0, function* () {
1388
+ return (Object.assign(Object.assign({}, currentPayload), { visitorId: addVisitorIdParameter ? yield this.getCurrentVisitorId() : '' }));
1389
+ });
1390
+ const addClientIdStep = (currentPayload) => __awaiter(this, void 0, void 0, function* () {
1391
+ if (addClientIdParameter) {
1392
+ return Object.assign(Object.assign({}, currentPayload), { clientId: yield this.getCurrentVisitorId() });
1393
+ }
1394
+ return currentPayload;
1395
+ });
1396
+ const setAnonymousUserStep = (currentPayload) => usesMeasurementProtocol ? this.ensureAnonymousUserWhenUsingApiKey(currentPayload) : currentPayload;
1397
+ const processBeforeSendHooksStep = (currentPayload) => this.beforeSendHooks.reduce((promisePayload, current) => __awaiter(this, void 0, void 0, function* () {
1398
+ const payload = yield promisePayload;
1399
+ return yield current(eventType, payload);
1400
+ }), currentPayload);
1401
+ const parametersToSend = yield [
1402
+ processVariableArgumentNamesStep,
1403
+ addVisitorIdStep,
1404
+ addClientIdStep,
1405
+ setAnonymousUserStep,
1406
+ processBeforeSendHooksStep,
1407
+ ].reduce((payloadPromise, step) => __awaiter(this, void 0, void 0, function* () {
1408
+ const payload = yield payloadPromise;
1409
+ return yield step(payload);
1410
+ }), Promise.resolve(payload));
1411
+ return parametersToSend;
1412
+ });
1413
+ }
1414
+ resolvePayloadForParameters(eventType, parameters) {
1415
+ return __awaiter(this, void 0, void 0, function* () {
1416
+ const { usesMeasurementProtocol = false } = this.eventTypeMapping[eventType] || {};
1417
+ const addTrackingIdStep = (currentPayload) => this.setTrackingIdIfTrackingIdNotPresent(currentPayload);
1418
+ const cleanPayloadStep = (currentPayload) => this.removeEmptyPayloadValues(currentPayload, eventType);
1419
+ const validateParams = (currentPayload) => this.validateParams(currentPayload, eventType);
1420
+ const processMeasurementProtocolConversionStep = (currentPayload) => usesMeasurementProtocol ? convertKeysToMeasurementProtocol(currentPayload) : currentPayload;
1421
+ const removeUnknownParameters = (currentPayload) => usesMeasurementProtocol ? this.removeUnknownParameters(currentPayload) : currentPayload;
1422
+ const processCustomParameters = (currentPayload) => usesMeasurementProtocol
1423
+ ? this.processCustomParameters(currentPayload)
1424
+ : this.mapCustomParametersToCustomData(currentPayload);
1425
+ const payloadToSend = yield [
1426
+ addTrackingIdStep,
1427
+ cleanPayloadStep,
1428
+ validateParams,
1429
+ processMeasurementProtocolConversionStep,
1430
+ removeUnknownParameters,
1431
+ processCustomParameters,
1432
+ ].reduce((payloadPromise, step) => __awaiter(this, void 0, void 0, function* () {
1433
+ const payload = yield payloadPromise;
1434
+ return yield step(payload);
1435
+ }), Promise.resolve(parameters));
1436
+ return payloadToSend;
1437
+ });
1438
+ }
1439
+ makeEvent(eventType, ...payload) {
1440
+ return __awaiter(this, void 0, void 0, function* () {
1441
+ const { newEventType: eventTypeToSend = eventType } = this.eventTypeMapping[eventType] || {};
1442
+ const parametersToSend = yield this.resolveParameters(eventType, ...payload);
1443
+ const payloadToSend = yield this.resolvePayloadForParameters(eventType, parametersToSend);
1444
+ return {
1445
+ eventType: eventTypeToSend,
1446
+ payload: payloadToSend,
1447
+ log: (remainingPayload) => __awaiter(this, void 0, void 0, function* () {
1448
+ this.bufferedRequests.push({
1449
+ eventType: eventTypeToSend,
1450
+ payload: Object.assign(Object.assign({}, payloadToSend), remainingPayload),
1451
+ });
1452
+ yield Promise.all(this.afterSendHooks.map((hook) => hook(eventType, Object.assign(Object.assign({}, parametersToSend), remainingPayload))));
1453
+ yield this.deferExecution();
1454
+ return (yield this.sendFromBuffer());
1455
+ }),
1456
+ };
1457
+ });
1458
+ }
1459
+ sendEvent(eventType, ...payload) {
1460
+ return __awaiter(this, void 0, void 0, function* () {
1461
+ return (yield this.makeEvent(eventType, ...payload)).log({});
1462
+ });
1463
+ }
1464
+ deferExecution() {
1465
+ return new Promise((resolve) => setTimeout(resolve, 0));
1466
+ }
1467
+ sendFromBuffer() {
1468
+ return __awaiter(this, void 0, void 0, function* () {
1469
+ const popped = this.bufferedRequests.shift();
1470
+ if (popped) {
1471
+ const { eventType, payload } = popped;
1472
+ return this.runtime.getClientDependingOnEventType(eventType).sendEvent(eventType, payload);
1473
+ }
1474
+ });
1475
+ }
1476
+ clear() {
1477
+ this.storage.removeItem('visitorId');
1478
+ const store = new HistoryStore();
1479
+ store.clear();
1480
+ }
1481
+ deleteHttpOnlyVisitorId() {
1482
+ this.runtime.client.deleteHttpCookieVisitorId();
1483
+ }
1484
+ makeSearchEvent(request) {
1485
+ return __awaiter(this, void 0, void 0, function* () {
1486
+ return this.makeEvent(EventType.search, request);
1487
+ });
1488
+ }
1489
+ sendSearchEvent(_a) {
1490
+ var { searchQueryUid } = _a, preparedRequest = __rest(_a, ["searchQueryUid"]);
1491
+ return __awaiter(this, void 0, void 0, function* () {
1492
+ return (yield this.makeSearchEvent(preparedRequest)).log({ searchQueryUid });
1493
+ });
1494
+ }
1495
+ makeClickEvent(request) {
1496
+ return __awaiter(this, void 0, void 0, function* () {
1497
+ return this.makeEvent(EventType.click, request);
1498
+ });
1499
+ }
1500
+ sendClickEvent(_a) {
1501
+ var { searchQueryUid } = _a, preparedRequest = __rest(_a, ["searchQueryUid"]);
1502
+ return __awaiter(this, void 0, void 0, function* () {
1503
+ return (yield this.makeClickEvent(preparedRequest)).log({ searchQueryUid });
1504
+ });
1505
+ }
1506
+ makeCustomEvent(request) {
1507
+ return __awaiter(this, void 0, void 0, function* () {
1508
+ return this.makeEvent(EventType.custom, request);
1509
+ });
1510
+ }
1511
+ sendCustomEvent(_a) {
1512
+ var { lastSearchQueryUid } = _a, preparedRequest = __rest(_a, ["lastSearchQueryUid"]);
1513
+ return __awaiter(this, void 0, void 0, function* () {
1514
+ return (yield this.makeCustomEvent(preparedRequest)).log({ lastSearchQueryUid });
1515
+ });
1516
+ }
1517
+ makeViewEvent(request) {
1518
+ return __awaiter(this, void 0, void 0, function* () {
1519
+ return this.makeEvent(EventType.view, request);
1520
+ });
1521
+ }
1522
+ sendViewEvent(request) {
1523
+ return __awaiter(this, void 0, void 0, function* () {
1524
+ return (yield this.makeViewEvent(request)).log({});
1525
+ });
1526
+ }
1527
+ getVisit() {
1528
+ return __awaiter(this, void 0, void 0, function* () {
1529
+ const response = yield fetch(`${this.baseUrl}/analytics/visit`);
1530
+ const visit = (yield response.json());
1531
+ this.visitorId = visit.visitorId;
1532
+ return visit;
1533
+ });
1534
+ }
1535
+ getHealth() {
1536
+ return __awaiter(this, void 0, void 0, function* () {
1537
+ const response = yield fetch(`${this.baseUrl}/analytics/monitoring/health`);
1538
+ return (yield response.json());
1539
+ });
1540
+ }
1541
+ registerBeforeSendEventHook(hook) {
1542
+ this.beforeSendHooks.push(hook);
1543
+ }
1544
+ registerAfterSendEventHook(hook) {
1545
+ this.afterSendHooks.push(hook);
1546
+ }
1547
+ addEventTypeMapping(eventType, eventConfig) {
1548
+ this.eventTypeMapping[eventType] = eventConfig;
1549
+ }
1550
+ setAcceptedLinkReferrers(hosts) {
1551
+ if (Array.isArray(hosts) && hosts.every((host) => typeof host == 'string'))
1552
+ this.acceptedLinkReferrers = hosts;
1553
+ else
1554
+ throw Error('Parameter should be an array of domain strings');
1555
+ }
1556
+ parseVariableArgumentsPayload(fieldsOrder, payload) {
1557
+ const parsedArguments = {};
1558
+ for (let i = 0, length = payload.length; i < length; i++) {
1559
+ const currentArgument = payload[i];
1560
+ if (typeof currentArgument === 'string') {
1561
+ parsedArguments[fieldsOrder[i]] = currentArgument;
1562
+ }
1563
+ else if (typeof currentArgument === 'object') {
1564
+ return Object.assign(Object.assign({}, parsedArguments), currentArgument);
1565
+ }
1566
+ }
1567
+ return parsedArguments;
1568
+ }
1569
+ isKeyAllowedEmpty(evtType, key) {
1570
+ const keysThatCanBeEmpty = {
1571
+ [EventType.search]: ['queryText'],
1572
+ };
1573
+ const match = keysThatCanBeEmpty[evtType] || [];
1574
+ return match.indexOf(key) !== -1;
1575
+ }
1576
+ removeEmptyPayloadValues(payload, eventType) {
1577
+ const isNotEmptyValue = (value) => typeof value !== 'undefined' && value !== null && value !== '';
1578
+ return Object.keys(payload)
1579
+ .filter((key) => this.isKeyAllowedEmpty(eventType, key) || isNotEmptyValue(payload[key]))
1580
+ .reduce((newPayload, key) => (Object.assign(Object.assign({}, newPayload), { [key]: payload[key] })), {});
1581
+ }
1582
+ removeUnknownParameters(payload) {
1583
+ const newPayload = Object.keys(payload)
1584
+ .filter((key) => {
1585
+ if (isMeasurementProtocolKey(key)) {
1586
+ return true;
1587
+ }
1588
+ else {
1589
+ console.log(key, 'is not processed by coveoua');
1590
+ }
1591
+ })
1592
+ .reduce((newPayload, key) => (Object.assign(Object.assign({}, newPayload), { [key]: payload[key] })), {});
1593
+ return newPayload;
1594
+ }
1595
+ processCustomParameters(payload) {
1596
+ const { custom } = payload, rest = __rest(payload, ["custom"]);
1597
+ let lowercasedCustom = {};
1598
+ if (custom && isObject(custom)) {
1599
+ lowercasedCustom = this.lowercaseKeys(custom);
1600
+ }
1601
+ const newPayload = convertCustomMeasurementProtocolKeys(rest);
1602
+ return Object.assign(Object.assign({}, lowercasedCustom), newPayload);
1603
+ }
1604
+ mapCustomParametersToCustomData(payload) {
1605
+ const { custom } = payload, rest = __rest(payload, ["custom"]);
1606
+ if (custom && isObject(custom)) {
1607
+ const lowercasedCustom = this.lowercaseKeys(custom);
1608
+ return Object.assign(Object.assign({}, rest), { customData: Object.assign(Object.assign({}, lowercasedCustom), payload.customData) });
1609
+ }
1610
+ else {
1611
+ return payload;
1612
+ }
1613
+ }
1614
+ lowercaseKeys(custom) {
1615
+ const keys = Object.keys(custom);
1616
+ let result = {};
1617
+ keys.forEach((key) => {
1618
+ result[key.toLowerCase()] = custom[key];
1619
+ });
1620
+ return result;
1621
+ }
1622
+ validateParams(payload, eventType) {
1623
+ const { anonymizeIp } = payload, rest = __rest(payload, ["anonymizeIp"]);
1624
+ if (anonymizeIp !== undefined) {
1625
+ if (['0', 'false', 'undefined', 'null', '{}', '[]', ''].indexOf(`${anonymizeIp}`.toLowerCase()) == -1) {
1626
+ rest.anonymizeIp = 1;
1627
+ }
1628
+ }
1629
+ if (eventType == EventType.view ||
1630
+ eventType == EventType.click ||
1631
+ eventType == EventType.search ||
1632
+ eventType == EventType.custom) {
1633
+ rest.originLevel3 = this.limit(rest.originLevel3, 128);
1634
+ }
1635
+ if (eventType == EventType.view) {
1636
+ rest.location = this.limit(rest.location, 128);
1637
+ }
1638
+ if (eventType == 'pageview' || eventType == 'event') {
1639
+ rest.referrer = this.limit(rest.referrer, 2048);
1640
+ rest.location = this.limit(rest.location, 2048);
1641
+ rest.page = this.limit(rest.page, 2048);
1642
+ }
1643
+ return rest;
1644
+ }
1645
+ ensureAnonymousUserWhenUsingApiKey(payload) {
1646
+ const { userId } = payload, rest = __rest(payload, ["userId"]);
1647
+ if (isApiKey(this.options.token) && !userId) {
1648
+ rest['userId'] = 'anonymous';
1649
+ return rest;
1650
+ }
1651
+ else {
1652
+ return payload;
1653
+ }
1654
+ }
1655
+ setTrackingIdIfTrackingIdNotPresent(payload) {
1656
+ const { trackingId } = payload, rest = __rest(payload, ["trackingId"]);
1657
+ if (trackingId) {
1658
+ return payload;
1659
+ }
1660
+ if (rest.hasOwnProperty('custom') && isObject(rest.custom)) {
1661
+ if (rest.custom.hasOwnProperty('context_website') || rest.custom.hasOwnProperty('siteName')) {
1662
+ rest['trackingId'] = rest.custom.context_website || rest.custom.siteName;
1663
+ }
1664
+ }
1665
+ if (rest.hasOwnProperty('customData') && isObject(rest.customData)) {
1666
+ if (rest.customData.hasOwnProperty('context_website') || rest.customData.hasOwnProperty('siteName')) {
1667
+ rest['trackingId'] = rest.customData.context_website || rest.customData.siteName;
1668
+ }
1669
+ }
1670
+ return rest;
1671
+ }
1672
+ limit(input, length) {
1673
+ if (typeof input !== 'string') {
1674
+ return input;
1675
+ }
1676
+ return input.substring(0, length);
1677
+ }
1678
+ get baseUrl() {
1679
+ return buildBaseUrl(this.options.endpoint, this.options.version, this.options.isCustomEndpoint);
1680
+ }
1681
+ }
1682
+
1683
+ var InsightEvents;
1684
+ (function (InsightEvents) {
1685
+ InsightEvents["contextChanged"] = "contextChanged";
1686
+ InsightEvents["expandToFullUI"] = "expandToFullUI";
1687
+ InsightEvents["openUserActions"] = "openUserActions";
1688
+ InsightEvents["showPrecedingSessions"] = "showPrecedingSessions";
1689
+ InsightEvents["showFollowingSessions"] = "showFollowingSessions";
1690
+ InsightEvents["clickViewedDocument"] = "clickViewedDocument";
1691
+ InsightEvents["clickPageView"] = "clickPageView";
1692
+ })(InsightEvents || (InsightEvents = {}));
1693
+
1694
+ var SearchPageEvents;
1695
+ (function (SearchPageEvents) {
1696
+ SearchPageEvents["interfaceLoad"] = "interfaceLoad";
1697
+ SearchPageEvents["interfaceChange"] = "interfaceChange";
1698
+ SearchPageEvents["didyoumeanAutomatic"] = "didyoumeanAutomatic";
1699
+ SearchPageEvents["didyoumeanClick"] = "didyoumeanClick";
1700
+ SearchPageEvents["resultsSort"] = "resultsSort";
1701
+ SearchPageEvents["searchboxSubmit"] = "searchboxSubmit";
1702
+ SearchPageEvents["searchboxClear"] = "searchboxClear";
1703
+ SearchPageEvents["searchboxAsYouType"] = "searchboxAsYouType";
1704
+ SearchPageEvents["breadcrumbFacet"] = "breadcrumbFacet";
1705
+ SearchPageEvents["breadcrumbResetAll"] = "breadcrumbResetAll";
1706
+ SearchPageEvents["documentQuickview"] = "documentQuickview";
1707
+ SearchPageEvents["documentOpen"] = "documentOpen";
1708
+ SearchPageEvents["omniboxAnalytics"] = "omniboxAnalytics";
1709
+ SearchPageEvents["omniboxFromLink"] = "omniboxFromLink";
1710
+ SearchPageEvents["searchFromLink"] = "searchFromLink";
1711
+ SearchPageEvents["triggerNotify"] = "notify";
1712
+ SearchPageEvents["triggerExecute"] = "execute";
1713
+ SearchPageEvents["triggerQuery"] = "query";
1714
+ SearchPageEvents["undoTriggerQuery"] = "undoQuery";
1715
+ SearchPageEvents["triggerRedirect"] = "redirect";
1716
+ SearchPageEvents["pagerResize"] = "pagerResize";
1717
+ SearchPageEvents["pagerNumber"] = "pagerNumber";
1718
+ SearchPageEvents["pagerNext"] = "pagerNext";
1719
+ SearchPageEvents["pagerPrevious"] = "pagerPrevious";
1720
+ SearchPageEvents["pagerScrolling"] = "pagerScrolling";
1721
+ SearchPageEvents["staticFilterClearAll"] = "staticFilterClearAll";
1722
+ SearchPageEvents["staticFilterSelect"] = "staticFilterSelect";
1723
+ SearchPageEvents["staticFilterDeselect"] = "staticFilterDeselect";
1724
+ SearchPageEvents["facetClearAll"] = "facetClearAll";
1725
+ SearchPageEvents["facetSearch"] = "facetSearch";
1726
+ SearchPageEvents["facetSelect"] = "facetSelect";
1727
+ SearchPageEvents["facetSelectAll"] = "facetSelectAll";
1728
+ SearchPageEvents["facetDeselect"] = "facetDeselect";
1729
+ SearchPageEvents["facetExclude"] = "facetExclude";
1730
+ SearchPageEvents["facetUnexclude"] = "facetUnexclude";
1731
+ SearchPageEvents["facetUpdateSort"] = "facetUpdateSort";
1732
+ SearchPageEvents["facetShowMore"] = "showMoreFacetResults";
1733
+ SearchPageEvents["facetShowLess"] = "showLessFacetResults";
1734
+ SearchPageEvents["queryError"] = "query";
1735
+ SearchPageEvents["queryErrorBack"] = "errorBack";
1736
+ SearchPageEvents["queryErrorClear"] = "errorClearQuery";
1737
+ SearchPageEvents["queryErrorRetry"] = "errorRetry";
1738
+ SearchPageEvents["recommendation"] = "recommendation";
1739
+ SearchPageEvents["recommendationInterfaceLoad"] = "recommendationInterfaceLoad";
1740
+ SearchPageEvents["recommendationOpen"] = "recommendationOpen";
1741
+ SearchPageEvents["likeSmartSnippet"] = "likeSmartSnippet";
1742
+ SearchPageEvents["dislikeSmartSnippet"] = "dislikeSmartSnippet";
1743
+ SearchPageEvents["expandSmartSnippet"] = "expandSmartSnippet";
1744
+ SearchPageEvents["collapseSmartSnippet"] = "collapseSmartSnippet";
1745
+ SearchPageEvents["openSmartSnippetFeedbackModal"] = "openSmartSnippetFeedbackModal";
1746
+ SearchPageEvents["closeSmartSnippetFeedbackModal"] = "closeSmartSnippetFeedbackModal";
1747
+ SearchPageEvents["sendSmartSnippetReason"] = "sendSmartSnippetReason";
1748
+ SearchPageEvents["expandSmartSnippetSuggestion"] = "expandSmartSnippetSuggestion";
1749
+ SearchPageEvents["collapseSmartSnippetSuggestion"] = "collapseSmartSnippetSuggestion";
1750
+ SearchPageEvents["showMoreSmartSnippetSuggestion"] = "showMoreSmartSnippetSuggestion";
1751
+ SearchPageEvents["showLessSmartSnippetSuggestion"] = "showLessSmartSnippetSuggestion";
1752
+ SearchPageEvents["openSmartSnippetSource"] = "openSmartSnippetSource";
1753
+ SearchPageEvents["openSmartSnippetSuggestionSource"] = "openSmartSnippetSuggestionSource";
1754
+ SearchPageEvents["openSmartSnippetInlineLink"] = "openSmartSnippetInlineLink";
1755
+ SearchPageEvents["openSmartSnippetSuggestionInlineLink"] = "openSmartSnippetSuggestionInlineLink";
1756
+ SearchPageEvents["recentQueryClick"] = "recentQueriesClick";
1757
+ SearchPageEvents["clearRecentQueries"] = "clearRecentQueries";
1758
+ SearchPageEvents["recentResultClick"] = "recentResultClick";
1759
+ SearchPageEvents["clearRecentResults"] = "clearRecentResults";
1760
+ SearchPageEvents["noResultsBack"] = "noResultsBack";
1761
+ SearchPageEvents["showMoreFoldedResults"] = "showMoreFoldedResults";
1762
+ SearchPageEvents["showLessFoldedResults"] = "showLessFoldedResults";
1763
+ SearchPageEvents["copyToClipboard"] = "copyToClipboard";
1764
+ SearchPageEvents["caseSendEmail"] = "Case.SendEmail";
1765
+ SearchPageEvents["feedItemTextPost"] = "FeedItem.TextPost";
1766
+ SearchPageEvents["caseAttach"] = "caseAttach";
1767
+ SearchPageEvents["caseDetach"] = "caseDetach";
1768
+ SearchPageEvents["retryGeneratedAnswer"] = "retryGeneratedAnswer";
1769
+ SearchPageEvents["likeGeneratedAnswer"] = "likeGeneratedAnswer";
1770
+ SearchPageEvents["dislikeGeneratedAnswer"] = "dislikeGeneratedAnswer";
1771
+ SearchPageEvents["openGeneratedAnswerSource"] = "openGeneratedAnswerSource";
1772
+ SearchPageEvents["generatedAnswerStreamEnd"] = "generatedAnswerStreamEnd";
1773
+ })(SearchPageEvents || (SearchPageEvents = {}));
1774
+ const CustomEventsTypes = {
1775
+ [SearchPageEvents.triggerNotify]: 'queryPipelineTriggers',
1776
+ [SearchPageEvents.triggerExecute]: 'queryPipelineTriggers',
1777
+ [SearchPageEvents.triggerQuery]: 'queryPipelineTriggers',
1778
+ [SearchPageEvents.triggerRedirect]: 'queryPipelineTriggers',
1779
+ [SearchPageEvents.queryError]: 'errors',
1780
+ [SearchPageEvents.queryErrorBack]: 'errors',
1781
+ [SearchPageEvents.queryErrorClear]: 'errors',
1782
+ [SearchPageEvents.queryErrorRetry]: 'errors',
1783
+ [SearchPageEvents.pagerNext]: 'getMoreResults',
1784
+ [SearchPageEvents.pagerPrevious]: 'getMoreResults',
1785
+ [SearchPageEvents.pagerNumber]: 'getMoreResults',
1786
+ [SearchPageEvents.pagerResize]: 'getMoreResults',
1787
+ [SearchPageEvents.pagerScrolling]: 'getMoreResults',
1788
+ [SearchPageEvents.facetSearch]: 'facet',
1789
+ [SearchPageEvents.facetShowLess]: 'facet',
1790
+ [SearchPageEvents.facetShowMore]: 'facet',
1791
+ [SearchPageEvents.recommendation]: 'recommendation',
1792
+ [SearchPageEvents.likeSmartSnippet]: 'smartSnippet',
1793
+ [SearchPageEvents.dislikeSmartSnippet]: 'smartSnippet',
1794
+ [SearchPageEvents.expandSmartSnippet]: 'smartSnippet',
1795
+ [SearchPageEvents.collapseSmartSnippet]: 'smartSnippet',
1796
+ [SearchPageEvents.openSmartSnippetFeedbackModal]: 'smartSnippet',
1797
+ [SearchPageEvents.closeSmartSnippetFeedbackModal]: 'smartSnippet',
1798
+ [SearchPageEvents.sendSmartSnippetReason]: 'smartSnippet',
1799
+ [SearchPageEvents.expandSmartSnippetSuggestion]: 'smartSnippetSuggestions',
1800
+ [SearchPageEvents.collapseSmartSnippetSuggestion]: 'smartSnippetSuggestions',
1801
+ [SearchPageEvents.showMoreSmartSnippetSuggestion]: 'smartSnippetSuggestions',
1802
+ [SearchPageEvents.showLessSmartSnippetSuggestion]: 'smartSnippetSuggestions',
1803
+ [SearchPageEvents.clearRecentQueries]: 'recentQueries',
1804
+ [SearchPageEvents.recentResultClick]: 'recentlyClickedDocuments',
1805
+ [SearchPageEvents.clearRecentResults]: 'recentlyClickedDocuments',
1806
+ [SearchPageEvents.showLessFoldedResults]: 'folding',
1807
+ [InsightEvents.expandToFullUI]: 'interface',
1808
+ [InsightEvents.openUserActions]: 'User Actions',
1809
+ [InsightEvents.showPrecedingSessions]: 'User Actions',
1810
+ [InsightEvents.showFollowingSessions]: 'User Actions',
1811
+ [InsightEvents.clickViewedDocument]: 'User Actions',
1812
+ [InsightEvents.clickPageView]: 'User Actions',
1813
+ [SearchPageEvents.caseDetach]: 'case',
1814
+ [SearchPageEvents.likeGeneratedAnswer]: 'generatedAnswer',
1815
+ [SearchPageEvents.dislikeGeneratedAnswer]: 'generatedAnswer',
1816
+ [SearchPageEvents.openGeneratedAnswerSource]: 'generatedAnswer',
1817
+ [SearchPageEvents.generatedAnswerStreamEnd]: 'generatedAnswer',
1818
+ };
1819
+
1820
+ class NoopAnalytics {
1821
+ constructor() {
1822
+ this.runtime = new NoopRuntime();
1823
+ this.currentVisitorId = '';
1824
+ }
1825
+ getPayload() {
1826
+ return Promise.resolve();
1827
+ }
1828
+ getParameters() {
1829
+ return Promise.resolve();
1830
+ }
1831
+ makeEvent(eventType) {
1832
+ return Promise.resolve({ eventType: eventType, payload: null, log: () => Promise.resolve() });
1833
+ }
1834
+ sendEvent() {
1835
+ return Promise.resolve();
1836
+ }
1837
+ makeSearchEvent() {
1838
+ return this.makeEvent(EventType.search);
1839
+ }
1840
+ sendSearchEvent() {
1841
+ return Promise.resolve();
1842
+ }
1843
+ makeClickEvent() {
1844
+ return this.makeEvent(EventType.click);
1845
+ }
1846
+ sendClickEvent() {
1847
+ return Promise.resolve();
1848
+ }
1849
+ makeCustomEvent() {
1850
+ return this.makeEvent(EventType.custom);
1851
+ }
1852
+ sendCustomEvent() {
1853
+ return Promise.resolve();
1854
+ }
1855
+ makeViewEvent() {
1856
+ return this.makeEvent(EventType.view);
1857
+ }
1858
+ sendViewEvent() {
1859
+ return Promise.resolve();
1860
+ }
1861
+ getVisit() {
1862
+ return Promise.resolve({ id: '', visitorId: '' });
1863
+ }
1864
+ getHealth() {
1865
+ return Promise.resolve({ status: '' });
1866
+ }
1867
+ registerBeforeSendEventHook() { }
1868
+ registerAfterSendEventHook() { }
1869
+ addEventTypeMapping() { }
1870
+ get version() {
1871
+ return libVersion;
1872
+ }
1873
+ }
1874
+
1875
+ function filterConsecutiveRepeatedValues(rawData) {
1876
+ let prev = '';
1877
+ return rawData.filter((value) => {
1878
+ const isDifferent = value !== prev;
1879
+ prev = value;
1880
+ return isDifferent;
1881
+ });
1882
+ }
1883
+ function removeSemicolons(rawData) {
1884
+ return rawData.map((value) => {
1885
+ return value.replace(/;/g, '');
1886
+ });
1887
+ }
1888
+ function getDataString(data) {
1889
+ const ANALYTICS_LENGTH_LIMIT = 256;
1890
+ const formattedData = data.join(';');
1891
+ if (formattedData.length <= ANALYTICS_LENGTH_LIMIT) {
1892
+ return formattedData;
1893
+ }
1894
+ return getDataString(data.slice(1));
1895
+ }
1896
+ const formatArrayForCoveoCustomData = (rawData) => {
1897
+ const dataWithoutSemicolons = removeSemicolons(rawData);
1898
+ const dataWithoutRepeatedValues = filterConsecutiveRepeatedValues(dataWithoutSemicolons);
1899
+ return getDataString(dataWithoutRepeatedValues);
1900
+ };
1901
+
1902
+ function formatOmniboxMetadata(meta) {
1903
+ const partialQueries = typeof meta.partialQueries === 'string'
1904
+ ? meta.partialQueries
1905
+ : formatArrayForCoveoCustomData(meta.partialQueries);
1906
+ const suggestions = typeof meta.suggestions === 'string' ? meta.suggestions : formatArrayForCoveoCustomData(meta.suggestions);
1907
+ return Object.assign(Object.assign({}, meta), { partialQueries,
1908
+ suggestions });
1909
+ }
1910
+
1911
+ class CoveoSearchPageClient {
1912
+ constructor(opts, provider) {
1913
+ this.opts = opts;
1914
+ this.provider = provider;
1915
+ const shouldDisableAnalytics = opts.enableAnalytics === false || doNotTrack();
1916
+ this.coveoAnalyticsClient = shouldDisableAnalytics ? new NoopAnalytics() : new CoveoAnalyticsClient(opts);
1917
+ }
1918
+ disable() {
1919
+ if (this.coveoAnalyticsClient instanceof CoveoAnalyticsClient) {
1920
+ this.coveoAnalyticsClient.clear();
1921
+ }
1922
+ this.coveoAnalyticsClient = new NoopAnalytics();
1923
+ }
1924
+ enable() {
1925
+ this.coveoAnalyticsClient = new CoveoAnalyticsClient(this.opts);
1926
+ }
1927
+ makeInterfaceLoad() {
1928
+ return this.makeSearchEvent(SearchPageEvents.interfaceLoad);
1929
+ }
1930
+ logInterfaceLoad() {
1931
+ return __awaiter(this, void 0, void 0, function* () {
1932
+ return (yield this.makeInterfaceLoad()).log({ searchUID: this.provider.getSearchUID() });
1933
+ });
1934
+ }
1935
+ makeRecommendationInterfaceLoad() {
1936
+ return this.makeSearchEvent(SearchPageEvents.recommendationInterfaceLoad);
1937
+ }
1938
+ logRecommendationInterfaceLoad() {
1939
+ return __awaiter(this, void 0, void 0, function* () {
1940
+ return (yield this.makeRecommendationInterfaceLoad()).log({ searchUID: this.provider.getSearchUID() });
1941
+ });
1942
+ }
1943
+ makeRecommendation() {
1944
+ return this.makeCustomEvent(SearchPageEvents.recommendation);
1945
+ }
1946
+ logRecommendation() {
1947
+ return __awaiter(this, void 0, void 0, function* () {
1948
+ return (yield this.makeRecommendation()).log({ searchUID: this.provider.getSearchUID() });
1949
+ });
1950
+ }
1951
+ makeRecommendationOpen(info, identifier) {
1952
+ return this.makeClickEvent(SearchPageEvents.recommendationOpen, info, identifier);
1953
+ }
1954
+ logRecommendationOpen(info, identifier) {
1955
+ return __awaiter(this, void 0, void 0, function* () {
1956
+ return (yield this.makeRecommendationOpen(info, identifier)).log({ searchUID: this.provider.getSearchUID() });
1957
+ });
1958
+ }
1959
+ makeStaticFilterClearAll(meta) {
1960
+ return this.makeSearchEvent(SearchPageEvents.staticFilterClearAll, meta);
1961
+ }
1962
+ logStaticFilterClearAll(meta) {
1963
+ return __awaiter(this, void 0, void 0, function* () {
1964
+ return (yield this.makeStaticFilterClearAll(meta)).log({ searchUID: this.provider.getSearchUID() });
1965
+ });
1966
+ }
1967
+ makeStaticFilterSelect(meta) {
1968
+ return this.makeSearchEvent(SearchPageEvents.staticFilterSelect, meta);
1969
+ }
1970
+ logStaticFilterSelect(meta) {
1971
+ return __awaiter(this, void 0, void 0, function* () {
1972
+ return (yield this.makeStaticFilterSelect(meta)).log({ searchUID: this.provider.getSearchUID() });
1973
+ });
1974
+ }
1975
+ makeStaticFilterDeselect(meta) {
1976
+ return this.makeSearchEvent(SearchPageEvents.staticFilterDeselect, meta);
1977
+ }
1978
+ logStaticFilterDeselect(meta) {
1979
+ return __awaiter(this, void 0, void 0, function* () {
1980
+ return (yield this.makeStaticFilterDeselect(meta)).log({ searchUID: this.provider.getSearchUID() });
1981
+ });
1982
+ }
1983
+ makeFetchMoreResults() {
1984
+ return this.makeCustomEvent(SearchPageEvents.pagerScrolling, { type: 'getMoreResults' });
1985
+ }
1986
+ logFetchMoreResults() {
1987
+ return __awaiter(this, void 0, void 0, function* () {
1988
+ return (yield this.makeFetchMoreResults()).log({ searchUID: this.provider.getSearchUID() });
1989
+ });
1990
+ }
1991
+ makeInterfaceChange(metadata) {
1992
+ return this.makeSearchEvent(SearchPageEvents.interfaceChange, metadata);
1993
+ }
1994
+ logInterfaceChange(metadata) {
1995
+ return __awaiter(this, void 0, void 0, function* () {
1996
+ return (yield this.makeInterfaceChange(metadata)).log({ searchUID: this.provider.getSearchUID() });
1997
+ });
1998
+ }
1999
+ makeDidYouMeanAutomatic() {
2000
+ return this.makeSearchEvent(SearchPageEvents.didyoumeanAutomatic);
2001
+ }
2002
+ logDidYouMeanAutomatic() {
2003
+ return __awaiter(this, void 0, void 0, function* () {
2004
+ return (yield this.makeDidYouMeanAutomatic()).log({ searchUID: this.provider.getSearchUID() });
2005
+ });
2006
+ }
2007
+ makeDidYouMeanClick() {
2008
+ return this.makeSearchEvent(SearchPageEvents.didyoumeanClick);
2009
+ }
2010
+ logDidYouMeanClick() {
2011
+ return __awaiter(this, void 0, void 0, function* () {
2012
+ return (yield this.makeDidYouMeanClick()).log({ searchUID: this.provider.getSearchUID() });
2013
+ });
2014
+ }
2015
+ makeResultsSort(metadata) {
2016
+ return this.makeSearchEvent(SearchPageEvents.resultsSort, metadata);
2017
+ }
2018
+ logResultsSort(metadata) {
2019
+ return __awaiter(this, void 0, void 0, function* () {
2020
+ return (yield this.makeResultsSort(metadata)).log({ searchUID: this.provider.getSearchUID() });
2021
+ });
2022
+ }
2023
+ makeSearchboxSubmit() {
2024
+ return this.makeSearchEvent(SearchPageEvents.searchboxSubmit);
2025
+ }
2026
+ logSearchboxSubmit() {
2027
+ return __awaiter(this, void 0, void 0, function* () {
2028
+ return (yield this.makeSearchboxSubmit()).log({ searchUID: this.provider.getSearchUID() });
2029
+ });
2030
+ }
2031
+ makeSearchboxClear() {
2032
+ return this.makeSearchEvent(SearchPageEvents.searchboxClear);
2033
+ }
2034
+ logSearchboxClear() {
2035
+ return __awaiter(this, void 0, void 0, function* () {
2036
+ return (yield this.makeSearchboxClear()).log({ searchUID: this.provider.getSearchUID() });
2037
+ });
2038
+ }
2039
+ makeSearchboxAsYouType() {
2040
+ return this.makeSearchEvent(SearchPageEvents.searchboxAsYouType);
2041
+ }
2042
+ logSearchboxAsYouType() {
2043
+ return __awaiter(this, void 0, void 0, function* () {
2044
+ return (yield this.makeSearchboxAsYouType()).log({ searchUID: this.provider.getSearchUID() });
2045
+ });
2046
+ }
2047
+ makeBreadcrumbFacet(metadata) {
2048
+ return this.makeSearchEvent(SearchPageEvents.breadcrumbFacet, metadata);
2049
+ }
2050
+ logBreadcrumbFacet(metadata) {
2051
+ return __awaiter(this, void 0, void 0, function* () {
2052
+ return (yield this.makeBreadcrumbFacet(metadata)).log({ searchUID: this.provider.getSearchUID() });
2053
+ });
2054
+ }
2055
+ makeBreadcrumbResetAll() {
2056
+ return this.makeSearchEvent(SearchPageEvents.breadcrumbResetAll);
2057
+ }
2058
+ logBreadcrumbResetAll() {
2059
+ return __awaiter(this, void 0, void 0, function* () {
2060
+ return (yield this.makeBreadcrumbResetAll()).log({ searchUID: this.provider.getSearchUID() });
2061
+ });
2062
+ }
2063
+ makeDocumentQuickview(info, identifier) {
2064
+ return this.makeClickEvent(SearchPageEvents.documentQuickview, info, identifier);
2065
+ }
2066
+ logDocumentQuickview(info, identifier) {
2067
+ return __awaiter(this, void 0, void 0, function* () {
2068
+ return (yield this.makeDocumentQuickview(info, identifier)).log({ searchUID: this.provider.getSearchUID() });
2069
+ });
2070
+ }
2071
+ makeDocumentOpen(info, identifier) {
2072
+ return this.makeClickEvent(SearchPageEvents.documentOpen, info, identifier);
2073
+ }
2074
+ logDocumentOpen(info, identifier) {
2075
+ return __awaiter(this, void 0, void 0, function* () {
2076
+ return (yield this.makeDocumentOpen(info, identifier)).log({ searchUID: this.provider.getSearchUID() });
2077
+ });
2078
+ }
2079
+ makeOmniboxAnalytics(meta) {
2080
+ return this.makeSearchEvent(SearchPageEvents.omniboxAnalytics, formatOmniboxMetadata(meta));
2081
+ }
2082
+ logOmniboxAnalytics(meta) {
2083
+ return __awaiter(this, void 0, void 0, function* () {
2084
+ return (yield this.makeOmniboxAnalytics(meta)).log({ searchUID: this.provider.getSearchUID() });
2085
+ });
2086
+ }
2087
+ makeOmniboxFromLink(meta) {
2088
+ return this.makeSearchEvent(SearchPageEvents.omniboxFromLink, formatOmniboxMetadata(meta));
2089
+ }
2090
+ logOmniboxFromLink(meta) {
2091
+ return __awaiter(this, void 0, void 0, function* () {
2092
+ return (yield this.makeOmniboxFromLink(meta)).log({ searchUID: this.provider.getSearchUID() });
2093
+ });
2094
+ }
2095
+ makeSearchFromLink() {
2096
+ return this.makeSearchEvent(SearchPageEvents.searchFromLink);
2097
+ }
2098
+ logSearchFromLink() {
2099
+ return __awaiter(this, void 0, void 0, function* () {
2100
+ return (yield this.makeSearchFromLink()).log({ searchUID: this.provider.getSearchUID() });
2101
+ });
2102
+ }
2103
+ makeTriggerNotify(meta) {
2104
+ return this.makeCustomEvent(SearchPageEvents.triggerNotify, meta);
2105
+ }
2106
+ logTriggerNotify(meta) {
2107
+ return __awaiter(this, void 0, void 0, function* () {
2108
+ return (yield this.makeTriggerNotify(meta)).log({ searchUID: this.provider.getSearchUID() });
2109
+ });
2110
+ }
2111
+ makeTriggerExecute(meta) {
2112
+ return this.makeCustomEvent(SearchPageEvents.triggerExecute, meta);
2113
+ }
2114
+ logTriggerExecute(meta) {
2115
+ return __awaiter(this, void 0, void 0, function* () {
2116
+ return (yield this.makeTriggerExecute(meta)).log({ searchUID: this.provider.getSearchUID() });
2117
+ });
2118
+ }
2119
+ makeTriggerQuery() {
2120
+ return this.makeCustomEvent(SearchPageEvents.triggerQuery, { query: this.provider.getSearchEventRequestPayload().queryText }, 'queryPipelineTriggers');
2121
+ }
2122
+ logTriggerQuery() {
2123
+ return __awaiter(this, void 0, void 0, function* () {
2124
+ return (yield this.makeTriggerQuery()).log({ searchUID: this.provider.getSearchUID() });
2125
+ });
2126
+ }
2127
+ makeUndoTriggerQuery(meta) {
2128
+ return this.makeSearchEvent(SearchPageEvents.undoTriggerQuery, meta);
2129
+ }
2130
+ logUndoTriggerQuery(meta) {
2131
+ return __awaiter(this, void 0, void 0, function* () {
2132
+ return (yield this.makeUndoTriggerQuery(meta)).log({ searchUID: this.provider.getSearchUID() });
2133
+ });
2134
+ }
2135
+ makeTriggerRedirect(meta) {
2136
+ return this.makeCustomEvent(SearchPageEvents.triggerRedirect, Object.assign(Object.assign({}, meta), { query: this.provider.getSearchEventRequestPayload().queryText }));
2137
+ }
2138
+ logTriggerRedirect(meta) {
2139
+ return __awaiter(this, void 0, void 0, function* () {
2140
+ return (yield this.makeTriggerRedirect(meta)).log({ searchUID: this.provider.getSearchUID() });
2141
+ });
2142
+ }
2143
+ makePagerResize(meta) {
2144
+ return this.makeCustomEvent(SearchPageEvents.pagerResize, meta);
2145
+ }
2146
+ logPagerResize(meta) {
2147
+ return __awaiter(this, void 0, void 0, function* () {
2148
+ return (yield this.makePagerResize(meta)).log({ searchUID: this.provider.getSearchUID() });
2149
+ });
2150
+ }
2151
+ makePagerNumber(meta) {
2152
+ return this.makeCustomEvent(SearchPageEvents.pagerNumber, meta);
2153
+ }
2154
+ logPagerNumber(meta) {
2155
+ return __awaiter(this, void 0, void 0, function* () {
2156
+ return (yield this.makePagerNumber(meta)).log({ searchUID: this.provider.getSearchUID() });
2157
+ });
2158
+ }
2159
+ makePagerNext(meta) {
2160
+ return this.makeCustomEvent(SearchPageEvents.pagerNext, meta);
2161
+ }
2162
+ logPagerNext(meta) {
2163
+ return __awaiter(this, void 0, void 0, function* () {
2164
+ return (yield this.makePagerNext(meta)).log({ searchUID: this.provider.getSearchUID() });
2165
+ });
2166
+ }
2167
+ makePagerPrevious(meta) {
2168
+ return this.makeCustomEvent(SearchPageEvents.pagerPrevious, meta);
2169
+ }
2170
+ logPagerPrevious(meta) {
2171
+ return __awaiter(this, void 0, void 0, function* () {
2172
+ return (yield this.makePagerPrevious(meta)).log({ searchUID: this.provider.getSearchUID() });
2173
+ });
2174
+ }
2175
+ makePagerScrolling() {
2176
+ return this.makeCustomEvent(SearchPageEvents.pagerScrolling);
2177
+ }
2178
+ logPagerScrolling() {
2179
+ return __awaiter(this, void 0, void 0, function* () {
2180
+ return (yield this.makePagerScrolling()).log({ searchUID: this.provider.getSearchUID() });
2181
+ });
2182
+ }
2183
+ makeFacetClearAll(meta) {
2184
+ return this.makeSearchEvent(SearchPageEvents.facetClearAll, meta);
2185
+ }
2186
+ logFacetClearAll(meta) {
2187
+ return __awaiter(this, void 0, void 0, function* () {
2188
+ return (yield this.makeFacetClearAll(meta)).log({ searchUID: this.provider.getSearchUID() });
2189
+ });
2190
+ }
2191
+ makeFacetSearch(meta) {
2192
+ return this.makeSearchEvent(SearchPageEvents.facetSearch, meta);
2193
+ }
2194
+ logFacetSearch(meta) {
2195
+ return __awaiter(this, void 0, void 0, function* () {
2196
+ return (yield this.makeFacetSearch(meta)).log({ searchUID: this.provider.getSearchUID() });
2197
+ });
2198
+ }
2199
+ makeFacetSelect(meta) {
2200
+ return this.makeSearchEvent(SearchPageEvents.facetSelect, meta);
2201
+ }
2202
+ logFacetSelect(meta) {
2203
+ return __awaiter(this, void 0, void 0, function* () {
2204
+ return (yield this.makeFacetSelect(meta)).log({ searchUID: this.provider.getSearchUID() });
2205
+ });
2206
+ }
2207
+ makeFacetDeselect(meta) {
2208
+ return this.makeSearchEvent(SearchPageEvents.facetDeselect, meta);
2209
+ }
2210
+ logFacetDeselect(meta) {
2211
+ return __awaiter(this, void 0, void 0, function* () {
2212
+ return (yield this.makeFacetDeselect(meta)).log({ searchUID: this.provider.getSearchUID() });
2213
+ });
2214
+ }
2215
+ makeFacetExclude(meta) {
2216
+ return this.makeSearchEvent(SearchPageEvents.facetExclude, meta);
2217
+ }
2218
+ logFacetExclude(meta) {
2219
+ return __awaiter(this, void 0, void 0, function* () {
2220
+ return (yield this.makeFacetExclude(meta)).log({ searchUID: this.provider.getSearchUID() });
2221
+ });
2222
+ }
2223
+ makeFacetUnexclude(meta) {
2224
+ return this.makeSearchEvent(SearchPageEvents.facetUnexclude, meta);
2225
+ }
2226
+ logFacetUnexclude(meta) {
2227
+ return __awaiter(this, void 0, void 0, function* () {
2228
+ return (yield this.makeFacetUnexclude(meta)).log({ searchUID: this.provider.getSearchUID() });
2229
+ });
2230
+ }
2231
+ makeFacetSelectAll(meta) {
2232
+ return this.makeSearchEvent(SearchPageEvents.facetSelectAll, meta);
2233
+ }
2234
+ logFacetSelectAll(meta) {
2235
+ return __awaiter(this, void 0, void 0, function* () {
2236
+ return (yield this.makeFacetSelectAll(meta)).log({ searchUID: this.provider.getSearchUID() });
2237
+ });
2238
+ }
2239
+ makeFacetUpdateSort(meta) {
2240
+ return this.makeSearchEvent(SearchPageEvents.facetUpdateSort, meta);
2241
+ }
2242
+ logFacetUpdateSort(meta) {
2243
+ return __awaiter(this, void 0, void 0, function* () {
2244
+ return (yield this.makeFacetUpdateSort(meta)).log({ searchUID: this.provider.getSearchUID() });
2245
+ });
2246
+ }
2247
+ makeFacetShowMore(meta) {
2248
+ return this.makeCustomEvent(SearchPageEvents.facetShowMore, meta);
2249
+ }
2250
+ logFacetShowMore(meta) {
2251
+ return __awaiter(this, void 0, void 0, function* () {
2252
+ return (yield this.makeFacetShowMore(meta)).log({ searchUID: this.provider.getSearchUID() });
2253
+ });
2254
+ }
2255
+ makeFacetShowLess(meta) {
2256
+ return this.makeCustomEvent(SearchPageEvents.facetShowLess, meta);
2257
+ }
2258
+ logFacetShowLess(meta) {
2259
+ return __awaiter(this, void 0, void 0, function* () {
2260
+ return (yield this.makeFacetShowLess(meta)).log({ searchUID: this.provider.getSearchUID() });
2261
+ });
2262
+ }
2263
+ makeQueryError(meta) {
2264
+ return this.makeCustomEvent(SearchPageEvents.queryError, meta);
2265
+ }
2266
+ logQueryError(meta) {
2267
+ return __awaiter(this, void 0, void 0, function* () {
2268
+ return (yield this.makeQueryError(meta)).log({ searchUID: this.provider.getSearchUID() });
2269
+ });
2270
+ }
2271
+ makeQueryErrorBack() {
2272
+ return __awaiter(this, void 0, void 0, function* () {
2273
+ const customEventBuilder = yield this.makeCustomEvent(SearchPageEvents.queryErrorBack);
2274
+ return {
2275
+ description: customEventBuilder.description,
2276
+ log: () => __awaiter(this, void 0, void 0, function* () {
2277
+ yield customEventBuilder.log({ searchUID: this.provider.getSearchUID() });
2278
+ return this.logSearchEvent(SearchPageEvents.queryErrorBack);
2279
+ }),
2280
+ };
2281
+ });
2282
+ }
2283
+ logQueryErrorBack() {
2284
+ return __awaiter(this, void 0, void 0, function* () {
2285
+ return (yield this.makeQueryErrorBack()).log({ searchUID: this.provider.getSearchUID() });
2286
+ });
2287
+ }
2288
+ makeQueryErrorRetry() {
2289
+ return __awaiter(this, void 0, void 0, function* () {
2290
+ const customEventBuilder = yield this.makeCustomEvent(SearchPageEvents.queryErrorRetry);
2291
+ return {
2292
+ description: customEventBuilder.description,
2293
+ log: () => __awaiter(this, void 0, void 0, function* () {
2294
+ yield customEventBuilder.log({ searchUID: this.provider.getSearchUID() });
2295
+ return this.logSearchEvent(SearchPageEvents.queryErrorRetry);
2296
+ }),
2297
+ };
2298
+ });
2299
+ }
2300
+ logQueryErrorRetry() {
2301
+ return __awaiter(this, void 0, void 0, function* () {
2302
+ return (yield this.makeQueryErrorRetry()).log({ searchUID: this.provider.getSearchUID() });
2303
+ });
2304
+ }
2305
+ makeQueryErrorClear() {
2306
+ return __awaiter(this, void 0, void 0, function* () {
2307
+ const customEventBuilder = yield this.makeCustomEvent(SearchPageEvents.queryErrorClear);
2308
+ return {
2309
+ description: customEventBuilder.description,
2310
+ log: () => __awaiter(this, void 0, void 0, function* () {
2311
+ yield customEventBuilder.log({ searchUID: this.provider.getSearchUID() });
2312
+ return this.logSearchEvent(SearchPageEvents.queryErrorClear);
2313
+ }),
2314
+ };
2315
+ });
2316
+ }
2317
+ logQueryErrorClear() {
2318
+ return __awaiter(this, void 0, void 0, function* () {
2319
+ return (yield this.makeQueryErrorClear()).log({ searchUID: this.provider.getSearchUID() });
2320
+ });
2321
+ }
2322
+ makeLikeSmartSnippet() {
2323
+ return this.makeCustomEvent(SearchPageEvents.likeSmartSnippet);
2324
+ }
2325
+ logLikeSmartSnippet() {
2326
+ return __awaiter(this, void 0, void 0, function* () {
2327
+ return (yield this.makeLikeSmartSnippet()).log({ searchUID: this.provider.getSearchUID() });
2328
+ });
2329
+ }
2330
+ makeDislikeSmartSnippet() {
2331
+ return this.makeCustomEvent(SearchPageEvents.dislikeSmartSnippet);
2332
+ }
2333
+ logDislikeSmartSnippet() {
2334
+ return __awaiter(this, void 0, void 0, function* () {
2335
+ return (yield this.makeDislikeSmartSnippet()).log({ searchUID: this.provider.getSearchUID() });
2336
+ });
2337
+ }
2338
+ makeExpandSmartSnippet() {
2339
+ return this.makeCustomEvent(SearchPageEvents.expandSmartSnippet);
2340
+ }
2341
+ logExpandSmartSnippet() {
2342
+ return __awaiter(this, void 0, void 0, function* () {
2343
+ return (yield this.makeExpandSmartSnippet()).log({ searchUID: this.provider.getSearchUID() });
2344
+ });
2345
+ }
2346
+ makeCollapseSmartSnippet() {
2347
+ return this.makeCustomEvent(SearchPageEvents.collapseSmartSnippet);
2348
+ }
2349
+ logCollapseSmartSnippet() {
2350
+ return __awaiter(this, void 0, void 0, function* () {
2351
+ return (yield this.makeCollapseSmartSnippet()).log({ searchUID: this.provider.getSearchUID() });
2352
+ });
2353
+ }
2354
+ makeOpenSmartSnippetFeedbackModal() {
2355
+ return this.makeCustomEvent(SearchPageEvents.openSmartSnippetFeedbackModal);
2356
+ }
2357
+ logOpenSmartSnippetFeedbackModal() {
2358
+ return __awaiter(this, void 0, void 0, function* () {
2359
+ return (yield this.makeOpenSmartSnippetFeedbackModal()).log({ searchUID: this.provider.getSearchUID() });
2360
+ });
2361
+ }
2362
+ makeCloseSmartSnippetFeedbackModal() {
2363
+ return this.makeCustomEvent(SearchPageEvents.closeSmartSnippetFeedbackModal);
2364
+ }
2365
+ logCloseSmartSnippetFeedbackModal() {
2366
+ return __awaiter(this, void 0, void 0, function* () {
2367
+ return (yield this.makeCloseSmartSnippetFeedbackModal()).log({ searchUID: this.provider.getSearchUID() });
2368
+ });
2369
+ }
2370
+ makeSmartSnippetFeedbackReason(reason, details) {
2371
+ return this.makeCustomEvent(SearchPageEvents.sendSmartSnippetReason, { reason, details });
2372
+ }
2373
+ logSmartSnippetFeedbackReason(reason, details) {
2374
+ return __awaiter(this, void 0, void 0, function* () {
2375
+ return (yield this.makeSmartSnippetFeedbackReason(reason, details)).log({
2376
+ searchUID: this.provider.getSearchUID(),
2377
+ });
2378
+ });
2379
+ }
2380
+ makeExpandSmartSnippetSuggestion(snippet) {
2381
+ return this.makeCustomEvent(SearchPageEvents.expandSmartSnippetSuggestion, 'documentId' in snippet ? snippet : { documentId: snippet });
2382
+ }
2383
+ logExpandSmartSnippetSuggestion(snippet) {
2384
+ return __awaiter(this, void 0, void 0, function* () {
2385
+ return (yield this.makeExpandSmartSnippetSuggestion(snippet)).log({ searchUID: this.provider.getSearchUID() });
2386
+ });
2387
+ }
2388
+ makeCollapseSmartSnippetSuggestion(snippet) {
2389
+ return this.makeCustomEvent(SearchPageEvents.collapseSmartSnippetSuggestion, 'documentId' in snippet ? snippet : { documentId: snippet });
2390
+ }
2391
+ logCollapseSmartSnippetSuggestion(snippet) {
2392
+ return __awaiter(this, void 0, void 0, function* () {
2393
+ return (yield this.makeCollapseSmartSnippetSuggestion(snippet)).log({ searchUID: this.provider.getSearchUID() });
2394
+ });
2395
+ }
2396
+ makeShowMoreSmartSnippetSuggestion(snippet) {
2397
+ return this.makeCustomEvent(SearchPageEvents.showMoreSmartSnippetSuggestion, snippet);
2398
+ }
2399
+ logShowMoreSmartSnippetSuggestion(snippet) {
2400
+ return __awaiter(this, void 0, void 0, function* () {
2401
+ return (yield this.makeShowMoreSmartSnippetSuggestion(snippet)).log({ searchUID: this.provider.getSearchUID() });
2402
+ });
2403
+ }
2404
+ makeShowLessSmartSnippetSuggestion(snippet) {
2405
+ return this.makeCustomEvent(SearchPageEvents.showLessSmartSnippetSuggestion, snippet);
2406
+ }
2407
+ logShowLessSmartSnippetSuggestion(snippet) {
2408
+ return __awaiter(this, void 0, void 0, function* () {
2409
+ return (yield this.makeShowLessSmartSnippetSuggestion(snippet)).log({ searchUID: this.provider.getSearchUID() });
2410
+ });
2411
+ }
2412
+ makeOpenSmartSnippetSource(info, identifier) {
2413
+ return this.makeClickEvent(SearchPageEvents.openSmartSnippetSource, info, identifier);
2414
+ }
2415
+ logOpenSmartSnippetSource(info, identifier) {
2416
+ return __awaiter(this, void 0, void 0, function* () {
2417
+ return (yield this.makeOpenSmartSnippetSource(info, identifier)).log({ searchUID: this.provider.getSearchUID() });
2418
+ });
2419
+ }
2420
+ makeOpenSmartSnippetSuggestionSource(info, snippet) {
2421
+ return this.makeClickEvent(SearchPageEvents.openSmartSnippetSuggestionSource, info, { contentIDKey: snippet.documentId.contentIdKey, contentIDValue: snippet.documentId.contentIdValue }, snippet);
2422
+ }
2423
+ makeCopyToClipboard(info, identifier) {
2424
+ return this.makeClickEvent(SearchPageEvents.copyToClipboard, info, identifier);
2425
+ }
2426
+ logCopyToClipboard(info, identifier) {
2427
+ return __awaiter(this, void 0, void 0, function* () {
2428
+ return (yield this.makeCopyToClipboard(info, identifier)).log({ searchUID: this.provider.getSearchUID() });
2429
+ });
2430
+ }
2431
+ logOpenSmartSnippetSuggestionSource(info, snippet) {
2432
+ return __awaiter(this, void 0, void 0, function* () {
2433
+ return (yield this.makeOpenSmartSnippetSuggestionSource(info, snippet)).log({
2434
+ searchUID: this.provider.getSearchUID(),
2435
+ });
2436
+ });
2437
+ }
2438
+ makeOpenSmartSnippetInlineLink(info, identifierAndLink) {
2439
+ return this.makeClickEvent(SearchPageEvents.openSmartSnippetInlineLink, info, { contentIDKey: identifierAndLink.contentIDKey, contentIDValue: identifierAndLink.contentIDValue }, identifierAndLink);
2440
+ }
2441
+ logOpenSmartSnippetInlineLink(info, identifierAndLink) {
2442
+ return __awaiter(this, void 0, void 0, function* () {
2443
+ return (yield this.makeOpenSmartSnippetInlineLink(info, identifierAndLink)).log({
2444
+ searchUID: this.provider.getSearchUID(),
2445
+ });
2446
+ });
2447
+ }
2448
+ makeOpenSmartSnippetSuggestionInlineLink(info, snippetAndLink) {
2449
+ return this.makeClickEvent(SearchPageEvents.openSmartSnippetSuggestionInlineLink, info, {
2450
+ contentIDKey: snippetAndLink.documentId.contentIdKey,
2451
+ contentIDValue: snippetAndLink.documentId.contentIdValue,
2452
+ }, snippetAndLink);
2453
+ }
2454
+ logOpenSmartSnippetSuggestionInlineLink(info, snippetAndLink) {
2455
+ return __awaiter(this, void 0, void 0, function* () {
2456
+ return (yield this.makeOpenSmartSnippetSuggestionInlineLink(info, snippetAndLink)).log({
2457
+ searchUID: this.provider.getSearchUID(),
2458
+ });
2459
+ });
2460
+ }
2461
+ makeRecentQueryClick() {
2462
+ return this.makeSearchEvent(SearchPageEvents.recentQueryClick);
2463
+ }
2464
+ logRecentQueryClick() {
2465
+ return __awaiter(this, void 0, void 0, function* () {
2466
+ return (yield this.makeRecentQueryClick()).log({ searchUID: this.provider.getSearchUID() });
2467
+ });
2468
+ }
2469
+ makeClearRecentQueries() {
2470
+ return this.makeCustomEvent(SearchPageEvents.clearRecentQueries);
2471
+ }
2472
+ logClearRecentQueries() {
2473
+ return __awaiter(this, void 0, void 0, function* () {
2474
+ return (yield this.makeClearRecentQueries()).log({ searchUID: this.provider.getSearchUID() });
2475
+ });
2476
+ }
2477
+ makeRecentResultClick(info, identifier) {
2478
+ return this.makeCustomEvent(SearchPageEvents.recentResultClick, { info, identifier });
2479
+ }
2480
+ logRecentResultClick(info, identifier) {
2481
+ return __awaiter(this, void 0, void 0, function* () {
2482
+ return (yield this.makeRecentResultClick(info, identifier)).log({ searchUID: this.provider.getSearchUID() });
2483
+ });
2484
+ }
2485
+ makeClearRecentResults() {
2486
+ return this.makeCustomEvent(SearchPageEvents.clearRecentResults);
2487
+ }
2488
+ logClearRecentResults() {
2489
+ return __awaiter(this, void 0, void 0, function* () {
2490
+ return (yield this.makeClearRecentResults()).log({ searchUID: this.provider.getSearchUID() });
2491
+ });
2492
+ }
2493
+ makeNoResultsBack() {
2494
+ return this.makeSearchEvent(SearchPageEvents.noResultsBack);
2495
+ }
2496
+ logNoResultsBack() {
2497
+ return __awaiter(this, void 0, void 0, function* () {
2498
+ return (yield this.makeNoResultsBack()).log({ searchUID: this.provider.getSearchUID() });
2499
+ });
2500
+ }
2501
+ makeShowMoreFoldedResults(info, identifier) {
2502
+ return this.makeClickEvent(SearchPageEvents.showMoreFoldedResults, info, identifier);
2503
+ }
2504
+ logShowMoreFoldedResults(info, identifier) {
2505
+ return __awaiter(this, void 0, void 0, function* () {
2506
+ return (yield this.makeShowMoreFoldedResults(info, identifier)).log({ searchUID: this.provider.getSearchUID() });
2507
+ });
2508
+ }
2509
+ makeShowLessFoldedResults() {
2510
+ return this.makeCustomEvent(SearchPageEvents.showLessFoldedResults);
2511
+ }
2512
+ logShowLessFoldedResults() {
2513
+ return __awaiter(this, void 0, void 0, function* () {
2514
+ return (yield this.makeShowLessFoldedResults()).log({ searchUID: this.provider.getSearchUID() });
2515
+ });
2516
+ }
2517
+ makeEventDescription(preparedEvent, actionCause) {
2518
+ var _a;
2519
+ return { actionCause, customData: (_a = preparedEvent.payload) === null || _a === void 0 ? void 0 : _a.customData };
2520
+ }
2521
+ makeCustomEvent(event, metadata, eventType = CustomEventsTypes[event]) {
2522
+ return __awaiter(this, void 0, void 0, function* () {
2523
+ this.coveoAnalyticsClient.getParameters;
2524
+ const customData = Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata);
2525
+ const request = Object.assign(Object.assign({}, (yield this.getBaseEventRequest(customData))), { eventType, eventValue: event });
2526
+ const preparedEvent = yield this.coveoAnalyticsClient.makeCustomEvent(request);
2527
+ return {
2528
+ description: this.makeEventDescription(preparedEvent, event),
2529
+ log: ({ searchUID }) => preparedEvent.log({ lastSearchQueryUid: searchUID }),
2530
+ };
2531
+ });
2532
+ }
2533
+ logCustomEvent(event, metadata, eventType = CustomEventsTypes[event]) {
2534
+ return __awaiter(this, void 0, void 0, function* () {
2535
+ return (yield this.makeCustomEvent(event, metadata, eventType)).log({ searchUID: this.provider.getSearchUID() });
2536
+ });
2537
+ }
2538
+ makeCustomEventWithType(eventValue, eventType, metadata) {
2539
+ return __awaiter(this, void 0, void 0, function* () {
2540
+ const customData = Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata);
2541
+ const payload = Object.assign(Object.assign({}, (yield this.getBaseEventRequest(customData))), { eventType,
2542
+ eventValue });
2543
+ const preparedEvent = yield this.coveoAnalyticsClient.makeCustomEvent(payload);
2544
+ return {
2545
+ description: this.makeEventDescription(preparedEvent, eventValue),
2546
+ log: ({ searchUID }) => preparedEvent.log({ lastSearchQueryUid: searchUID }),
2547
+ };
2548
+ });
2549
+ }
2550
+ logCustomEventWithType(eventValue, eventType, metadata) {
2551
+ return __awaiter(this, void 0, void 0, function* () {
2552
+ return (yield this.makeCustomEventWithType(eventValue, eventType, metadata)).log({
2553
+ searchUID: this.provider.getSearchUID(),
2554
+ });
2555
+ });
2556
+ }
2557
+ logSearchEvent(event, metadata) {
2558
+ return __awaiter(this, void 0, void 0, function* () {
2559
+ return (yield this.makeSearchEvent(event, metadata)).log({ searchUID: this.provider.getSearchUID() });
2560
+ });
2561
+ }
2562
+ makeSearchEvent(event, metadata) {
2563
+ return __awaiter(this, void 0, void 0, function* () {
2564
+ const request = yield this.getBaseSearchEventRequest(event, metadata);
2565
+ const preparedEvent = yield this.coveoAnalyticsClient.makeSearchEvent(request);
2566
+ return {
2567
+ description: this.makeEventDescription(preparedEvent, event),
2568
+ log: ({ searchUID }) => preparedEvent.log({ searchQueryUid: searchUID }),
2569
+ };
2570
+ });
2571
+ }
2572
+ makeClickEvent(event, info, identifier, metadata) {
2573
+ return __awaiter(this, void 0, void 0, function* () {
2574
+ const request = Object.assign(Object.assign(Object.assign({}, info), (yield this.getBaseEventRequest(Object.assign(Object.assign({}, identifier), metadata)))), { queryPipeline: this.provider.getPipeline(), actionCause: event });
2575
+ const preparedEvent = yield this.coveoAnalyticsClient.makeClickEvent(request);
2576
+ return {
2577
+ description: this.makeEventDescription(preparedEvent, event),
2578
+ log: ({ searchUID }) => preparedEvent.log({ searchQueryUid: searchUID }),
2579
+ };
2580
+ });
2581
+ }
2582
+ logClickEvent(event, info, identifier, metadata) {
2583
+ return __awaiter(this, void 0, void 0, function* () {
2584
+ return (yield this.makeClickEvent(event, info, identifier, metadata)).log({
2585
+ searchUID: this.provider.getSearchUID(),
2586
+ });
2587
+ });
2588
+ }
2589
+ getBaseSearchEventRequest(event, metadata) {
2590
+ return __awaiter(this, void 0, void 0, function* () {
2591
+ return Object.assign(Object.assign(Object.assign({}, (yield this.getBaseEventRequest(metadata))), this.provider.getSearchEventRequestPayload()), { queryPipeline: this.provider.getPipeline(), actionCause: event });
2592
+ });
2593
+ }
2594
+ getBaseEventRequest(metadata) {
2595
+ return __awaiter(this, void 0, void 0, function* () {
2596
+ const customData = Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata);
2597
+ return Object.assign(Object.assign(Object.assign({}, this.getOrigins()), this.getSplitTestRun()), { customData, language: this.provider.getLanguage(), facetState: this.provider.getFacetState ? this.provider.getFacetState() : [], anonymous: this.provider.getIsAnonymous(), clientId: yield this.getClientId() });
2598
+ });
2599
+ }
2600
+ getOrigins() {
2601
+ var _a, _b;
2602
+ return {
2603
+ originContext: (_b = (_a = this.provider).getOriginContext) === null || _b === void 0 ? void 0 : _b.call(_a),
2604
+ originLevel1: this.provider.getOriginLevel1(),
2605
+ originLevel2: this.provider.getOriginLevel2(),
2606
+ originLevel3: this.provider.getOriginLevel3(),
2607
+ };
2608
+ }
2609
+ getClientId() {
2610
+ return this.coveoAnalyticsClient instanceof CoveoAnalyticsClient
2611
+ ? this.coveoAnalyticsClient.getCurrentVisitorId()
2612
+ : undefined;
2613
+ }
2614
+ getSplitTestRun() {
2615
+ const splitTestRunName = this.provider.getSplitTestRunName ? this.provider.getSplitTestRunName() : '';
2616
+ const splitTestRunVersion = this.provider.getSplitTestRunVersion ? this.provider.getSplitTestRunVersion() : '';
2617
+ return Object.assign(Object.assign({}, (splitTestRunName && { splitTestRunName })), (splitTestRunVersion && { splitTestRunVersion }));
2618
+ }
2619
+ makeLikeGeneratedAnswer(metadata) {
2620
+ return this.makeCustomEvent(SearchPageEvents.likeGeneratedAnswer, metadata);
2621
+ }
2622
+ logLikeGeneratedAnswer(metadata) {
2623
+ return __awaiter(this, void 0, void 0, function* () {
2624
+ return (yield this.makeLikeGeneratedAnswer(metadata)).log({ searchUID: this.provider.getSearchUID() });
2625
+ });
2626
+ }
2627
+ makeDislikeGeneratedAnswer(metadata) {
2628
+ return this.makeCustomEvent(SearchPageEvents.dislikeGeneratedAnswer, metadata);
2629
+ }
2630
+ logDislikeGeneratedAnswer(metadata) {
2631
+ return __awaiter(this, void 0, void 0, function* () {
2632
+ return (yield this.makeDislikeGeneratedAnswer(metadata)).log({ searchUID: this.provider.getSearchUID() });
2633
+ });
2634
+ }
2635
+ makeOpenGeneratedAnswerSource(metadata) {
2636
+ return this.makeCustomEvent(SearchPageEvents.openGeneratedAnswerSource, metadata);
2637
+ }
2638
+ logOpenGeneratedAnswerSource(metadata) {
2639
+ return __awaiter(this, void 0, void 0, function* () {
2640
+ return (yield this.makeOpenGeneratedAnswerSource(metadata)).log({
2641
+ searchUID: this.provider.getSearchUID(),
2642
+ });
2643
+ });
2644
+ }
2645
+ makeRetryGeneratedAnswer() {
2646
+ return this.makeSearchEvent(SearchPageEvents.retryGeneratedAnswer);
2647
+ }
2648
+ logRetryGeneratedAnswer() {
2649
+ return __awaiter(this, void 0, void 0, function* () {
2650
+ return (yield this.makeRetryGeneratedAnswer()).log({ searchUID: this.provider.getSearchUID() });
2651
+ });
2652
+ }
2653
+ makeGeneratedAnswerStreamEnd(metadata) {
2654
+ return this.makeCustomEvent(SearchPageEvents.generatedAnswerStreamEnd, metadata);
2655
+ }
2656
+ logGeneratedAnswerStreamEnd(metadata) {
2657
+ return __awaiter(this, void 0, void 0, function* () {
2658
+ return (yield this.makeGeneratedAnswerStreamEnd(metadata)).log({ searchUID: this.provider.getSearchUID() });
2659
+ });
2660
+ }
2661
+ }
2662
+
2663
+ const SVCPluginEventTypes = Object.assign({}, BasePluginEventTypes);
2664
+ const allSVCEventTypes = Object.keys(SVCPluginEventTypes).map((key) => SVCPluginEventTypes[key]);
2665
+ class SVCPlugin extends BasePlugin {
2666
+ constructor({ client, uuidGenerator = v4 }) {
2667
+ super({ client, uuidGenerator });
2668
+ this.ticket = {};
2669
+ }
2670
+ getApi(name) {
2671
+ const superCall = super.getApi(name);
2672
+ if (superCall !== null)
2673
+ return superCall;
2674
+ switch (name) {
2675
+ case 'setTicket':
2676
+ return this.setTicket;
2677
+ default:
2678
+ return null;
2679
+ }
2680
+ }
2681
+ addHooks() {
2682
+ this.addHooksForEvent();
2683
+ this.addHooksForPageView();
2684
+ this.addHooksForSVCEvents();
2685
+ }
2686
+ setTicket(ticket) {
2687
+ this.ticket = ticket;
2688
+ }
2689
+ clearPluginData() {
2690
+ this.ticket = {};
2691
+ }
2692
+ addHooksForSVCEvents() {
2693
+ this.client.registerBeforeSendEventHook((eventType, ...[payload]) => {
2694
+ return allSVCEventTypes.indexOf(eventType) !== -1 ? this.addSVCDataToPayload(eventType, payload) : payload;
2695
+ });
2696
+ this.client.registerAfterSendEventHook((eventType, ...[payload]) => {
2697
+ if (allSVCEventTypes.indexOf(eventType) !== -1) {
2698
+ this.updateLocationInformation(eventType, payload);
2699
+ }
2700
+ return payload;
2701
+ });
2702
+ }
2703
+ addHooksForPageView() {
2704
+ this.client.addEventTypeMapping(SVCPluginEventTypes.pageview, {
2705
+ newEventType: EventType.collect,
2706
+ variableLengthArgumentsNames: ['page'],
2707
+ addVisitorIdParameter: true,
2708
+ usesMeasurementProtocol: true,
2709
+ });
2710
+ }
2711
+ addHooksForEvent() {
2712
+ this.client.addEventTypeMapping(SVCPluginEventTypes.event, {
2713
+ newEventType: EventType.collect,
2714
+ variableLengthArgumentsNames: ['eventCategory', 'eventAction', 'eventLabel', 'eventValue'],
2715
+ addVisitorIdParameter: true,
2716
+ usesMeasurementProtocol: true,
2717
+ });
2718
+ }
2719
+ addSVCDataToPayload(eventType, payload) {
2720
+ var _a;
2721
+ const svcPayload = Object.assign(Object.assign(Object.assign(Object.assign({}, this.getLocationInformation(eventType, payload)), this.getDefaultContextInformation(eventType)), (this.action ? { svcAction: this.action } : {})), (Object.keys((_a = this.actionData) !== null && _a !== void 0 ? _a : {}).length > 0 ? { svcActionData: this.actionData } : {}));
2722
+ const ticketPayload = this.getTicketPayload();
2723
+ this.clearData();
2724
+ return Object.assign(Object.assign(Object.assign({}, ticketPayload), svcPayload), payload);
2725
+ }
2726
+ getTicketPayload() {
2727
+ return convertTicketToMeasurementProtocol(this.ticket);
2728
+ }
2729
+ }
2730
+ SVCPlugin.Id = 'svc';
2731
+
2732
+ var CaseAssistEvents;
2733
+ (function (CaseAssistEvents) {
2734
+ CaseAssistEvents["click"] = "click";
2735
+ CaseAssistEvents["flowStart"] = "flowStart";
2736
+ })(CaseAssistEvents || (CaseAssistEvents = {}));
2737
+ var CaseAssistActions;
2738
+ (function (CaseAssistActions) {
2739
+ CaseAssistActions["enterInterface"] = "ticket_create_start";
2740
+ CaseAssistActions["fieldUpdate"] = "ticket_field_update";
2741
+ CaseAssistActions["fieldSuggestionClick"] = "ticket_classification_click";
2742
+ CaseAssistActions["suggestionClick"] = "suggestion_click";
2743
+ CaseAssistActions["suggestionRate"] = "suggestion_rate";
2744
+ CaseAssistActions["nextCaseStep"] = "ticket_next_stage";
2745
+ CaseAssistActions["caseCancelled"] = "ticket_cancel";
2746
+ CaseAssistActions["caseSolved"] = "ticket_cancel";
2747
+ CaseAssistActions["caseCreated"] = "ticket_create";
2748
+ })(CaseAssistActions || (CaseAssistActions = {}));
2749
+ var CaseCancelledReasons;
2750
+ (function (CaseCancelledReasons) {
2751
+ CaseCancelledReasons["quit"] = "Quit";
2752
+ CaseCancelledReasons["solved"] = "Solved";
2753
+ })(CaseCancelledReasons || (CaseCancelledReasons = {}));
2754
+
2755
+ class CaseAssistClient {
2756
+ constructor(options, provider) {
2757
+ var _a;
2758
+ this.options = options;
2759
+ this.provider = provider;
2760
+ const analyticsEnabled = ((_a = options.enableAnalytics) !== null && _a !== void 0 ? _a : true) && !doNotTrack();
2761
+ this.coveoAnalyticsClient = analyticsEnabled ? new CoveoAnalyticsClient(options) : new NoopAnalytics();
2762
+ this.svc = new SVCPlugin({ client: this.coveoAnalyticsClient });
2763
+ }
2764
+ disable() {
2765
+ if (this.coveoAnalyticsClient instanceof CoveoAnalyticsClient) {
2766
+ this.coveoAnalyticsClient.clear();
2767
+ }
2768
+ this.coveoAnalyticsClient = new NoopAnalytics();
2769
+ this.svc = new SVCPlugin({ client: this.coveoAnalyticsClient });
2770
+ }
2771
+ enable() {
2772
+ this.coveoAnalyticsClient = new CoveoAnalyticsClient(this.options);
2773
+ this.svc = new SVCPlugin({ client: this.coveoAnalyticsClient });
2774
+ }
2775
+ logEnterInterface(meta) {
2776
+ this.svc.setAction(CaseAssistActions.enterInterface);
2777
+ this.svc.setTicket(meta.ticket);
2778
+ return this.sendFlowStartEvent();
2779
+ }
2780
+ logUpdateCaseField(meta) {
2781
+ this.svc.setAction(CaseAssistActions.fieldUpdate, {
2782
+ fieldName: meta.fieldName,
2783
+ });
2784
+ this.svc.setTicket(meta.ticket);
2785
+ return this.sendClickEvent();
2786
+ }
2787
+ logSelectFieldSuggestion(meta) {
2788
+ this.svc.setAction(CaseAssistActions.fieldSuggestionClick, meta.suggestion);
2789
+ this.svc.setTicket(meta.ticket);
2790
+ return this.sendClickEvent();
2791
+ }
2792
+ logSelectDocumentSuggestion(meta) {
2793
+ this.svc.setAction(CaseAssistActions.suggestionClick, meta.suggestion);
2794
+ this.svc.setTicket(meta.ticket);
2795
+ return this.sendClickEvent();
2796
+ }
2797
+ logRateDocumentSuggestion(meta) {
2798
+ this.svc.setAction(CaseAssistActions.suggestionRate, Object.assign({ rate: meta.rating }, meta.suggestion));
2799
+ this.svc.setTicket(meta.ticket);
2800
+ return this.sendClickEvent();
2801
+ }
2802
+ logMoveToNextCaseStep(meta) {
2803
+ this.svc.setAction(CaseAssistActions.nextCaseStep, {
2804
+ stage: meta === null || meta === void 0 ? void 0 : meta.stage,
2805
+ });
2806
+ this.svc.setTicket(meta.ticket);
2807
+ return this.sendClickEvent();
2808
+ }
2809
+ logCaseCancelled(meta) {
2810
+ this.svc.setAction(CaseAssistActions.caseCancelled, {
2811
+ reason: CaseCancelledReasons.quit,
2812
+ });
2813
+ this.svc.setTicket(meta.ticket);
2814
+ return this.sendClickEvent();
2815
+ }
2816
+ logCaseSolved(meta) {
2817
+ this.svc.setAction(CaseAssistActions.caseSolved, {
2818
+ reason: CaseCancelledReasons.solved,
2819
+ });
2820
+ this.svc.setTicket(meta.ticket);
2821
+ return this.sendClickEvent();
2822
+ }
2823
+ logCaseCreated(meta) {
2824
+ this.svc.setAction(CaseAssistActions.caseCreated);
2825
+ this.svc.setTicket(meta.ticket);
2826
+ return this.sendClickEvent();
2827
+ }
2828
+ sendFlowStartEvent() {
2829
+ return this.coveoAnalyticsClient.sendEvent('event', 'svc', CaseAssistEvents.flowStart, this.provider
2830
+ ? {
2831
+ searchHub: this.provider.getOriginLevel1(),
2832
+ }
2833
+ : null);
2834
+ }
2835
+ sendClickEvent() {
2836
+ return this.coveoAnalyticsClient.sendEvent('event', 'svc', CaseAssistEvents.click, this.provider
2837
+ ? {
2838
+ searchHub: this.provider.getOriginLevel1(),
2839
+ }
2840
+ : null);
2841
+ }
2842
+ }
2843
+
2844
+ const extractContextFromMetadata = (meta) => {
2845
+ const context = {};
2846
+ if (meta.caseContext) {
2847
+ Object.keys(meta.caseContext).forEach((contextKey) => {
2848
+ var _a;
2849
+ const value = (_a = meta.caseContext) === null || _a === void 0 ? void 0 : _a[contextKey];
2850
+ if (value) {
2851
+ const keyToBeSent = `context_${contextKey}`;
2852
+ context[keyToBeSent] = value;
2853
+ }
2854
+ });
2855
+ }
2856
+ return context;
2857
+ };
2858
+ const generateMetadataToSend = (metadata, includeContext = true) => {
2859
+ const { caseContext, caseId, caseNumber } = metadata, metadataWithoutContext = __rest(metadata, ["caseContext", "caseId", "caseNumber"]);
2860
+ const context = extractContextFromMetadata(metadata);
2861
+ return Object.assign(Object.assign(Object.assign({ CaseId: caseId, CaseNumber: caseNumber }, metadataWithoutContext), (!!context.context_Case_Subject && { CaseSubject: context.context_Case_Subject })), (includeContext && context));
2862
+ };
2863
+ class CoveoInsightClient {
2864
+ constructor(opts, provider) {
2865
+ this.opts = opts;
2866
+ this.provider = provider;
2867
+ const shouldDisableAnalytics = opts.enableAnalytics === false || doNotTrack();
2868
+ this.coveoAnalyticsClient = shouldDisableAnalytics ? new NoopAnalytics() : new CoveoAnalyticsClient(opts);
2869
+ }
2870
+ disable() {
2871
+ if (this.coveoAnalyticsClient instanceof CoveoAnalyticsClient) {
2872
+ this.coveoAnalyticsClient.clear();
2873
+ }
2874
+ this.coveoAnalyticsClient = new NoopAnalytics();
2875
+ }
2876
+ enable() {
2877
+ this.coveoAnalyticsClient = new CoveoAnalyticsClient(this.opts);
2878
+ }
2879
+ logInterfaceLoad(metadata) {
2880
+ if (metadata) {
2881
+ const metadataToSend = generateMetadataToSend(metadata);
2882
+ return this.logSearchEvent(SearchPageEvents.interfaceLoad, metadataToSend);
2883
+ }
2884
+ return this.logSearchEvent(SearchPageEvents.interfaceLoad);
2885
+ }
2886
+ logInterfaceChange(metadata) {
2887
+ const metadataToSend = generateMetadataToSend(metadata);
2888
+ return this.logSearchEvent(SearchPageEvents.interfaceChange, metadataToSend);
2889
+ }
2890
+ logStaticFilterDeselect(metadata) {
2891
+ const metadataToSend = generateMetadataToSend(metadata);
2892
+ return this.logSearchEvent(SearchPageEvents.staticFilterDeselect, metadataToSend);
2893
+ }
2894
+ logFetchMoreResults(metadata) {
2895
+ if (metadata) {
2896
+ const metadataToSend = generateMetadataToSend(metadata);
2897
+ return this.logCustomEvent(SearchPageEvents.pagerScrolling, Object.assign(Object.assign({}, metadataToSend), { type: 'getMoreResults' }));
2898
+ }
2899
+ return this.logCustomEvent(SearchPageEvents.pagerScrolling, { type: 'getMoreResults' });
2900
+ }
2901
+ logBreadcrumbFacet(metadata) {
2902
+ const metadataToSend = generateMetadataToSend(metadata);
2903
+ return this.logSearchEvent(SearchPageEvents.breadcrumbFacet, metadataToSend);
2904
+ }
2905
+ logBreadcrumbResetAll(metadata) {
2906
+ if (metadata) {
2907
+ const metadataToSend = generateMetadataToSend(metadata);
2908
+ return this.logSearchEvent(SearchPageEvents.breadcrumbResetAll, metadataToSend);
2909
+ }
2910
+ return this.logSearchEvent(SearchPageEvents.breadcrumbResetAll);
2911
+ }
2912
+ logFacetSelect(metadata) {
2913
+ const metadataToSend = generateMetadataToSend(metadata);
2914
+ return this.logSearchEvent(SearchPageEvents.facetSelect, metadataToSend);
2915
+ }
2916
+ logFacetExclude(metadata) {
2917
+ const metadataToSend = generateMetadataToSend(metadata);
2918
+ return this.logSearchEvent(SearchPageEvents.facetExclude, metadataToSend);
2919
+ }
2920
+ logFacetDeselect(metadata) {
2921
+ const metadataToSend = generateMetadataToSend(metadata);
2922
+ return this.logSearchEvent(SearchPageEvents.facetDeselect, metadataToSend);
2923
+ }
2924
+ logFacetUpdateSort(metadata) {
2925
+ const metadataToSend = generateMetadataToSend(metadata);
2926
+ return this.logSearchEvent(SearchPageEvents.facetUpdateSort, metadataToSend);
2927
+ }
2928
+ logFacetClearAll(metadata) {
2929
+ const metadataToSend = generateMetadataToSend(metadata);
2930
+ return this.logSearchEvent(SearchPageEvents.facetClearAll, metadataToSend);
2931
+ }
2932
+ logFacetShowMore(metadata) {
2933
+ const metadataToSend = generateMetadataToSend(metadata, false);
2934
+ return this.logCustomEvent(SearchPageEvents.facetShowMore, metadataToSend);
2935
+ }
2936
+ logFacetShowLess(metadata) {
2937
+ const metadataToSend = generateMetadataToSend(metadata, false);
2938
+ return this.logCustomEvent(SearchPageEvents.facetShowLess, metadataToSend);
2939
+ }
2940
+ logQueryError(metadata) {
2941
+ const metadataToSend = generateMetadataToSend(metadata, false);
2942
+ return this.logCustomEvent(SearchPageEvents.queryError, metadataToSend);
2943
+ }
2944
+ logPagerNumber(metadata) {
2945
+ const metadataToSend = generateMetadataToSend(metadata, false);
2946
+ return this.logCustomEvent(SearchPageEvents.pagerNumber, metadataToSend);
2947
+ }
2948
+ logPagerNext(metadata) {
2949
+ const metadataToSend = generateMetadataToSend(metadata, false);
2950
+ return this.logCustomEvent(SearchPageEvents.pagerNext, metadataToSend);
2951
+ }
2952
+ logPagerPrevious(metadata) {
2953
+ const metadataToSend = generateMetadataToSend(metadata, false);
2954
+ return this.logCustomEvent(SearchPageEvents.pagerPrevious, metadataToSend);
2955
+ }
2956
+ logDidYouMeanAutomatic(metadata) {
2957
+ if (metadata) {
2958
+ const metadataToSend = generateMetadataToSend(metadata);
2959
+ return this.logSearchEvent(SearchPageEvents.didyoumeanAutomatic, metadataToSend);
2960
+ }
2961
+ return this.logSearchEvent(SearchPageEvents.didyoumeanAutomatic);
2962
+ }
2963
+ logDidYouMeanClick(metadata) {
2964
+ if (metadata) {
2965
+ const metadataToSend = generateMetadataToSend(metadata);
2966
+ return this.logSearchEvent(SearchPageEvents.didyoumeanClick, metadataToSend);
2967
+ }
2968
+ return this.logSearchEvent(SearchPageEvents.didyoumeanClick);
2969
+ }
2970
+ logResultsSort(metadata) {
2971
+ const metadataToSend = generateMetadataToSend(metadata);
2972
+ return this.logSearchEvent(SearchPageEvents.resultsSort, metadataToSend);
2973
+ }
2974
+ logSearchboxSubmit(metadata) {
2975
+ if (metadata) {
2976
+ const metadataToSend = generateMetadataToSend(metadata);
2977
+ return this.logSearchEvent(SearchPageEvents.searchboxSubmit, metadataToSend);
2978
+ }
2979
+ return this.logSearchEvent(SearchPageEvents.searchboxSubmit);
2980
+ }
2981
+ logContextChanged(metadata) {
2982
+ const metadataToSend = generateMetadataToSend(metadata);
2983
+ return this.logSearchEvent(InsightEvents.contextChanged, metadataToSend);
2984
+ }
2985
+ logExpandToFullUI(metadata) {
2986
+ const metadataToSend = generateMetadataToSend(metadata);
2987
+ return this.logCustomEvent(InsightEvents.expandToFullUI, metadataToSend);
2988
+ }
2989
+ logOpenUserActions(metadata) {
2990
+ const metadataToSend = generateMetadataToSend(metadata, false);
2991
+ return this.logCustomEvent(InsightEvents.openUserActions, metadataToSend);
2992
+ }
2993
+ logShowPrecedingSessions(metadata) {
2994
+ const metadataToSend = generateMetadataToSend(metadata, false);
2995
+ return this.logCustomEvent(InsightEvents.showPrecedingSessions, metadataToSend);
2996
+ }
2997
+ logShowFollowingSessions(metadata) {
2998
+ const metadataToSend = generateMetadataToSend(metadata, false);
2999
+ return this.logCustomEvent(InsightEvents.showFollowingSessions, metadataToSend);
3000
+ }
3001
+ logViewedDocumentClick(document, metadata) {
3002
+ return this.logCustomEvent(InsightEvents.clickViewedDocument, Object.assign(Object.assign({}, generateMetadataToSend(metadata, false)), { document }));
3003
+ }
3004
+ logPageViewClick(pageView, metadata) {
3005
+ return this.logCustomEvent(InsightEvents.clickPageView, Object.assign(Object.assign({}, generateMetadataToSend(metadata, false)), { pageView }));
3006
+ }
3007
+ logDocumentOpen(info, identifier, metadata) {
3008
+ return this.logClickEvent(SearchPageEvents.documentOpen, info, identifier, metadata ? generateMetadataToSend(metadata, false) : undefined);
3009
+ }
3010
+ logCopyToClipboard(info, identifier, metadata) {
3011
+ return this.logClickEvent(SearchPageEvents.copyToClipboard, info, identifier, metadata ? generateMetadataToSend(metadata, false) : undefined);
3012
+ }
3013
+ logCaseSendEmail(info, identifier, metadata) {
3014
+ return this.logClickEvent(SearchPageEvents.caseSendEmail, info, identifier, metadata ? generateMetadataToSend(metadata, false) : undefined);
3015
+ }
3016
+ logFeedItemTextPost(info, identifier, metadata) {
3017
+ return this.logClickEvent(SearchPageEvents.feedItemTextPost, info, identifier, metadata ? generateMetadataToSend(metadata, false) : undefined);
3018
+ }
3019
+ logDocumentQuickview(info, identifier, caseMetadata) {
3020
+ const metadata = {
3021
+ documentTitle: info.documentTitle,
3022
+ documentURL: info.documentUrl,
3023
+ };
3024
+ return this.logClickEvent(SearchPageEvents.documentQuickview, info, identifier, caseMetadata ? Object.assign(Object.assign({}, generateMetadataToSend(caseMetadata, false)), metadata) : metadata);
3025
+ }
3026
+ logCaseAttach(info, identifier, caseMetadata) {
3027
+ const metadata = {
3028
+ documentTitle: info.documentTitle,
3029
+ documentURL: info.documentUrl,
3030
+ resultUriHash: info.documentUriHash,
3031
+ };
3032
+ return this.logClickEvent(SearchPageEvents.caseAttach, info, identifier, caseMetadata ? Object.assign(Object.assign({}, generateMetadataToSend(caseMetadata, false)), metadata) : metadata);
3033
+ }
3034
+ logCaseDetach(resultUriHash, metadata) {
3035
+ return this.logCustomEvent(SearchPageEvents.caseDetach, metadata ? Object.assign(Object.assign({}, generateMetadataToSend(metadata, false)), { resultUriHash }) : { resultUriHash });
3036
+ }
3037
+ logLikeSmartSnippet(metadata) {
3038
+ return this.logCustomEvent(SearchPageEvents.likeSmartSnippet, metadata ? generateMetadataToSend(metadata, false) : undefined);
3039
+ }
3040
+ logDislikeSmartSnippet(metadata) {
3041
+ return this.logCustomEvent(SearchPageEvents.dislikeSmartSnippet, metadata ? generateMetadataToSend(metadata, false) : undefined);
3042
+ }
3043
+ logExpandSmartSnippet(metadata) {
3044
+ return this.logCustomEvent(SearchPageEvents.expandSmartSnippet, metadata ? generateMetadataToSend(metadata, false) : undefined);
3045
+ }
3046
+ logCollapseSmartSnippet(metadata) {
3047
+ return this.logCustomEvent(SearchPageEvents.collapseSmartSnippet, metadata ? generateMetadataToSend(metadata, false) : undefined);
3048
+ }
3049
+ logOpenSmartSnippetFeedbackModal(metadata) {
3050
+ return this.logCustomEvent(SearchPageEvents.openSmartSnippetFeedbackModal, metadata ? generateMetadataToSend(metadata, false) : undefined);
3051
+ }
3052
+ logCloseSmartSnippetFeedbackModal(metadata) {
3053
+ return this.logCustomEvent(SearchPageEvents.closeSmartSnippetFeedbackModal, metadata ? generateMetadataToSend(metadata, false) : undefined);
3054
+ }
3055
+ logSmartSnippetFeedbackReason(reason, details, metadata) {
3056
+ return this.logCustomEvent(SearchPageEvents.sendSmartSnippetReason, metadata ? Object.assign(Object.assign({}, generateMetadataToSend(metadata, false)), { reason, details }) : { reason, details });
3057
+ }
3058
+ logExpandSmartSnippetSuggestion(snippet, metadata) {
3059
+ const snippetMetadata = 'documentId' in snippet ? snippet : { documentId: snippet };
3060
+ return this.logCustomEvent(SearchPageEvents.expandSmartSnippetSuggestion, metadata ? Object.assign(Object.assign({}, generateMetadataToSend(metadata, false)), snippetMetadata) : snippetMetadata);
3061
+ }
3062
+ logCollapseSmartSnippetSuggestion(snippet, metadata) {
3063
+ const snippetMetadata = 'documentId' in snippet ? snippet : { documentId: snippet };
3064
+ return this.logCustomEvent(SearchPageEvents.collapseSmartSnippetSuggestion, metadata ? Object.assign(Object.assign({}, generateMetadataToSend(metadata, false)), snippetMetadata) : snippetMetadata);
3065
+ }
3066
+ logOpenSmartSnippetSource(info, identifier, metadata) {
3067
+ return this.logClickEvent(SearchPageEvents.openSmartSnippetSource, info, identifier, metadata ? generateMetadataToSend(metadata, false) : undefined);
3068
+ }
3069
+ logOpenSmartSnippetSuggestionSource(info, snippet, metadata) {
3070
+ return this.logClickEvent(SearchPageEvents.openSmartSnippetSuggestionSource, info, { contentIDKey: snippet.documentId.contentIdKey, contentIDValue: snippet.documentId.contentIdValue }, metadata ? Object.assign(Object.assign({}, generateMetadataToSend(metadata, false)), snippet) : snippet);
3071
+ }
3072
+ logOpenSmartSnippetInlineLink(info, identifierAndLink, metadata) {
3073
+ return this.logClickEvent(SearchPageEvents.openSmartSnippetInlineLink, info, { contentIDKey: identifierAndLink.contentIDKey, contentIDValue: identifierAndLink.contentIDValue }, metadata ? Object.assign(Object.assign({}, generateMetadataToSend(metadata, false)), identifierAndLink) : identifierAndLink);
3074
+ }
3075
+ logOpenSmartSnippetSuggestionInlineLink(info, snippetAndLink, metadata) {
3076
+ return this.logClickEvent(SearchPageEvents.openSmartSnippetSuggestionInlineLink, info, {
3077
+ contentIDKey: snippetAndLink.documentId.contentIdKey,
3078
+ contentIDValue: snippetAndLink.documentId.contentIdValue,
3079
+ }, metadata ? Object.assign(Object.assign({}, generateMetadataToSend(metadata, false)), snippetAndLink) : snippetAndLink);
3080
+ }
3081
+ logCustomEvent(event, metadata) {
3082
+ return __awaiter(this, void 0, void 0, function* () {
3083
+ const customData = Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata);
3084
+ const payload = Object.assign(Object.assign({}, (yield this.getBaseCustomEventRequest(customData))), { eventType: CustomEventsTypes[event], eventValue: event });
3085
+ return this.coveoAnalyticsClient.sendCustomEvent(payload);
3086
+ });
3087
+ }
3088
+ logSearchEvent(event, metadata) {
3089
+ return __awaiter(this, void 0, void 0, function* () {
3090
+ return this.coveoAnalyticsClient.sendSearchEvent(yield this.getBaseSearchEventRequest(event, metadata));
3091
+ });
3092
+ }
3093
+ logClickEvent(event, info, identifier, metadata) {
3094
+ return __awaiter(this, void 0, void 0, function* () {
3095
+ const payload = Object.assign(Object.assign(Object.assign({}, info), (yield this.getBaseEventRequest(Object.assign(Object.assign({}, identifier), metadata)))), { searchQueryUid: this.provider.getSearchUID(), queryPipeline: this.provider.getPipeline(), actionCause: event });
3096
+ return this.coveoAnalyticsClient.sendClickEvent(payload);
3097
+ });
3098
+ }
3099
+ logShowMoreFoldedResults(info, identifier, metadata) {
3100
+ return __awaiter(this, void 0, void 0, function* () {
3101
+ return this.logClickEvent(SearchPageEvents.showMoreFoldedResults, info, identifier, metadata ? generateMetadataToSend(metadata, false) : undefined);
3102
+ });
3103
+ }
3104
+ logShowLessFoldedResults(metadata) {
3105
+ return __awaiter(this, void 0, void 0, function* () {
3106
+ return this.logCustomEvent(SearchPageEvents.showLessFoldedResults, metadata ? generateMetadataToSend(metadata, false) : undefined);
3107
+ });
3108
+ }
3109
+ getBaseCustomEventRequest(metadata) {
3110
+ return __awaiter(this, void 0, void 0, function* () {
3111
+ return Object.assign(Object.assign({}, (yield this.getBaseEventRequest(metadata))), { lastSearchQueryUid: this.provider.getSearchUID() });
3112
+ });
3113
+ }
3114
+ getBaseSearchEventRequest(event, metadata) {
3115
+ return __awaiter(this, void 0, void 0, function* () {
3116
+ return Object.assign(Object.assign(Object.assign({}, (yield this.getBaseEventRequest(metadata))), this.provider.getSearchEventRequestPayload()), { searchQueryUid: this.provider.getSearchUID(), queryPipeline: this.provider.getPipeline(), actionCause: event });
3117
+ });
3118
+ }
3119
+ getBaseEventRequest(metadata) {
3120
+ return __awaiter(this, void 0, void 0, function* () {
3121
+ const customData = Object.assign(Object.assign({}, this.provider.getBaseMetadata()), metadata);
3122
+ return Object.assign(Object.assign({}, this.getOrigins()), { customData, language: this.provider.getLanguage(), facetState: this.provider.getFacetState ? this.provider.getFacetState() : [], anonymous: this.provider.getIsAnonymous(), clientId: yield this.getClientId() });
3123
+ });
3124
+ }
3125
+ getOrigins() {
3126
+ var _a, _b;
3127
+ return {
3128
+ originContext: (_b = (_a = this.provider).getOriginContext) === null || _b === void 0 ? void 0 : _b.call(_a),
3129
+ originLevel1: this.provider.getOriginLevel1(),
3130
+ originLevel2: this.provider.getOriginLevel2(),
3131
+ originLevel3: this.provider.getOriginLevel3(),
3132
+ };
3133
+ }
3134
+ getClientId() {
3135
+ return this.coveoAnalyticsClient instanceof CoveoAnalyticsClient
3136
+ ? this.coveoAnalyticsClient.getCurrentVisitorId()
3137
+ : undefined;
3138
+ }
3139
+ }
3140
+
3141
+ export { CaseAssistClient, CoveoAnalyticsClient, CoveoInsightClient, CoveoSearchPageClient, history };