@cleartrip/ct-platform-utils 3.18.1-beta.7 → 3.18.1

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.
@@ -1,1150 +1,2 @@
1
- 'use strict';
2
-
3
- var tslib = require('tslib');
4
- var uuid = require('uuid');
5
- var ctPlatformConstants = require('@cleartrip/ct-platform-constants');
6
- var UAParser = require('ua-parser-js');
7
- var ctPlatformTypes = require('@cleartrip/ct-platform-types');
8
-
9
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
-
11
- var UAParser__default = /*#__PURE__*/_interopDefault(UAParser);
12
-
13
- var urlJoin = function () {
14
- var parts = [];
15
- for (var _i = 0; _i < arguments.length; _i++) {
16
- parts[_i] = arguments[_i];
17
- }
18
- var trimmedParts = parts.map(function (part) { return part.trim().replace(/^[/]+/, ''); });
19
- var joinedParts = trimmedParts.join('/');
20
- joinedParts = joinedParts.replace(/\/\?/g, '?');
21
- return joinedParts;
22
- };
23
- var getApiDomain = function () {
24
- var domain = typeof window !== 'undefined' ? window.location.hostname : '';
25
- console.log('API_BASE domain', domain);
26
- switch (domain) {
27
- case 'localhost':
28
- case '0.0.0.0':
29
- case 'qa2new.cleartrip.com':
30
- return 'https://qa2new.cleartrip.com';
31
- case 'qa2.cleartrip.com':
32
- return 'https://qa2.cleartrip.com';
33
- case 'qa3new.cleartrip.com':
34
- return 'https://qa3new.cleartrip.com';
35
- case 'www.cleartrip.com':
36
- default:
37
- return 'https://www.cleartrip.com';
38
- }
39
- };
40
- var getNestedValue = function (data, path) {
41
- var reducerFunction = function (prev, current) {
42
- return prev && prev[current] ? prev[current] : null;
43
- };
44
- return path.reduce(reducerFunction, data);
45
- };
46
- var path = function (p, o) {
47
- return p.reduce(function (prev, curr) {
48
- return prev && prev[curr] ? prev[curr] : null;
49
- }, o);
50
- };
51
- var MULTI_SPACE = /\s\s+/g;
52
- var isEmpty = function (obj) {
53
- if (obj instanceof Date) {
54
- return false;
55
- }
56
- if (obj == null) {
57
- return true;
58
- }
59
- var isNumber = function (value) {
60
- return Object.prototype.toString.call(value) === '[object Number]';
61
- };
62
- var isNaN = function (value) { return isNumber(value) && value.toString() === 'NaN'; };
63
- if (isNumber(obj)) {
64
- return isNaN(obj);
65
- }
66
- if (obj.length > 0) {
67
- return false;
68
- }
69
- if (obj.length === 0) {
70
- return true;
71
- }
72
- if (typeof obj !== 'object') {
73
- return true;
74
- }
75
- var keys = Object.keys(obj);
76
- for (var i = 0, key = keys[i]; i < keys.length; i += 1) {
77
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
78
- return false;
79
- }
80
- }
81
- return true;
82
- };
83
- var isHTMLInputElement = function (ref) {
84
- return (typeof ref === 'object' &&
85
- ref !== null &&
86
- 'value' in ref &&
87
- ref instanceof HTMLInputElement);
88
- };
89
- var isNumeric = function (value) {
90
- return /^[0-9]*$/.test(value);
91
- };
92
- var getCurrentUrl = typeof window !== 'undefined' ? window.location.href : '';
93
- var getQueryParam = function (queryParam) {
94
- if (isServer()) {
95
- return '';
96
- }
97
- var urlParams = new URLSearchParams(window.location.search);
98
- return urlParams.get(queryParam);
99
- };
100
- var getCurrentPathName = function () {
101
- return typeof window !== 'undefined'
102
- ? (window.location.pathname + window.location.search).slice(1)
103
- : '';
104
- };
105
- var getHeightFromImgUrl = function (url) {
106
- if (!url) {
107
- return;
108
- }
109
- var regex = /h_(\d+)[,\/]/;
110
- var match = url.match(regex);
111
- if (match && match[1]) {
112
- return parseInt(match[1], 10);
113
- }
114
- return;
115
- };
116
- var getWidthFromImgUrl = function (url) {
117
- if (!url) {
118
- return;
119
- }
120
- var regex = /w_(\d+)[,\/]/;
121
- var match = url.match(regex);
122
- if (match && match[1]) {
123
- return parseInt(match[1], 10);
124
- }
125
- return;
126
- };
127
- var isServer = function () {
128
- return typeof window === 'undefined' || !window;
129
- };
130
- function getCookie(name, customCookie) {
131
- var _cookie = customCookie || getNestedValue(document, ['cookie']);
132
- if (_cookie) {
133
- var nameEQ = name + '=';
134
- var ca = _cookie.split(';');
135
- for (var i = 0; i < ca.length; i++) {
136
- var c = ca[i];
137
- while (c.charAt(0) == ' ')
138
- c = c.substring(1, c.length);
139
- if (c.indexOf(nameEQ) == 0)
140
- return c.substring(nameEQ.length, c.length);
141
- }
142
- return '';
143
- }
144
- else {
145
- return '';
146
- }
147
- }
148
- var getDimensionFromImageUrl = function (url) {
149
- if (url === void 0) { url = ''; }
150
- var height = getHeightFromImgUrl(url) || 0;
151
- var width = getWidthFromImgUrl(url) || 0;
152
- return {
153
- height: "".concat(height, "px"),
154
- width: "".concat(width, "px"),
155
- heightInNumber: height,
156
- widthInNumber: width,
157
- };
158
- };
159
- var secondsToDateString = function (sec) {
160
- try {
161
- if (!sec || Number.isNaN(Number(sec))) {
162
- return '';
163
- }
164
- var date = new Date(sec * 1000);
165
- var year = date.getFullYear();
166
- var day = String(date.getDate()).padStart(2, '0');
167
- var month = String(date.getMonth() + 1).padStart(2, '0');
168
- return "".concat(year, "-").concat(month, "-").concat(day);
169
- }
170
- catch (_e) {
171
- return '';
172
- }
173
- };
174
- var formatFullDateString = function (dateString, format, fallback) {
175
- if (format === void 0) { format = 'dd-mm-yyyy'; }
176
- if (fallback === void 0) { fallback = ''; }
177
- try {
178
- var date = new Date(dateString);
179
- var year = date.getFullYear();
180
- var day = String(date.getDate()).padStart(2, '0');
181
- var month = String(date.getMonth() + 1).padStart(2, '0');
182
- switch (format) {
183
- case 'yyyy-mm-dd':
184
- return "".concat(year, "-").concat(month, "-").concat(day);
185
- case 'dd-mm-yyyy':
186
- default:
187
- return "".concat(day, "-").concat(month, "-").concat(year);
188
- }
189
- }
190
- catch (_e) {
191
- return fallback;
192
- }
193
- };
194
- var formatCurrency = function (value, withIcon) {
195
- if (withIcon === void 0) { withIcon = true; }
196
- try {
197
- var config = {
198
- currency: 'INR',
199
- minimumFractionDigits: 0,
200
- };
201
- if (withIcon) {
202
- config.style = 'currency';
203
- }
204
- if (typeof value !== 'string') {
205
- value = value === null || value === void 0 ? void 0 : value.toString();
206
- }
207
- value = value.replace(/,/g, '');
208
- return parseInt(value, 10).toLocaleString('en-IN', config);
209
- }
210
- catch (_e) {
211
- return '';
212
- }
213
- };
214
- var setCookie = function (_a) {
215
- var cookieName = _a.cookieName, cookieValue = _a.cookieValue, expiryInDay = _a.expiryInDay, expiryInHours = _a.expiryInHours, expiryInMinutes = _a.expiryInMinutes;
216
- var expires;
217
- var date = new Date();
218
- if (expiryInDay) {
219
- date.setTime(date.getTime() + expiryInDay * 24 * 60 * 60 * 1000);
220
- expires = date.toUTCString();
221
- }
222
- else if (expiryInHours) {
223
- date.setTime(date.getTime() + expiryInHours * 3600 * 1000);
224
- expires = date.toUTCString();
225
- }
226
- else if (expiryInMinutes) {
227
- date.setTime(date.getTime() + expiryInMinutes * 60 * 1000);
228
- expires = date.toUTCString();
229
- }
230
- else {
231
- expires = '';
232
- }
233
- document.cookie = "".concat(cookieName, "=").concat(cookieValue, "; expires=").concat(expires, "; path=/");
234
- };
235
- function extractQueryParamsAsObj(url) {
236
- try {
237
- var urlObj = new URL(url);
238
- var queryParams = new URLSearchParams(urlObj.search);
239
- var params_1 = {};
240
- queryParams.forEach(function (value, key) {
241
- params_1[key] = value;
242
- });
243
- return params_1;
244
- }
245
- catch (error) {
246
- return {};
247
- }
248
- }
249
- function getNoOfDaysFromToday(checkInDate) {
250
- var checkIn = new Date(checkInDate);
251
- var today = new Date();
252
- today.setHours(12, 0, 0, 0);
253
- checkIn.setHours(12, 0, 0, 0);
254
- var differenceInMs = checkIn.getTime() - today.getTime();
255
- var differenceInDays = differenceInMs / (1000 * 60 * 60 * 24);
256
- return Math.round(differenceInDays);
257
- }
258
-
259
- var getDevicePlatform = function () {
260
- var _a;
261
- var userAgent = (_a = getNestedValue(window, [
262
- 'navigator',
263
- 'userAgent',
264
- ])) === null || _a === void 0 ? void 0 : _a.toLowerCase();
265
- var safariBrowser = /safari/.test(userAgent);
266
- var appleDevice = /iphone|ipod|ipad/.test(userAgent);
267
- if ((getNestedValue(window, ['androidData', 'app-agent']) &&
268
- getNestedValue(window, ['androidData', 'js-version'])) ||
269
- typeof getNestedValue(window, ['MobileApp', 'getAppSpecificData']) ===
270
- 'function') {
271
- return ctPlatformConstants.Platform.ANDROID;
272
- }
273
- else if ((getNestedValue(window, ['iosData', 'app-agent']) &&
274
- getNestedValue(window, ['iosData', 'js-version'])) ||
275
- (appleDevice && !safariBrowser)) {
276
- return ctPlatformConstants.Platform.IOS;
277
- }
278
- return ctPlatformConstants.Platform.PWA;
279
- };
280
- var getAppAgent = function () {
281
- var _a, _b;
282
- var platform = getDevicePlatform();
283
- if (platform === ctPlatformConstants.Platform.IOS) {
284
- return (_a = getNestedValue(window, ['iosData', 'app-agent'])) !== null && _a !== void 0 ? _a : ctPlatformConstants.AppAgent.IOS;
285
- }
286
- else if (platform === ctPlatformConstants.Platform.ANDROID) {
287
- return ((_b = getNestedValue(window, ['androidData', 'app-agent'])) !== null && _b !== void 0 ? _b : ctPlatformConstants.AppAgent.ANDROID);
288
- }
289
- return ctPlatformConstants.AppAgent.PWA;
290
- };
291
- var getAppAgentForHotelUnifiedHeader = function () {
292
- if (isServer()) {
293
- return ctPlatformConstants.AppAgent.H_UNKNOWN;
294
- }
295
- var platform = getDevicePlatform();
296
- if (platform === ctPlatformConstants.Platform.IOS) {
297
- return ctPlatformConstants.AppAgent.H_IOS;
298
- }
299
- else if (platform === ctPlatformConstants.Platform.ANDROID) {
300
- ctPlatformConstants.AppAgent.H_ANDROID;
301
- }
302
- return ctPlatformConstants.AppAgent.H_PWA;
303
- };
304
- var getJSVersion = function () {
305
- var jsVersion = '';
306
- if (isIOSApp()) {
307
- jsVersion = getNestedValue(window, ['iosData', 'js-version']);
308
- }
309
- else if (isAndroidApp()) {
310
- jsVersion = getNestedValue(window, ['androidData', 'js-version']);
311
- }
312
- if (jsVersion) {
313
- jsVersion = jsVersion.toString().split('.')[0];
314
- }
315
- return jsVersion;
316
- };
317
- var getDeviceModel = function () {
318
- var _a, _b, _c, _d;
319
- if (!isServer()) {
320
- return '';
321
- }
322
- var parser = new UAParser__default.default((_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.userAgent);
323
- return (_d = (_c = (_b = parser === null || parser === void 0 ? void 0 : parser.getDevice()) === null || _b === void 0 ? void 0 : _b.model) === null || _c === void 0 ? void 0 : _c.toLowerCase()) !== null && _d !== void 0 ? _d : '';
324
- };
325
- var isPwa = function () {
326
- return getDevicePlatform() !== ctPlatformConstants.Platform.ANDROID &&
327
- getDevicePlatform() !== ctPlatformConstants.Platform.IOS;
328
- };
329
- var isAndroidApp = function () {
330
- return getDevicePlatform() === ctPlatformConstants.Platform.ANDROID;
331
- };
332
- var isJSVersionUpdated = function (compareVersion) {
333
- return parseInt(getJSVersion()) >= compareVersion;
334
- };
335
- var isIOSApp = function () { return getDevicePlatform() === ctPlatformConstants.Platform.IOS; };
336
-
337
- var API_BASE = getApiDomain();
338
- var getCustomHeaderClientSide = function (additionalInfo) {
339
- var unifiedHeader = {
340
- trackingId: uuid.v4(),
341
- source: ctPlatformConstants.SOURCE_NAME,
342
- };
343
- if (!isServer()) {
344
- return tslib.__assign(tslib.__assign(tslib.__assign({}, unifiedHeader), { platform: getAppAgent(), deviceModel: getDeviceModel() }), (additionalInfo !== null && additionalInfo !== void 0 ? additionalInfo : {}));
345
- }
346
- return tslib.__assign(tslib.__assign({}, unifiedHeader), (additionalInfo !== null && additionalInfo !== void 0 ? additionalInfo : {}));
347
- };
348
- var getRequestUrl = function (path, params) {
349
- var url = ctPlatformConstants.API_ROUTES[path];
350
- if (!url || !url.trim().length) {
351
- return;
352
- }
353
- url = urlJoin(API_BASE, url);
354
- if (params === null || params === void 0 ? void 0 : params.pathParams) {
355
- for (var _i = 0, _a = Object.entries(params.pathParams); _i < _a.length; _i++) {
356
- var _b = _a[_i], key = _b[0], value = _b[1];
357
- url = url.replace(":".concat(key), value);
358
- }
359
- }
360
- if (params === null || params === void 0 ? void 0 : params.queryParams) {
361
- url += "?".concat(new URLSearchParams(params.queryParams).toString());
362
- }
363
- return url;
364
- };
365
- var createAPIRequest = function (path, method, payload, headers, params, useCustomErrorHandler, additionalUnifiedHeaders) {
366
- if (method === void 0) { method = ctPlatformConstants.RequestMethods.GET; }
367
- if (headers === void 0) { headers = {}; }
368
- if (params === void 0) { params = {}; }
369
- if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
370
- if (additionalUnifiedHeaders === void 0) { additionalUnifiedHeaders = {}; }
371
- return tslib.__awaiter(void 0, void 0, void 0, function () {
372
- var url, channel, unifiedHeader, API_AUTHORITY, requestOptions, responseData, response, error, message, contentType;
373
- return tslib.__generator(this, function (_a) {
374
- switch (_a.label) {
375
- case 0:
376
- url = getRequestUrl(path, params);
377
- if (!url || !url.trim().length) {
378
- return [2, Promise.reject('URL parameter missing')];
379
- }
380
- channel = '';
381
- unifiedHeader = '';
382
- API_AUTHORITY = getApiDomain();
383
- if (!isServer()) {
384
- channel = getDevicePlatform();
385
- unifiedHeader = JSON.stringify(getCustomHeaderClientSide(additionalUnifiedHeaders));
386
- }
387
- requestOptions = {
388
- method: method,
389
- headers: tslib.__assign({ channel: channel, Caller: API_BASE, Origin: API_BASE, Referer: API_BASE, Authority: API_AUTHORITY, x_ct_sourcetype: 'MOBILE', 'app-agent': getAppAgent(), 'x-unified-header': unifiedHeader, 'Content-Type': 'application/json' }, headers),
390
- };
391
- if (payload) {
392
- requestOptions.body = JSON.stringify(payload);
393
- }
394
- return [4, fetch(url, requestOptions)];
395
- case 1:
396
- response = _a.sent();
397
- error = {
398
- name: 'API_FAILURE',
399
- status: response.status,
400
- message: 'UNKNOWN_ERROR',
401
- statusText: response.statusText,
402
- };
403
- if (!!(response === null || response === void 0 ? void 0 : response.ok)) return [3, 3];
404
- if (useCustomErrorHandler) {
405
- return [2, Promise.reject(error)];
406
- }
407
- return [4, response.json()];
408
- case 2:
409
- message = (_a.sent()).message;
410
- error.message = message;
411
- throw error;
412
- case 3:
413
- contentType = response.headers.get('content-type');
414
- if (!(contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json'))) return [3, 5];
415
- return [4, response.json()];
416
- case 4:
417
- responseData = _a.sent();
418
- return [3, 9];
419
- case 5:
420
- if (!(contentType === null || contentType === void 0 ? void 0 : contentType.includes('text'))) return [3, 7];
421
- return [4, response.text()];
422
- case 6:
423
- responseData = _a.sent();
424
- return [3, 9];
425
- case 7:
426
- if (!(response.status !== 204)) return [3, 9];
427
- return [4, response.blob()];
428
- case 8:
429
- responseData = _a.sent();
430
- _a.label = 9;
431
- case 9: return [2, {
432
- data: responseData,
433
- status: response.status,
434
- }];
435
- }
436
- });
437
- });
438
- };
439
- var createGetRequest = function (path, headers, params, useCustomErrorHandler, additionalUnifiedHeaders) {
440
- if (headers === void 0) { headers = {}; }
441
- if (params === void 0) { params = {}; }
442
- if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
443
- if (additionalUnifiedHeaders === void 0) { additionalUnifiedHeaders = {}; }
444
- return tslib.__awaiter(void 0, void 0, void 0, function () {
445
- return tslib.__generator(this, function (_a) {
446
- return [2, createAPIRequest(path, ctPlatformConstants.RequestMethods.GET, null, tslib.__assign({ expires: '0', accept: 'application/json', 'cache-control': 'no-cache' }, headers), params, useCustomErrorHandler, additionalUnifiedHeaders)];
447
- });
448
- });
449
- };
450
- var createPostOrPutRequest = function (path, method, payload, headers, params, useCustomErrorHandler, additionalUnifiedHeaders) {
451
- if (method === void 0) { method = ctPlatformConstants.RequestMethods.POST; }
452
- if (payload === void 0) { payload = {}; }
453
- if (headers === void 0) { headers = {}; }
454
- if (params === void 0) { params = {}; }
455
- if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
456
- if (additionalUnifiedHeaders === void 0) { additionalUnifiedHeaders = {}; }
457
- return tslib.__awaiter(void 0, void 0, void 0, function () {
458
- return tslib.__generator(this, function (_a) {
459
- return [2, createAPIRequest(path, method, payload, tslib.__assign({ expires: '0', accept: 'application/json', 'cache-control': 'no-cache' }, headers), params, useCustomErrorHandler, additionalUnifiedHeaders)];
460
- });
461
- });
462
- };
463
-
464
- var showMobileNumberHint = function () {
465
- var _a;
466
- if (typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onRequestMobileNumber) === 'function') {
467
- window.MobileApp.onRequestMobileNumber();
468
- var promiseResolver_1;
469
- var mobileNoPromise = new Promise(function (resolve) {
470
- promiseResolver_1 = resolve;
471
- });
472
- window.sendSelectedMobileNumber = function (mobileNum) {
473
- return promiseResolver_1(getAutoDetectedMobile(mobileNum));
474
- };
475
- return mobileNoPromise;
476
- }
477
- return Promise.resolve('');
478
- };
479
- var getAutoDetectedMobile = function (mobileNumber) {
480
- var formattedMobileNo = '';
481
- var matches = mobileNumber.match(ctPlatformConstants.MOBILE_CONSTANTS.REGEX);
482
- if (matches) {
483
- formattedMobileNo = matches[0].replace(/\D/g, '');
484
- }
485
- return formattedMobileNo;
486
- };
487
- var autoReadOtp = function () { return tslib.__awaiter(void 0, void 0, void 0, function () {
488
- return tslib.__generator(this, function (_a) {
489
- return [2, isAndroidApp() ? readOtpAndroid() : readOtpPWA()];
490
- });
491
- }); };
492
- var updateNativeIOSOnSignIn = function () {
493
- var _a, _b, _c;
494
- (_c = (_b = (_a = window.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.PWA_IS_SIGNIN) === null || _c === void 0 ? void 0 : _c.postMessage({
495
- isSignIn: true,
496
- });
497
- };
498
- var updateNativeAndroidOnSignIn = function () {
499
- var _a;
500
- (_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onPWALoginStatus(JSON.stringify({
501
- isSignIn: true,
502
- }));
503
- };
504
- var triggerOTPListener = function () {
505
- var _a;
506
- if (isAndroidApp()) {
507
- (_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onPageStart('OTP_SCREEN');
508
- }
509
- };
510
- var readOtpPWA = function () { return tslib.__awaiter(void 0, void 0, void 0, function () {
511
- var abortController;
512
- var _a;
513
- return tslib.__generator(this, function (_b) {
514
- if (!((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.get) || !('OTPCredential' in window)) {
515
- return [2, Promise.reject('NOT_SUPPORTED')];
516
- }
517
- abortController = new AbortController();
518
- setTimeout(function () {
519
- abortController.abort();
520
- }, 60000);
521
- return [2, navigator.credentials
522
- .get({
523
- otp: { transport: ['sms'] },
524
- signal: abortController.signal,
525
- })
526
- .then(function (content) { return content === null || content === void 0 ? void 0 : content.code; })];
527
- });
528
- }); };
529
- var readOtpAndroid = function () { return tslib.__awaiter(void 0, void 0, void 0, function () {
530
- var promiseResolver, otpPromise;
531
- return tslib.__generator(this, function (_a) {
532
- otpPromise = new Promise(function (resolve) {
533
- promiseResolver = resolve;
534
- });
535
- window.sendOtpValue = function (otp) {
536
- promiseResolver(otp);
537
- };
538
- return [2, otpPromise];
539
- });
540
- }); };
541
- var shouldShowPushPrimer = function () { return tslib.__awaiter(void 0, void 0, void 0, function () {
542
- var _a, _b;
543
- return tslib.__generator(this, function (_c) {
544
- if (isAndroidApp() &&
545
- typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.isPNPermissionEnabled) === 'function') {
546
- return [2, Promise.resolve(!((_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.isPNPermissionEnabled()))];
547
- }
548
- else if (isIOSApp()) {
549
- return [2, new Promise(function (resolve, _reject) {
550
- var _a, _b, _c, _d;
551
- window.pushNotifcationPermissionStatus = function (data) {
552
- var parsedData = JSON.parse(data);
553
- var status = parsedData === null || parsedData === void 0 ? void 0 : parsedData.status;
554
- if (typeof status === 'boolean') {
555
- resolve(!status);
556
- }
557
- };
558
- try {
559
- (_d = (_c = (_b = (_a = window === null || window === void 0 ? void 0 : window.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b['IS_PN_PERMISSION_ENABLED']) === null || _c === void 0 ? void 0 : _c.postMessage) === null || _d === void 0 ? void 0 : _d.call(_c, '');
560
- }
561
- catch (error) {
562
- resolve(false);
563
- }
564
- })];
565
- }
566
- return [2, Promise.resolve(false)];
567
- });
568
- }); };
569
- var handlePushPrimerCTA = function (type) {
570
- var _a, _b, _c, _d, _e, _f, _g, _h;
571
- if (isAndroidApp() &&
572
- typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.handlePNPermission) === 'function') {
573
- (_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.handlePNPermission(JSON.stringify({ type: type }));
574
- }
575
- else if (isIOSApp() &&
576
- ((_d = (_c = window === null || window === void 0 ? void 0 : window.webkit) === null || _c === void 0 ? void 0 : _c.messageHandlers) === null || _d === void 0 ? void 0 : _d.HANDLE_PN_PERMISSION)) {
577
- (_h = (_g = (_f = (_e = window.webkit) === null || _e === void 0 ? void 0 : _e.messageHandlers) === null || _f === void 0 ? void 0 : _f.HANDLE_PN_PERMISSION) === null || _g === void 0 ? void 0 : _g.postMessage) === null || _h === void 0 ? void 0 : _h.call(_g, JSON.stringify({ type: type }));
578
- }
579
- return;
580
- };
581
-
582
- var getProfileDetails = function () { return tslib.__awaiter(void 0, void 0, void 0, function () {
583
- var response, error_1;
584
- return tslib.__generator(this, function (_a) {
585
- switch (_a.label) {
586
- case 0:
587
- _a.trys.push([0, 2, , 3]);
588
- return [4, createGetRequest('GET_PROFILE_DETAILS', {
589
- caller: getApiDomain(),
590
- 'app-agent': getAppAgent(),
591
- }, {})];
592
- case 1:
593
- response = _a.sent();
594
- return [2, response === null || response === void 0 ? void 0 : response.data];
595
- case 2:
596
- error_1 = _a.sent();
597
- console.error('Failed to fetch user details. Error: ', error_1);
598
- return [2, Promise.resolve(null)];
599
- case 3: return [2];
600
- }
601
- });
602
- }); };
603
- var sendLoginOtp = function (mobile, personalizationHeaders) { return tslib.__awaiter(void 0, void 0, void 0, function () {
604
- var response;
605
- return tslib.__generator(this, function (_a) {
606
- switch (_a.label) {
607
- case 0: return [4, createPostOrPutRequest('SEND_OTP', ctPlatformConstants.RequestMethods.POST, {
608
- value: mobile,
609
- type: 'MOBILE',
610
- action: 'SIGNIN',
611
- countryCode: ctPlatformConstants.MOBILE_CONSTANTS.COUNTRY_CODE,
612
- }, {
613
- 'ab-otp': 'b',
614
- dvid_data: personalizationHeaders,
615
- })];
616
- case 1:
617
- response = _a.sent();
618
- return [2, response === null || response === void 0 ? void 0 : response.data];
619
- }
620
- });
621
- }); };
622
- var validateOtp = function (mobile, otp) { return tslib.__awaiter(void 0, void 0, void 0, function () {
623
- var response, data;
624
- return tslib.__generator(this, function (_a) {
625
- switch (_a.label) {
626
- case 0: return [4, createPostOrPutRequest('VALIDATE_OTP', ctPlatformConstants.RequestMethods.POST, {
627
- otp: otp,
628
- value: mobile,
629
- type: 'MOBILE',
630
- action: 'SIGNIN',
631
- countryCode: '+91',
632
- }, { 'ab-otp': 'b' })];
633
- case 1:
634
- response = _a.sent();
635
- data = response === null || response === void 0 ? void 0 : response.data;
636
- return [2, tslib.__assign(tslib.__assign({}, response), { signup: (data === null || data === void 0 ? void 0 : data.action) === ctPlatformTypes.ValidateOTPAction.SIGNUP, action: data === null || data === void 0 ? void 0 : data.action, status: response === null || response === void 0 ? void 0 : response.status })];
637
- }
638
- });
639
- }); };
640
- var handleFKSSO = function (fallbackUri, skipProfileFlow) { return tslib.__awaiter(void 0, void 0, void 0, function () {
641
- var currentPageUri, redirectionInfo;
642
- return tslib.__generator(this, function (_a) {
643
- switch (_a.label) {
644
- case 0:
645
- if (isIOSApp()) {
646
- return [2, Promise.reject()];
647
- }
648
- currentPageUri = getCurrentPathName();
649
- return [4, sendFKSSORedirectionInfo(fallbackUri, skipProfileFlow
650
- ? currentPageUri
651
- : ctPlatformConstants.NAVIGATION_ROUTES.PERSONAL_DETAILS + '?onboardingFlow=true', currentPageUri)];
652
- case 1:
653
- redirectionInfo = _a.sent();
654
- if (isAndroidApp()) {
655
- return [2, handleFKSSOAndroid(redirectionInfo)];
656
- }
657
- else {
658
- return [2, handleFKSSOWeb(redirectionInfo)];
659
- }
660
- }
661
- });
662
- }); };
663
- var isValidMobileNumber = function (text) {
664
- return (text === null || text === void 0 ? void 0 : text.length) === ctPlatformConstants.MOBILE_CONSTANTS.LENGTH && /^\d{10}$/.test(text);
665
- };
666
- var updateNativeOnLogin = function () {
667
- if (isIOSApp()) {
668
- updateNativeIOSOnSignIn();
669
- }
670
- else if (isAndroidApp()) {
671
- updateNativeAndroidOnSignIn();
672
- }
673
- };
674
- var isFKSSOEnabled = function () {
675
- return isPwa() || (!isIOSApp() && isJSVersionUpdated(5));
676
- };
677
- var sendFKSSORedirectionInfo = function (fallbackUri, signupPageUri, currentPageUri) { return tslib.__awaiter(void 0, void 0, void 0, function () {
678
- var WEBSITE_BASE, response;
679
- return tslib.__generator(this, function (_a) {
680
- switch (_a.label) {
681
- case 0:
682
- WEBSITE_BASE = getApiDomain();
683
- return [4, createPostOrPutRequest('FK_REDIRECTION_INFO', ctPlatformConstants.RequestMethods.POST, {
684
- provider: 'flipkart',
685
- fallbackUri: urlJoin(WEBSITE_BASE, fallbackUri || currentPageUri),
686
- signupPageUri: urlJoin(WEBSITE_BASE, signupPageUri || 'personal-details'),
687
- currentPageUri: urlJoin(WEBSITE_BASE, currentPageUri),
688
- })];
689
- case 1:
690
- response = _a.sent();
691
- return [2, response === null || response === void 0 ? void 0 : response.data];
692
- }
693
- });
694
- }); };
695
- var handleFKSSOWeb = function (redirectionInfo) {
696
- var _a;
697
- var params = (_a = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.params) !== null && _a !== void 0 ? _a : {};
698
- var redirectUri = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.redirectUri;
699
- if (redirectUri) {
700
- redirectUri += '?';
701
- for (var key in params) {
702
- redirectUri += key + '=' + params[key] + '&';
703
- }
704
- return Promise.resolve(redirectUri);
705
- }
706
- return Promise.reject();
707
- };
708
- var handleFKSSOAndroid = function (redirectionInfo) {
709
- var _a, _b;
710
- var params = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.params;
711
- if (isEmpty(params) ||
712
- typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onNavigationChange) !== 'function') {
713
- return Promise.reject();
714
- }
715
- else {
716
- var FK_REDIRECT_DL = urlJoin(getApiDomain(), 'dl/oauth2');
717
- (_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.onNavigationChange(JSON.stringify({
718
- type: 'FkSSO',
719
- miscData: tslib.__assign(tslib.__assign({}, params), { redirectURI: FK_REDIRECT_DL }),
720
- }));
721
- return Promise.resolve();
722
- }
723
- };
724
- function getUserAuthValues(customCookie) {
725
- try {
726
- var _a = decodeURIComponent(getCookie('userid', customCookie) || '').split('|'), email = _a[0], profileName = _a[1], gender = _a[2], photo = _a[3], userId = _a[4];
727
- return {
728
- email: email,
729
- profileName: profileName,
730
- gender: gender,
731
- photo: photo,
732
- userId: userId,
733
- };
734
- }
735
- catch (error) {
736
- return {};
737
- }
738
- }
739
- var isUserSignedIn = function (customCookie) {
740
- var userObject = getUserAuthValues(customCookie) || {};
741
- var usermiscVal = decodeURIComponent(getCookie('usermisc', customCookie) || '').split('|');
742
- var signedIn = usermiscVal.includes('SIGNED_IN') &&
743
- userObject.userId &&
744
- userObject.userId.length > 0
745
- ? true
746
- : false;
747
- return signedIn;
748
- };
749
- var sendClevertapProfileDetails = function (profileDetails) {
750
- var _a, _b, _c, _d, _e, _f;
751
- try {
752
- if (isServer() || !(window === null || window === void 0 ? void 0 : window.clevertap) || isEmpty(profileDetails)) {
753
- return;
754
- }
755
- var Site = {
756
- Identity: (_a = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.id) !== null && _a !== void 0 ? _a : '',
757
- Gender: (_b = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.gender) !== null && _b !== void 0 ? _b : '',
758
- Email: (_c = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.username) !== null && _c !== void 0 ? _c : '',
759
- Phone: "".concat(profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.countryCode).concat(profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.mobile),
760
- 'MSG-sms': true,
761
- 'MSG-push': true,
762
- 'MSG-email': false,
763
- 'MSG-whatsapp': true,
764
- };
765
- if ((_d = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.travellerDetails) === null || _d === void 0 ? void 0 : _d.length) {
766
- for (var i = 0; i < ((_e = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.travellerDetails) === null || _e === void 0 ? void 0 : _e.length); i++) {
767
- var traveller = profileDetails === null || profileDetails === void 0 ? void 0 : profileDetails.travellerDetails[i];
768
- if (traveller.isRegistered) {
769
- var dateOfBirth = traveller.personalDetails.dateOfBirth;
770
- Site.Name = "".concat(traveller.personalDetails.firstName, " ").concat(traveller.personalDetails.lastName);
771
- if (!isNaN(dateOfBirth)) {
772
- Site.DOB = new Date(dateOfBirth);
773
- }
774
- break;
775
- }
776
- }
777
- }
778
- (_f = window === null || window === void 0 ? void 0 : window.clevertap) === null || _f === void 0 ? void 0 : _f.onUserLogin.push({ Site: Site });
779
- }
780
- catch (error) {
781
- console.log('Error pushing clevertap profile information. Error: ', error);
782
- }
783
- };
784
- var handleProfileFetch = function (updateClevertap) {
785
- if (updateClevertap === void 0) { updateClevertap = true; }
786
- return tslib.__awaiter(void 0, void 0, void 0, function () {
787
- var response;
788
- return tslib.__generator(this, function (_a) {
789
- switch (_a.label) {
790
- case 0: return [4, getProfileDetails()];
791
- case 1:
792
- response = _a.sent();
793
- if (response) {
794
- if (updateClevertap) {
795
- sendClevertapProfileDetails(response);
796
- }
797
- }
798
- return [2];
799
- }
800
- });
801
- });
802
- };
803
-
804
- var getUserInsights = function (userId) { return tslib.__awaiter(void 0, void 0, void 0, function () {
805
- var response;
806
- return tslib.__generator(this, function (_a) {
807
- switch (_a.label) {
808
- case 0:
809
- _a.trys.push([0, 2, , 3]);
810
- return [4, createGetRequest('USER_INSIGHTS', {}, {
811
- pathParams: {
812
- userId: userId,
813
- },
814
- })];
815
- case 1:
816
- response = _a.sent();
817
- return [2, response === null || response === void 0 ? void 0 : response.data];
818
- case 2:
819
- _a.sent();
820
- return [2, Promise.resolve(null)];
821
- case 3: return [2];
822
- }
823
- });
824
- }); };
825
- var getUserInsightsData = function (userId) { return tslib.__awaiter(void 0, void 0, void 0, function () {
826
- var _userId, stringifiedData, sessionData, userInsights;
827
- var _a, _b, _c, _d;
828
- return tslib.__generator(this, function (_f) {
829
- switch (_f.label) {
830
- case 0:
831
- _f.trys.push([0, 2, , 3]);
832
- _userId = userId !== null && userId !== void 0 ? userId : getUserAuthValues().userId;
833
- if (!_userId) {
834
- (_a = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _a === void 0 ? void 0 : _a.removeItem('martech_user_attributes');
835
- return [2, null];
836
- }
837
- stringifiedData = (_b = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _b === void 0 ? void 0 : _b.getItem('martech_user_attributes');
838
- sessionData = void 0;
839
- if (typeof stringifiedData === 'string') {
840
- sessionData = JSON.parse(stringifiedData);
841
- }
842
- if (_userId !== (sessionData === null || sessionData === void 0 ? void 0 : sessionData.accountId)) {
843
- (_c = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _c === void 0 ? void 0 : _c.removeItem('martech_user_attributes');
844
- }
845
- return [4, getUserInsights(_userId)];
846
- case 1:
847
- userInsights = _f.sent();
848
- if (isEmpty(userInsights === null || userInsights === void 0 ? void 0 : userInsights.data)) {
849
- return [2, null];
850
- }
851
- (_d = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _d === void 0 ? void 0 : _d.setItem('martech_user_attributes', JSON.stringify(userInsights === null || userInsights === void 0 ? void 0 : userInsights.data));
852
- return [2, userInsights === null || userInsights === void 0 ? void 0 : userInsights.data];
853
- case 2:
854
- _f.sent();
855
- return [2, null];
856
- case 3: return [2];
857
- }
858
- });
859
- }); };
860
-
861
- var stringifyPayload = function (payload) {
862
- var keys = Object.keys(payload);
863
- keys.forEach(function (key) {
864
- if (key === 'a_fare_price' ||
865
- key === 'a_ct_discount' ||
866
- key === 'supercoin_balance' ||
867
- key === 'supercoin_earned' ||
868
- key === 'supercoin_burnt' ||
869
- key === 'wallet_balance_used' ||
870
- key === 'convenience_fee')
871
- payload[key] = Number(payload[key]);
872
- else
873
- payload[key] = '' + payload[key];
874
- });
875
- return payload;
876
- };
877
- var getCTStatsigExpForRaven = function () {
878
- try {
879
- if (isServer()) {
880
- return '';
881
- }
882
- var cookie = getCookie('ct_statsig_experiments') || '{}';
883
- var parsedCookie_1 = cookie
884
- ? JSON.parse(decodeURIComponent(cookie))
885
- : {};
886
- return Object.keys(parsedCookie_1)
887
- .map(function (key) {
888
- if (key && parsedCookie_1[key]) {
889
- return "".concat(key, ":").concat(parsedCookie_1[key]);
890
- }
891
- return '';
892
- })
893
- .filter(function (value) { return !!value; })
894
- .join('|');
895
- }
896
- catch (_e) {
897
- return '';
898
- }
899
- };
900
- var ravenSDKTrigger = function (eventName, ravenPayload) {
901
- var _a;
902
- if (window && window['ravenWebManager']) {
903
- var _b = getRavenEventProps(), pageName = _b.pageName, utmSource = _b.utmSource;
904
- var commonPayload = {
905
- page_name: pageName,
906
- u_utm_source: utmSource,
907
- domain: window.location.host,
908
- u_ab_key: getCTStatsigExpForRaven(),
909
- platform: (_a = getDevicePlatform()) === null || _a === void 0 ? void 0 : _a.toLowerCase(),
910
- login_status: isUserSignedIn() ? 'yes' : 'no',
911
- };
912
- var newRavenPayload = stringifyPayload(ravenPayload);
913
- var RavenWebManager = window['ravenWebManager'];
914
- RavenWebManager === null || RavenWebManager === void 0 ? void 0 : RavenWebManager.triggerRaven(eventName, tslib.__assign(tslib.__assign({}, commonPayload), newRavenPayload));
915
- }
916
- };
917
- var isAirHomePage = function () {
918
- if (window && typeof window !== 'undefined') {
919
- var pathname = getNestedValue(window, ['location', 'pathname']);
920
- if (pathname === '/' || pathname === '/flights') {
921
- return true;
922
- }
923
- }
924
- return false;
925
- };
926
- var getRavenEventProps = function () {
927
- var _a, _b;
928
- if (window && typeof window !== 'undefined') {
929
- var pathUrl = window.location.pathname;
930
- var redirectionPath = (_a = getQueryParam('service')) !== null && _a !== void 0 ? _a : '';
931
- var utmSource = (_b = getQueryParam('utm_source')) !== null && _b !== void 0 ? _b : 'organic';
932
- var loginForm = isAirHomePage() ? 'skippable_login' : 'account_login';
933
- var vertical = 'air';
934
- var pageName = pathUrl.includes('flights/itinerary') ||
935
- redirectionPath.includes('flights/itinerary')
936
- ? 'a_itinerary'
937
- : 'a_home';
938
- if (redirectionPath.includes('my-account')) {
939
- vertical = 'uar';
940
- pageName = 'account';
941
- }
942
- if (redirectionPath.includes('hotels')) {
943
- vertical = 'hotel';
944
- pageName = redirectionPath.includes('hotels/itinerary')
945
- ? 'h_itinerary'
946
- : 'h_home';
947
- }
948
- if (redirectionPath.includes('bus')) {
949
- vertical = 'bus';
950
- pageName = redirectionPath.includes('bus/itinerary')
951
- ? 'b_itinerary'
952
- : 'b_home';
953
- }
954
- return { loginForm: loginForm, vertical: vertical, pageName: pageName, utmSource: utmSource };
955
- }
956
- return {};
957
- };
958
- var sendEventWithUserInsights = function (eventName, ravenPayload, userId) { return tslib.__awaiter(void 0, void 0, void 0, function () {
959
- var userInsights, updatedPayload, loyaltyData, martechAttributes;
960
- var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
961
- return tslib.__generator(this, function (_t) {
962
- switch (_t.label) {
963
- case 0: return [4, getUserInsightsData(userId)];
964
- case 1:
965
- userInsights = _t.sent();
966
- updatedPayload = tslib.__assign(tslib.__assign({}, ravenPayload), { fk_loyalty_status: 'na', fk_loyalty_end_dt: 'na', ct_last_booking_dt: 'na', ct_lifetime_booking: 'na', fk_loyalty_start_dt: 'na', ct_first_booking_dt: 'na', myntra_loyalty_status: 'na', ct_postmerger_booking: 'na', ct_last_1year_booking: 'na', myntra_loyalty_end_dt: 'na', ct_2nd_last_booking_dt: 'na', myntra_loyalty_start_dt: 'na' });
967
- if (!isEmpty(userInsights)) {
968
- loyaltyData = ((_a = userInsights === null || userInsights === void 0 ? void 0 : userInsights.loyaltyStatus) !== null && _a !== void 0 ? _a : []).reduce(function (prev, curr) {
969
- return tslib.__assign(tslib.__assign({}, prev), curr);
970
- }, {});
971
- martechAttributes = {
972
- ct_lifetime_booking: ((_c = (_b = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _b === void 0 ? void 0 : _b.lifetimeBooking) !== null && _c !== void 0 ? _c : 'na').toString(),
973
- ct_postmerger_booking: ((_f = (_d = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _d === void 0 ? void 0 : _d.postmergerBooking) !== null && _f !== void 0 ? _f : 'na').toString(),
974
- ct_last_1year_booking: ((_h = (_g = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _g === void 0 ? void 0 : _g.lastOneYearBooking) !== null && _h !== void 0 ? _h : 'na').toString(),
975
- ct_first_booking_dt: secondsToDateString((_j = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _j === void 0 ? void 0 : _j.firstbookingDate) || 'na',
976
- ct_last_booking_dt: secondsToDateString((_k = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _k === void 0 ? void 0 : _k.lastbookingDate) || 'na',
977
- ct_2nd_last_booking_dt: secondsToDateString((_l = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _l === void 0 ? void 0 : _l.secondLastbookingDate) || 'na',
978
- fk_loyalty_status: ((_m = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _m === void 0 ? void 0 : _m.program) || 'na',
979
- myntra_loyalty_status: ((_o = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _o === void 0 ? void 0 : _o.program) || 'na',
980
- fk_loyalty_end_dt: secondsToDateString((_p = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _p === void 0 ? void 0 : _p.loyaltyEndDate) || '',
981
- fk_loyalty_start_dt: secondsToDateString((_q = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _q === void 0 ? void 0 : _q.loyaltyStartDate) || 'na',
982
- myntra_loyalty_start_dt: secondsToDateString((_r = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _r === void 0 ? void 0 : _r.loyaltyStartDate) ||
983
- 'na',
984
- myntra_loyalty_end_dt: secondsToDateString((_s = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _s === void 0 ? void 0 : _s.loyaltyEndDate) ||
985
- 'na',
986
- };
987
- updatedPayload = tslib.__assign(tslib.__assign({}, updatedPayload), martechAttributes);
988
- setMartechUserProperties(martechAttributes);
989
- }
990
- ravenSDKTrigger(eventName, updatedPayload);
991
- return [2];
992
- }
993
- });
994
- }); };
995
- var setMartechUserProperties = function (userProperties) {
996
- var _a, _b, _c, _d, _f, _g, _h, _j, _k;
997
- if (isEmpty(userProperties) ||
998
- ((_a = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _a === void 0 ? void 0 : _a.getItem('martech_user_props_sent'))) {
999
- return;
1000
- }
1001
- if (isIOSApp() && ((_c = (_b = window === null || window === void 0 ? void 0 : window.webkit) === null || _b === void 0 ? void 0 : _b.messageHandlers) === null || _c === void 0 ? void 0 : _c.SEND_ATTRIBUTES)) {
1002
- (_d = window.webkit.messageHandlers.SEND_ATTRIBUTES) === null || _d === void 0 ? void 0 : _d.postMessage({
1003
- type: 'GA',
1004
- params: userProperties,
1005
- });
1006
- (_f = window.webkit.messageHandlers.SEND_ATTRIBUTES) === null || _f === void 0 ? void 0 : _f.postMessage({
1007
- type: 'Clevertap',
1008
- params: userProperties,
1009
- });
1010
- (_g = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _g === void 0 ? void 0 : _g.setItem('martech_user_props_sent', 'true');
1011
- }
1012
- else if (isAndroidApp() && ((_h = window === null || window === void 0 ? void 0 : window.MobileApp) === null || _h === void 0 ? void 0 : _h.sendAttributes)) {
1013
- window.MobileApp.sendAttributes('GA', JSON.stringify(userProperties));
1014
- window.MobileApp.sendAttributes('Clevertap', JSON.stringify(userProperties));
1015
- (_j = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _j === void 0 ? void 0 : _j.setItem('martech_user_props_sent', 'true');
1016
- }
1017
- else if (isPwa() && window.clevertap) {
1018
- window.clevertap.profile.push({
1019
- Site: userProperties,
1020
- });
1021
- (_k = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _k === void 0 ? void 0 : _k.setItem('martech_user_props_sent', 'true');
1022
- }
1023
- };
1024
- var batchRavenEvent = function (eventName, ravenPayload) {
1025
- if (typeof window !== 'undefined' &&
1026
- typeof window.requestIdleCallback === 'function') {
1027
- requestIdleCallback(function () {
1028
- ravenSDKTrigger(eventName, ravenPayload);
1029
- });
1030
- }
1031
- else {
1032
- setTimeout(function () {
1033
- ravenSDKTrigger(eventName, ravenPayload);
1034
- }, 0);
1035
- }
1036
- };
1037
-
1038
- var getHotelCrossSellRecos = function (vertical, fallbackPageLandingURL, cutoff, couponCallOutPrefix, couponCallOutSuffix, offerCallOut, additionalHeaders, additionalParams) {
1039
- if (cutoff === void 0) { cutoff = 450; }
1040
- if (couponCallOutPrefix === void 0) { couponCallOutPrefix = 'Discounts'; }
1041
- if (couponCallOutSuffix === void 0) { couponCallOutSuffix = 'on hotels'; }
1042
- if (offerCallOut === void 0) { offerCallOut = 'CTBEST - Exclusive coupon applied for you!'; }
1043
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
1044
- if (additionalParams === void 0) { additionalParams = {}; }
1045
- return tslib.__awaiter(void 0, void 0, void 0, function () {
1046
- var userId, fallbackData, timeoutPromise, fetchRecommendationsPromise, result;
1047
- var _a, _b;
1048
- return tslib.__generator(this, function (_c) {
1049
- switch (_c.label) {
1050
- case 0:
1051
- userId = (_b = (_a = getUserAuthValues()) === null || _a === void 0 ? void 0 : _a.userId) !== null && _b !== void 0 ? _b : '';
1052
- fallbackData = {
1053
- couponCode: '',
1054
- couponCallOut: '',
1055
- couponCallOutPrefix: couponCallOutPrefix,
1056
- couponCallOutSuffix: couponCallOutSuffix,
1057
- offerCallOut: offerCallOut,
1058
- pageLandingUrl: fallbackPageLandingURL,
1059
- };
1060
- _c.label = 1;
1061
- case 1:
1062
- _c.trys.push([1, 3, , 4]);
1063
- timeoutPromise = new Promise(function (resolve) {
1064
- setTimeout(function () {
1065
- resolve(fallbackData);
1066
- }, cutoff);
1067
- });
1068
- fetchRecommendationsPromise = createGetRequest('HOTEL_RECOMMENDATIONS', additionalHeaders, {
1069
- queryParams: tslib.__assign({ userId: userId, vertical: vertical }, additionalParams),
1070
- }, false, {
1071
- userBuckets: { 'x-cross-sell': 'true' },
1072
- platform: getAppAgentForHotelUnifiedHeader(),
1073
- }).then(function (res) { return res.data; });
1074
- return [4, Promise.race([
1075
- fetchRecommendationsPromise,
1076
- timeoutPromise,
1077
- ])];
1078
- case 2:
1079
- result = _c.sent();
1080
- return [2, result];
1081
- case 3:
1082
- _c.sent();
1083
- return [2, fallbackData];
1084
- case 4: return [2];
1085
- }
1086
- });
1087
- });
1088
- };
1089
-
1090
- exports.MULTI_SPACE = MULTI_SPACE;
1091
- exports.autoReadOtp = autoReadOtp;
1092
- exports.batchRavenEvent = batchRavenEvent;
1093
- exports.createAPIRequest = createAPIRequest;
1094
- exports.createGetRequest = createGetRequest;
1095
- exports.createPostOrPutRequest = createPostOrPutRequest;
1096
- exports.extractQueryParamsAsObj = extractQueryParamsAsObj;
1097
- exports.formatCurrency = formatCurrency;
1098
- exports.formatFullDateString = formatFullDateString;
1099
- exports.getApiDomain = getApiDomain;
1100
- exports.getAppAgent = getAppAgent;
1101
- exports.getAppAgentForHotelUnifiedHeader = getAppAgentForHotelUnifiedHeader;
1102
- exports.getAutoDetectedMobile = getAutoDetectedMobile;
1103
- exports.getCTStatsigExpForRaven = getCTStatsigExpForRaven;
1104
- exports.getCookie = getCookie;
1105
- exports.getCurrentPathName = getCurrentPathName;
1106
- exports.getCurrentUrl = getCurrentUrl;
1107
- exports.getDeviceModel = getDeviceModel;
1108
- exports.getDevicePlatform = getDevicePlatform;
1109
- exports.getDimensionFromImageUrl = getDimensionFromImageUrl;
1110
- exports.getHeightFromImgUrl = getHeightFromImgUrl;
1111
- exports.getHotelCrossSellRecos = getHotelCrossSellRecos;
1112
- exports.getJSVersion = getJSVersion;
1113
- exports.getNestedValue = getNestedValue;
1114
- exports.getNoOfDaysFromToday = getNoOfDaysFromToday;
1115
- exports.getQueryParam = getQueryParam;
1116
- exports.getRavenEventProps = getRavenEventProps;
1117
- exports.getUserAuthValues = getUserAuthValues;
1118
- exports.getWidthFromImgUrl = getWidthFromImgUrl;
1119
- exports.handleFKSSO = handleFKSSO;
1120
- exports.handleProfileFetch = handleProfileFetch;
1121
- exports.handlePushPrimerCTA = handlePushPrimerCTA;
1122
- exports.isAirHomePage = isAirHomePage;
1123
- exports.isAndroidApp = isAndroidApp;
1124
- exports.isEmpty = isEmpty;
1125
- exports.isFKSSOEnabled = isFKSSOEnabled;
1126
- exports.isHTMLInputElement = isHTMLInputElement;
1127
- exports.isIOSApp = isIOSApp;
1128
- exports.isJSVersionUpdated = isJSVersionUpdated;
1129
- exports.isNumeric = isNumeric;
1130
- exports.isPwa = isPwa;
1131
- exports.isServer = isServer;
1132
- exports.isUserSignedIn = isUserSignedIn;
1133
- exports.isValidMobileNumber = isValidMobileNumber;
1134
- exports.path = path;
1135
- exports.ravenSDKTrigger = ravenSDKTrigger;
1136
- exports.secondsToDateString = secondsToDateString;
1137
- exports.sendEventWithUserInsights = sendEventWithUserInsights;
1138
- exports.sendLoginOtp = sendLoginOtp;
1139
- exports.setCookie = setCookie;
1140
- exports.setMartechUserProperties = setMartechUserProperties;
1141
- exports.shouldShowPushPrimer = shouldShowPushPrimer;
1142
- exports.showMobileNumberHint = showMobileNumberHint;
1143
- exports.stringifyPayload = stringifyPayload;
1144
- exports.triggerOTPListener = triggerOTPListener;
1145
- exports.updateNativeAndroidOnSignIn = updateNativeAndroidOnSignIn;
1146
- exports.updateNativeIOSOnSignIn = updateNativeIOSOnSignIn;
1147
- exports.updateNativeOnLogin = updateNativeOnLogin;
1148
- exports.urlJoin = urlJoin;
1149
- exports.validateOtp = validateOtp;
1
+ "use strict";var e=require("tslib"),t=require("uuid"),n=require("@cleartrip/ct-platform-constants"),o=require("ua-parser-js"),i=require("@cleartrip/ct-platform-types");function r(e){return e&&e.__esModule?e:{default:e}}var a=r(o),s=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e.map((function(e){return e.trim().replace(/^[/]+/,"")})).join("/");return n=n.replace(/\/\?/g,"?")},u=function(){var e="undefined"!=typeof window?window.location.hostname:"";switch(console.log("API_BASE domain",e),e){case"localhost":case"0.0.0.0":case"qa2new.cleartrip.com":return"https://qa2new.cleartrip.com";case"qa2.cleartrip.com":return"https://qa2.cleartrip.com";case"qa3new.cleartrip.com":return"https://qa3new.cleartrip.com";default:return"https://www.cleartrip.com"}},l=function(e,t){return t.reduce((function(e,t){return e&&e[t]?e[t]:null}),e)},d=function(e){if(e instanceof Date)return!1;if(null==e)return!0;var t,n=function(e){return"[object Number]"===Object.prototype.toString.call(e)};if(n(e))return n(t=e)&&"NaN"===t.toString();if(e.length>0)return!1;if(0===e.length)return!0;if("object"!=typeof e)return!0;for(var o=Object.keys(e),i=0,r=o[i];i<o.length;i+=1)if(Object.prototype.hasOwnProperty.call(e,r))return!1;return!0},c="undefined"!=typeof window?window.location.href:"",v=function(e){return _()?"":new URLSearchParams(window.location.search).get(e)},p=function(){return"undefined"!=typeof window?(window.location.pathname+window.location.search).slice(1):""},f=function(e){if(e){var t=e.match(/h_(\d+)[,\/]/);return t&&t[1]?parseInt(t[1],10):void 0}},w=function(e){if(e){var t=e.match(/w_(\d+)[,\/]/);return t&&t[1]?parseInt(t[1],10):void 0}},_=function(){return"undefined"==typeof window||!window};function g(e,t){var n=t||l(document,["cookie"]);if(n){for(var o=e+"=",i=n.split(";"),r=0;r<i.length;r++){for(var a=i[r];" "==a.charAt(0);)a=a.substring(1,a.length);if(0==a.indexOf(o))return a.substring(o.length,a.length)}return""}return""}var m=function(e){try{if(!e||Number.isNaN(Number(e)))return"";var t=new Date(1e3*e),n=t.getFullYear(),o=String(t.getDate()).padStart(2,"0"),i=String(t.getMonth()+1).padStart(2,"0");return"".concat(n,"-").concat(i,"-").concat(o)}catch(e){return""}};var h=function(){var e,t=null===(e=l(window,["navigator","userAgent"]))||void 0===e?void 0:e.toLowerCase(),o=/safari/.test(t),i=/iphone|ipod|ipad/.test(t);return l(window,["androidData","app-agent"])&&l(window,["androidData","js-version"])||"function"==typeof l(window,["MobileApp","getAppSpecificData"])?n.Platform.ANDROID:l(window,["iosData","app-agent"])&&l(window,["iosData","js-version"])||i&&!o?n.Platform.IOS:n.Platform.PWA},y=function(){var e,t,o=h();return o===n.Platform.IOS?null!==(e=l(window,["iosData","app-agent"]))&&void 0!==e?e:n.AppAgent.IOS:o===n.Platform.ANDROID?null!==(t=l(window,["androidData","app-agent"]))&&void 0!==t?t:n.AppAgent.ANDROID:n.AppAgent.PWA},S=function(){if(_())return n.AppAgent.H_UNKNOWN;var e=h();return e===n.Platform.IOS?n.AppAgent.H_IOS:(e===n.Platform.ANDROID&&n.AppAgent.H_ANDROID,n.AppAgent.H_PWA)},b=function(){var e="";return A()?e=l(window,["iosData","js-version"]):P()&&(e=l(window,["androidData","js-version"])),e&&(e=e.toString().split(".")[0]),e},I=function(){var e,t,n,o;if(!_())return"";var i=new a.default(null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.userAgent);return null!==(o=null===(n=null===(t=null==i?void 0:i.getDevice())||void 0===t?void 0:t.model)||void 0===n?void 0:n.toLowerCase())&&void 0!==o?o:""},N=function(){return h()!==n.Platform.ANDROID&&h()!==n.Platform.IOS},P=function(){return h()===n.Platform.ANDROID},O=function(e){return parseInt(b())>=e},A=function(){return h()===n.Platform.IOS},x=u(),D=function(o,i,r,a,l,d,c){return void 0===i&&(i=n.RequestMethods.GET),void 0===a&&(a={}),void 0===l&&(l={}),void 0===d&&(d=!1),void 0===c&&(c={}),e.__awaiter(void 0,void 0,void 0,(function(){var v,p,f,w,g,m,S,b,N,P;return e.__generator(this,(function(O){switch(O.label){case 0:return v=function(e,t){var o=n.API_ROUTES[e];if(o&&o.trim().length){if(o=s(x,o),null==t?void 0:t.pathParams)for(var i=0,r=Object.entries(t.pathParams);i<r.length;i++){var a=r[i],u=a[0],l=a[1];o=o.replace(":".concat(u),l)}return(null==t?void 0:t.queryParams)&&(o+="?".concat(new URLSearchParams(t.queryParams).toString())),o}}(o,l),v&&v.trim().length?(p="",f="",w=u(),_()||(p=h(),f=JSON.stringify(function(o){var i={trackingId:t.v4(),source:n.SOURCE_NAME};return _()?e.__assign(e.__assign({},i),null!=o?o:{}):e.__assign(e.__assign(e.__assign({},i),{platform:y(),deviceModel:I()}),null!=o?o:{})}(c))),g={method:i,headers:e.__assign({channel:p,Caller:x,Origin:x,Referer:x,Authority:w,x_ct_sourcetype:"MOBILE","app-agent":y(),"x-unified-header":f,"Content-Type":"application/json"},a)},r&&(g.body=JSON.stringify(r)),[4,fetch(v,g)]):[2,Promise.reject("URL parameter missing")];case 1:return S=O.sent(),b={name:"API_FAILURE",status:S.status,message:"UNKNOWN_ERROR",statusText:S.statusText},(null==S?void 0:S.ok)?[3,3]:d?[2,Promise.reject(b)]:[4,S.json()];case 2:throw N=O.sent().message,b.message=N,b;case 3:return(null==(P=S.headers.get("content-type"))?void 0:P.includes("application/json"))?[4,S.json()]:[3,5];case 4:return m=O.sent(),[3,9];case 5:return(null==P?void 0:P.includes("text"))?[4,S.text()]:[3,7];case 6:return m=O.sent(),[3,9];case 7:return 204===S.status?[3,9]:[4,S.blob()];case 8:m=O.sent(),O.label=9;case 9:return[2,{data:m,status:S.status}]}}))}))},E=function(t,o,i,r,a){return void 0===o&&(o={}),void 0===i&&(i={}),void 0===r&&(r=!1),void 0===a&&(a={}),e.__awaiter(void 0,void 0,void 0,(function(){return e.__generator(this,(function(s){return[2,D(t,n.RequestMethods.GET,null,e.__assign({expires:"0",accept:"application/json","cache-control":"no-cache"},o),i,r,a)]}))}))},T=function(t,o,i,r,a,s,u){return void 0===o&&(o=n.RequestMethods.POST),void 0===i&&(i={}),void 0===r&&(r={}),void 0===a&&(a={}),void 0===s&&(s=!1),void 0===u&&(u={}),e.__awaiter(void 0,void 0,void 0,(function(){return e.__generator(this,(function(n){return[2,D(t,o,i,e.__assign({expires:"0",accept:"application/json","cache-control":"no-cache"},r),a,s,u)]}))}))},k=function(e){var t="",o=e.match(n.MOBILE_CONSTANTS.REGEX);return o&&(t=o[0].replace(/\D/g,"")),t},M=function(){var e,t,n;null===(n=null===(t=null===(e=window.webkit)||void 0===e?void 0:e.messageHandlers)||void 0===t?void 0:t.PWA_IS_SIGNIN)||void 0===n||n.postMessage({isSignIn:!0})},R=function(){var e;null===(e=window.MobileApp)||void 0===e||e.onPWALoginStatus(JSON.stringify({isSignIn:!0}))},C=function(){return e.__awaiter(void 0,void 0,void 0,(function(){var t,n;return e.__generator(this,(function(e){return(null===(n=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===n?void 0:n.get)&&"OTPCredential"in window?(t=new AbortController,setTimeout((function(){t.abort()}),6e4),[2,navigator.credentials.get({otp:{transport:["sms"]},signal:t.signal}).then((function(e){return null==e?void 0:e.code}))]):[2,Promise.reject("NOT_SUPPORTED")]}))}))},U=function(){return e.__awaiter(void 0,void 0,void 0,(function(){var t,n;return e.__generator(this,(function(e){return n=new Promise((function(e){t=e})),window.sendOtpValue=function(e){t(e)},[2,n]}))}))},L=function(t,o,i){return e.__awaiter(void 0,void 0,void 0,(function(){var r,a;return e.__generator(this,(function(e){switch(e.label){case 0:return r=u(),[4,T("FK_REDIRECTION_INFO",n.RequestMethods.POST,{provider:"flipkart",fallbackUri:s(r,t||i),signupPageUri:s(r,o||"personal-details"),currentPageUri:s(r,i)})];case 1:return[2,null==(a=e.sent())?void 0:a.data]}}))}))},j=function(e){var t,n=null!==(t=null==e?void 0:e.params)&&void 0!==t?t:{},o=null==e?void 0:e.redirectUri;if(o){for(var i in o+="?",n)o+=i+"="+n[i]+"&";return Promise.resolve(o)}return Promise.reject()},q=function(t){var n,o,i=null==t?void 0:t.params;if(d(i)||"function"!=typeof(null===(n=window.MobileApp)||void 0===n?void 0:n.onNavigationChange))return Promise.reject();var r=s(u(),"dl/oauth2");return null===(o=window.MobileApp)||void 0===o||o.onNavigationChange(JSON.stringify({type:"FkSSO",miscData:e.__assign(e.__assign({},i),{redirectURI:r})})),Promise.resolve()};function H(e){try{var t=decodeURIComponent(g("userid",e)||"").split("|");return{email:t[0],profileName:t[1],gender:t[2],photo:t[3],userId:t[4]}}catch(e){return{}}}var F=function(e){var t=H(e)||{};return!!(decodeURIComponent(g("usermisc",e)||"").split("|").includes("SIGNED_IN")&&t.userId&&t.userId.length>0)},G=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var n;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,E("USER_INSIGHTS",{},{pathParams:{userId:t}})];case 1:return[2,null==(n=e.sent())?void 0:n.data];case 2:return e.sent(),[2,Promise.resolve(null)];case 3:return[2]}}))}))},B=function(t){return e.__awaiter(void 0,void 0,void 0,(function(){var n,o,i,r,a,s,u,l;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),(n=null!=t?t:H().userId)?(o=null===(s=null===window||void 0===window?void 0:window.sessionStorage)||void 0===s?void 0:s.getItem("martech_user_attributes"),i=void 0,"string"==typeof o&&(i=JSON.parse(o)),n!==(null==i?void 0:i.accountId)&&(null===(u=null===window||void 0===window?void 0:window.sessionStorage)||void 0===u||u.removeItem("martech_user_attributes")),[4,G(n)]):(null===(a=null===window||void 0===window?void 0:window.sessionStorage)||void 0===a||a.removeItem("martech_user_attributes"),[2,null]);case 1:return r=e.sent(),d(null==r?void 0:r.data)?[2,null]:(null===(l=null===window||void 0===window?void 0:window.sessionStorage)||void 0===l||l.setItem("martech_user_attributes",JSON.stringify(null==r?void 0:r.data)),[2,null==r?void 0:r.data]);case 2:return e.sent(),[2,null];case 3:return[2]}}))}))},J=function(e){return Object.keys(e).forEach((function(t){e[t]="a_fare_price"===t||"a_ct_discount"===t||"supercoin_balance"===t||"supercoin_earned"===t||"supercoin_burnt"===t||"wallet_balance_used"===t||"convenience_fee"===t?Number(e[t]):""+e[t]})),e},W=function(){try{if(_())return"";var e=g("ct_statsig_experiments")||"{}",t=e?JSON.parse(decodeURIComponent(e)):{};return Object.keys(t).map((function(e){return e&&t[e]?"".concat(e,":").concat(t[e]):""})).filter((function(e){return!!e})).join("|")}catch(e){return""}},V=function(t,n){var o;if(window&&window.ravenWebManager){var i=Y(),r={page_name:i.pageName,u_utm_source:i.utmSource,domain:window.location.host,u_ab_key:W(),platform:null===(o=h())||void 0===o?void 0:o.toLowerCase(),login_status:F()?"yes":"no"},a=J(n),s=window.ravenWebManager;null==s||s.triggerRaven(t,e.__assign(e.__assign({},r),a))}},K=function(){if(window&&"undefined"!=typeof window){var e=l(window,["location","pathname"]);if("/"===e||"/flights"===e)return!0}return!1},Y=function(){var e,t;if(window&&"undefined"!=typeof window){var n=window.location.pathname,o=null!==(e=v("service"))&&void 0!==e?e:"",i=null!==(t=v("utm_source"))&&void 0!==t?t:"organic",r=K()?"skippable_login":"account_login",a="air",s=n.includes("flights/itinerary")||o.includes("flights/itinerary")?"a_itinerary":"a_home";return o.includes("my-account")&&(a="uar",s="account"),o.includes("hotels")&&(a="hotel",s=o.includes("hotels/itinerary")?"h_itinerary":"h_home"),o.includes("bus")&&(a="bus",s=o.includes("bus/itinerary")?"b_itinerary":"b_home"),{loginForm:r,vertical:a,pageName:s,utmSource:i}}return{}},Q=function(e){var t,n,o,i,r,a,s,u,l;d(e)||(null===(t=null===window||void 0===window?void 0:window.sessionStorage)||void 0===t?void 0:t.getItem("martech_user_props_sent"))||(A()&&(null===(o=null===(n=null===window||void 0===window?void 0:window.webkit)||void 0===n?void 0:n.messageHandlers)||void 0===o?void 0:o.SEND_ATTRIBUTES)?(null===(i=window.webkit.messageHandlers.SEND_ATTRIBUTES)||void 0===i||i.postMessage({type:"GA",params:e}),null===(r=window.webkit.messageHandlers.SEND_ATTRIBUTES)||void 0===r||r.postMessage({type:"Clevertap",params:e}),null===(a=null===window||void 0===window?void 0:window.sessionStorage)||void 0===a||a.setItem("martech_user_props_sent","true")):P()&&(null===(s=null===window||void 0===window?void 0:window.MobileApp)||void 0===s?void 0:s.sendAttributes)?(window.MobileApp.sendAttributes("GA",JSON.stringify(e)),window.MobileApp.sendAttributes("Clevertap",JSON.stringify(e)),null===(u=null===window||void 0===window?void 0:window.sessionStorage)||void 0===u||u.setItem("martech_user_props_sent","true")):N()&&window.clevertap&&(window.clevertap.profile.push({Site:e}),null===(l=null===window||void 0===window?void 0:window.sessionStorage)||void 0===l||l.setItem("martech_user_props_sent","true")))};exports.MULTI_SPACE=/\s\s+/g,exports.autoReadOtp=function(){return e.__awaiter(void 0,void 0,void 0,(function(){return e.__generator(this,(function(e){return[2,P()?U():C()]}))}))},exports.batchRavenEvent=function(e,t){"undefined"!=typeof window&&"function"==typeof window.requestIdleCallback?requestIdleCallback((function(){V(e,t)})):setTimeout((function(){V(e,t)}),0)},exports.createAPIRequest=D,exports.createGetRequest=E,exports.createPostOrPutRequest=T,exports.extractQueryParamsAsObj=function(e){try{var t=new URL(e),n=new URLSearchParams(t.search),o={};return n.forEach((function(e,t){o[t]=e})),o}catch(e){return{}}},exports.formatCurrency=function(e,t){void 0===t&&(t=!0);try{var n={currency:"INR",minimumFractionDigits:0};return t&&(n.style="currency"),"string"!=typeof e&&(e=null==e?void 0:e.toString()),e=e.replace(/,/g,""),parseInt(e,10).toLocaleString("en-IN",n)}catch(e){return""}},exports.formatFullDateString=function(e,t,n){void 0===t&&(t="dd-mm-yyyy"),void 0===n&&(n="");try{var o=new Date(e),i=o.getFullYear(),r=String(o.getDate()).padStart(2,"0"),a=String(o.getMonth()+1).padStart(2,"0");return"yyyy-mm-dd"===t?"".concat(i,"-").concat(a,"-").concat(r):"".concat(r,"-").concat(a,"-").concat(i)}catch(e){return n}},exports.getApiDomain=u,exports.getAppAgent=y,exports.getAppAgentForHotelUnifiedHeader=S,exports.getAutoDetectedMobile=k,exports.getCTStatsigExpForRaven=W,exports.getCookie=g,exports.getCurrentPathName=p,exports.getCurrentUrl=c,exports.getDeviceModel=I,exports.getDevicePlatform=h,exports.getDimensionFromImageUrl=function(e){void 0===e&&(e="");var t=f(e)||0,n=w(e)||0;return{height:"".concat(t,"px"),width:"".concat(n,"px"),heightInNumber:t,widthInNumber:n}},exports.getHeightFromImgUrl=f,exports.getHotelCrossSellRecos=function(t,n,o,i,r,a,s,u){return void 0===o&&(o=450),void 0===i&&(i="Discounts"),void 0===r&&(r="on hotels"),void 0===a&&(a="CTBEST - Exclusive coupon applied for you!"),void 0===s&&(s={}),void 0===u&&(u={}),e.__awaiter(void 0,void 0,void 0,(function(){var l,d,c,v,p,f;return e.__generator(this,(function(w){switch(w.label){case 0:l=null!==(f=null===(p=H())||void 0===p?void 0:p.userId)&&void 0!==f?f:"",d={couponCode:"",couponCallOut:"",couponCallOutPrefix:i,couponCallOutSuffix:r,offerCallOut:a,pageLandingUrl:n},w.label=1;case 1:return w.trys.push([1,3,,4]),c=new Promise((function(e){setTimeout((function(){e(d)}),o)})),v=E("HOTEL_RECOMMENDATIONS",s,{queryParams:e.__assign({userId:l,vertical:t},u)},!1,{userBuckets:{"x-cross-sell":"true"},platform:S()}).then((function(e){return e.data})),[4,Promise.race([v,c])];case 2:return[2,w.sent()];case 3:return w.sent(),[2,d];case 4:return[2]}}))}))},exports.getJSVersion=b,exports.getNestedValue=l,exports.getNoOfDaysFromToday=function(e){var t=new Date(e),n=new Date;n.setHours(12,0,0,0),t.setHours(12,0,0,0);var o=(t.getTime()-n.getTime())/864e5;return Math.round(o)},exports.getQueryParam=v,exports.getRavenEventProps=Y,exports.getUserAuthValues=H,exports.getWidthFromImgUrl=w,exports.handleFKSSO=function(t,o){return e.__awaiter(void 0,void 0,void 0,(function(){var i,r;return e.__generator(this,(function(e){switch(e.label){case 0:return A()?[2,Promise.reject()]:(i=p(),[4,L(t,o?i:n.NAVIGATION_ROUTES.PERSONAL_DETAILS+"?onboardingFlow=true",i)]);case 1:return r=e.sent(),P()?[2,q(r)]:[2,j(r)]}}))}))},exports.handleProfileFetch=function(t){return void 0===t&&(t=!0),e.__awaiter(void 0,void 0,void 0,(function(){var n;return e.__generator(this,(function(o){switch(o.label){case 0:return[4,e.__awaiter(void 0,void 0,void 0,(function(){var t,n;return e.__generator(this,(function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,E("GET_PROFILE_DETAILS",{caller:u(),"app-agent":y()},{})];case 1:return[2,null==(t=e.sent())?void 0:t.data];case 2:return n=e.sent(),console.error("Failed to fetch user details. Error: ",n),[2,Promise.resolve(null)];case 3:return[2]}}))}))];case 1:return(n=o.sent())&&t&&function(e){var t,n,o,i,r,a;try{if(_()||!(null===window||void 0===window?void 0:window.clevertap)||d(e))return;var s={Identity:null!==(t=null==e?void 0:e.id)&&void 0!==t?t:"",Gender:null!==(n=null==e?void 0:e.gender)&&void 0!==n?n:"",Email:null!==(o=null==e?void 0:e.username)&&void 0!==o?o:"",Phone:"".concat(null==e?void 0:e.countryCode).concat(null==e?void 0:e.mobile),"MSG-sms":!0,"MSG-push":!0,"MSG-email":!1,"MSG-whatsapp":!0};if(null===(i=null==e?void 0:e.travellerDetails)||void 0===i?void 0:i.length)for(var u=0;u<(null===(r=null==e?void 0:e.travellerDetails)||void 0===r?void 0:r.length);u++){var l=null==e?void 0:e.travellerDetails[u];if(l.isRegistered){var c=l.personalDetails.dateOfBirth;s.Name="".concat(l.personalDetails.firstName," ").concat(l.personalDetails.lastName),isNaN(c)||(s.DOB=new Date(c));break}}null===(a=null===window||void 0===window?void 0:window.clevertap)||void 0===a||a.onUserLogin.push({Site:s})}catch(e){console.log("Error pushing clevertap profile information. Error: ",e)}}(n),[2]}}))}))},exports.handlePushPrimerCTA=function(e){var t,n,o,i,r,a,s,u;P()&&"function"==typeof(null===(t=window.MobileApp)||void 0===t?void 0:t.handlePNPermission)?null===(n=window.MobileApp)||void 0===n||n.handlePNPermission(JSON.stringify({type:e})):A()&&(null===(i=null===(o=null===window||void 0===window?void 0:window.webkit)||void 0===o?void 0:o.messageHandlers)||void 0===i?void 0:i.HANDLE_PN_PERMISSION)&&(null===(u=null===(s=null===(a=null===(r=window.webkit)||void 0===r?void 0:r.messageHandlers)||void 0===a?void 0:a.HANDLE_PN_PERMISSION)||void 0===s?void 0:s.postMessage)||void 0===u||u.call(s,JSON.stringify({type:e})))},exports.isAirHomePage=K,exports.isAndroidApp=P,exports.isEmpty=d,exports.isFKSSOEnabled=function(){return N()||!A()&&O(5)},exports.isHTMLInputElement=function(e){return"object"==typeof e&&null!==e&&"value"in e&&e instanceof HTMLInputElement},exports.isIOSApp=A,exports.isJSVersionUpdated=O,exports.isNumeric=function(e){return/^[0-9]*$/.test(e)},exports.isPwa=N,exports.isServer=_,exports.isUserSignedIn=F,exports.isValidMobileNumber=function(e){return(null==e?void 0:e.length)===n.MOBILE_CONSTANTS.LENGTH&&/^\d{10}$/.test(e)},exports.path=function(e,t){return e.reduce((function(e,t){return e&&e[t]?e[t]:null}),t)},exports.ravenSDKTrigger=V,exports.secondsToDateString=m,exports.sendEventWithUserInsights=function(t,n,o){return e.__awaiter(void 0,void 0,void 0,(function(){var i,r,a,s,u,l,c,v,p,f,w,_,g,h,y,S,b,I,N,P;return e.__generator(this,(function(O){switch(O.label){case 0:return[4,B(o)];case 1:return i=O.sent(),r=e.__assign(e.__assign({},n),{fk_loyalty_status:"na",fk_loyalty_end_dt:"na",ct_last_booking_dt:"na",ct_lifetime_booking:"na",fk_loyalty_start_dt:"na",ct_first_booking_dt:"na",myntra_loyalty_status:"na",ct_postmerger_booking:"na",ct_last_1year_booking:"na",myntra_loyalty_end_dt:"na",ct_2nd_last_booking_dt:"na",myntra_loyalty_start_dt:"na"}),d(i)||(a=(null!==(u=null==i?void 0:i.loyaltyStatus)&&void 0!==u?u:[]).reduce((function(t,n){return e.__assign(e.__assign({},t),n)}),{}),s={ct_lifetime_booking:(null!==(c=null===(l=null==i?void 0:i.bookingStatus)||void 0===l?void 0:l.lifetimeBooking)&&void 0!==c?c:"na").toString(),ct_postmerger_booking:(null!==(p=null===(v=null==i?void 0:i.bookingStatus)||void 0===v?void 0:v.postmergerBooking)&&void 0!==p?p:"na").toString(),ct_last_1year_booking:(null!==(w=null===(f=null==i?void 0:i.bookingStatus)||void 0===f?void 0:f.lastOneYearBooking)&&void 0!==w?w:"na").toString(),ct_first_booking_dt:m(null===(_=null==i?void 0:i.bookingStatus)||void 0===_?void 0:_.firstbookingDate)||"na",ct_last_booking_dt:m(null===(g=null==i?void 0:i.bookingStatus)||void 0===g?void 0:g.lastbookingDate)||"na",ct_2nd_last_booking_dt:m(null===(h=null==i?void 0:i.bookingStatus)||void 0===h?void 0:h.secondLastbookingDate)||"na",fk_loyalty_status:(null===(y=null==a?void 0:a.fk)||void 0===y?void 0:y.program)||"na",myntra_loyalty_status:(null===(S=null==a?void 0:a.myntra)||void 0===S?void 0:S.program)||"na",fk_loyalty_end_dt:m(null===(b=null==a?void 0:a.fk)||void 0===b?void 0:b.loyaltyEndDate)||"",fk_loyalty_start_dt:m(null===(I=null==a?void 0:a.fk)||void 0===I?void 0:I.loyaltyStartDate)||"na",myntra_loyalty_start_dt:m(null===(N=null==a?void 0:a.myntra)||void 0===N?void 0:N.loyaltyStartDate)||"na",myntra_loyalty_end_dt:m(null===(P=null==a?void 0:a.myntra)||void 0===P?void 0:P.loyaltyEndDate)||"na"},r=e.__assign(e.__assign({},r),s),Q(s)),V(t,r),[2]}}))}))},exports.sendLoginOtp=function(t,o){return e.__awaiter(void 0,void 0,void 0,(function(){var i;return e.__generator(this,(function(e){switch(e.label){case 0:return[4,T("SEND_OTP",n.RequestMethods.POST,{value:t,type:"MOBILE",action:"SIGNIN",countryCode:n.MOBILE_CONSTANTS.COUNTRY_CODE},{"ab-otp":"b",dvid_data:o})];case 1:return[2,null==(i=e.sent())?void 0:i.data]}}))}))},exports.setCookie=function(e){var t,n=e.cookieName,o=e.cookieValue,i=e.expiryInDay,r=e.expiryInHours,a=e.expiryInMinutes,s=new Date;i?(s.setTime(s.getTime()+24*i*60*60*1e3),t=s.toUTCString()):r?(s.setTime(s.getTime()+3600*r*1e3),t=s.toUTCString()):a?(s.setTime(s.getTime()+60*a*1e3),t=s.toUTCString()):t="",document.cookie="".concat(n,"=").concat(o,"; expires=").concat(t,"; path=/")},exports.setMartechUserProperties=Q,exports.shouldShowPushPrimer=function(){return e.__awaiter(void 0,void 0,void 0,(function(){var t,n;return e.__generator(this,(function(e){return P()&&"function"==typeof(null===(t=window.MobileApp)||void 0===t?void 0:t.isPNPermissionEnabled)?[2,Promise.resolve(!(null===(n=window.MobileApp)||void 0===n?void 0:n.isPNPermissionEnabled()))]:A()?[2,new Promise((function(e,t){var n,o,i,r;window.pushNotifcationPermissionStatus=function(t){var n=JSON.parse(t),o=null==n?void 0:n.status;"boolean"==typeof o&&e(!o)};try{null===(r=null===(i=null===(o=null===(n=null===window||void 0===window?void 0:window.webkit)||void 0===n?void 0:n.messageHandlers)||void 0===o?void 0:o.IS_PN_PERMISSION_ENABLED)||void 0===i?void 0:i.postMessage)||void 0===r||r.call(i,"")}catch(t){e(!1)}}))]:[2,Promise.resolve(!1)]}))}))},exports.showMobileNumberHint=function(){var e;if("function"==typeof(null===(e=window.MobileApp)||void 0===e?void 0:e.onRequestMobileNumber)){var t;window.MobileApp.onRequestMobileNumber();var n=new Promise((function(e){t=e}));return window.sendSelectedMobileNumber=function(e){return t(k(e))},n}return Promise.resolve("")},exports.stringifyPayload=J,exports.triggerOTPListener=function(){var e;P()&&(null===(e=window.MobileApp)||void 0===e||e.onPageStart("OTP_SCREEN"))},exports.updateNativeAndroidOnSignIn=R,exports.updateNativeIOSOnSignIn=M,exports.updateNativeOnLogin=function(){A()?M():P()&&R()},exports.urlJoin=s,exports.validateOtp=function(t,o){return e.__awaiter(void 0,void 0,void 0,(function(){var r,a;return e.__generator(this,(function(s){switch(s.label){case 0:return[4,T("VALIDATE_OTP",n.RequestMethods.POST,{otp:o,value:t,type:"MOBILE",action:"SIGNIN",countryCode:"+91"},{"ab-otp":"b"})];case 1:return r=s.sent(),a=null==r?void 0:r.data,[2,e.__assign(e.__assign({},r),{signup:(null==a?void 0:a.action)===i.ValidateOTPAction.SIGNUP,action:null==a?void 0:a.action,status:null==r?void 0:r.status})]}}))}))};
1150
2
  //# sourceMappingURL=ct-platform-utils.cjs.js.map