@cleartrip/ct-platform-utils 3.11.3-beta.0 → 3.11.3

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,905 +1,2 @@
1
- import { __awaiter, __generator, __assign } from 'tslib';
2
- import { Platform, AppAgent, RequestMethods, API_ROUTES, MOBILE_CONSTANTS } from '@cleartrip/ct-platform-constants';
3
- import { ValidateOTPAction } from '@cleartrip/ct-platform-types';
4
-
5
- var urlJoin = function () {
6
- var parts = [];
7
- for (var _i = 0; _i < arguments.length; _i++) {
8
- parts[_i] = arguments[_i];
9
- }
10
- var trimmedParts = parts.map(function (part) { return part.trim().replace(/^[/]+/, ''); });
11
- var joinedParts = trimmedParts.join('/');
12
- joinedParts = joinedParts.replace(/\/\?/g, '?');
13
- return joinedParts;
14
- };
15
- var getApiDomain = function () {
16
- var domain = typeof window !== 'undefined' ? window.location.hostname : '';
17
- console.log('API_BASE domain', domain);
18
- switch (domain) {
19
- case 'localhost':
20
- case '0.0.0.0':
21
- case 'qa2new.cleartrip.com':
22
- return 'https://qa2new.cleartrip.com';
23
- case 'qa2.cleartrip.com':
24
- return 'https://qa2.cleartrip.com';
25
- case 'qa3new.cleartrip.com':
26
- return 'https://qa3new.cleartrip.com';
27
- case 'www.cleartrip.com':
28
- default:
29
- return 'https://www.cleartrip.com';
30
- }
31
- };
32
- var getNestedValue = function (data, path) {
33
- var reducerFunction = function (prev, current) {
34
- return prev && prev[current] ? prev[current] : null;
35
- };
36
- return path.reduce(reducerFunction, data);
37
- };
38
- var path = function (p, o) {
39
- return p.reduce(function (prev, curr) {
40
- return prev && prev[curr] ? prev[curr] : null;
41
- }, o);
42
- };
43
- var MULTI_SPACE = /\s\s+/g;
44
- var isEmpty = function (obj) {
45
- if (obj instanceof Date) {
46
- return false;
47
- }
48
- if (obj == null) {
49
- return true;
50
- }
51
- var isNumber = function (value) {
52
- return Object.prototype.toString.call(value) === '[object Number]';
53
- };
54
- var isNaN = function (value) { return isNumber(value) && value.toString() === 'NaN'; };
55
- if (isNumber(obj)) {
56
- return isNaN(obj);
57
- }
58
- if (obj.length > 0) {
59
- return false;
60
- }
61
- if (obj.length === 0) {
62
- return true;
63
- }
64
- if (typeof obj !== 'object') {
65
- return true;
66
- }
67
- var keys = Object.keys(obj);
68
- for (var i = 0, key = keys[i]; i < keys.length; i += 1) {
69
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
70
- return false;
71
- }
72
- }
73
- return true;
74
- };
75
- var isHTMLInputElement = function (ref) {
76
- return (typeof ref === 'object' &&
77
- ref !== null &&
78
- 'value' in ref &&
79
- ref instanceof HTMLInputElement);
80
- };
81
- var isNumeric = function (value) {
82
- return /^[0-9]*$/.test(value);
83
- };
84
- var getCurrentUrl = typeof window !== 'undefined' ? window.location.href : '';
85
- var getQueryParam = function (queryParam) {
86
- if (isServer()) {
87
- return '';
88
- }
89
- var urlParams = new URLSearchParams(window.location.search);
90
- return urlParams.get(queryParam);
91
- };
92
- var getCurrentPathName = function () {
93
- return typeof window !== 'undefined'
94
- ? (window.location.pathname + window.location.search).slice(1)
95
- : '';
96
- };
97
- var getHeightFromImgUrl = function (url) {
98
- if (!url) {
99
- return;
100
- }
101
- var regex = /h_(\d+)[,\/]/;
102
- var match = url.match(regex);
103
- if (match && match[1]) {
104
- return parseInt(match[1], 10);
105
- }
106
- return;
107
- };
108
- var getWidthFromImgUrl = function (url) {
109
- if (!url) {
110
- return;
111
- }
112
- var regex = /w_(\d+)[,\/]/;
113
- var match = url.match(regex);
114
- if (match && match[1]) {
115
- return parseInt(match[1], 10);
116
- }
117
- return;
118
- };
119
- var isServer = function () {
120
- return typeof window === 'undefined' || !window;
121
- };
122
- function getCookie(name, customCookie) {
123
- var _cookie = customCookie || getNestedValue(document, ['cookie']);
124
- if (_cookie) {
125
- var nameEQ = name + '=';
126
- var ca = _cookie.split(';');
127
- for (var i = 0; i < ca.length; i++) {
128
- var c = ca[i];
129
- while (c.charAt(0) == ' ')
130
- c = c.substring(1, c.length);
131
- if (c.indexOf(nameEQ) == 0)
132
- return c.substring(nameEQ.length, c.length);
133
- }
134
- return '';
135
- }
136
- else {
137
- return '';
138
- }
139
- }
140
- var getDimensionFromImageUrl = function (url) {
141
- if (url === void 0) { url = ''; }
142
- var height = getHeightFromImgUrl(url) || 0;
143
- var width = getWidthFromImgUrl(url) || 0;
144
- return {
145
- height: "".concat(height, "px"),
146
- width: "".concat(width, "px"),
147
- heightInNumber: height,
148
- widthInNumber: width,
149
- };
150
- };
151
- var secondsToDateString = function (sec) {
152
- try {
153
- if (!sec || Number.isNaN(Number(sec))) {
154
- return '';
155
- }
156
- var date = new Date(sec * 1000);
157
- var year = date.getFullYear();
158
- var day = String(date.getDate()).padStart(2, '0');
159
- var month = String(date.getMonth() + 1).padStart(2, '0');
160
- return "".concat(year, "-").concat(month, "-").concat(day);
161
- }
162
- catch (_e) {
163
- return '';
164
- }
165
- };
166
- var formatFullDateString = function (dateString, format, fallback) {
167
- if (format === void 0) { format = 'dd-mm-yyyy'; }
168
- if (fallback === void 0) { fallback = ''; }
169
- try {
170
- var date = new Date(dateString);
171
- var year = date.getFullYear();
172
- var day = String(date.getDate()).padStart(2, '0');
173
- var month = String(date.getMonth() + 1).padStart(2, '0');
174
- switch (format) {
175
- case 'yyyy-mm-dd':
176
- return "".concat(year, "-").concat(month, "-").concat(day);
177
- case 'dd-mm-yyyy':
178
- default:
179
- return "".concat(day, "-").concat(month, "-").concat(year);
180
- }
181
- }
182
- catch (_e) {
183
- return fallback;
184
- }
185
- };
186
- var formatCurrency = function (value, withIcon) {
187
- if (withIcon === void 0) { withIcon = true; }
188
- try {
189
- var config = {
190
- currency: 'INR',
191
- minimumFractionDigits: 0,
192
- };
193
- if (withIcon) {
194
- config.style = 'currency';
195
- }
196
- if (typeof value !== 'string') {
197
- value = value === null || value === void 0 ? void 0 : value.toString();
198
- }
199
- value = value.replace(/,/g, '');
200
- return parseInt(value, 10).toLocaleString('en-IN', config);
201
- }
202
- catch (_e) {
203
- return '';
204
- }
205
- };
206
-
207
- var getDevicePlatform = function () {
208
- var _a;
209
- var userAgent = (_a = getNestedValue(window, [
210
- 'navigator',
211
- 'userAgent',
212
- ])) === null || _a === void 0 ? void 0 : _a.toLowerCase();
213
- var safariBrowser = /safari/.test(userAgent);
214
- var appleDevice = /iphone|ipod|ipad/.test(userAgent);
215
- if ((getNestedValue(window, ['androidData', 'app-agent']) &&
216
- getNestedValue(window, ['androidData', 'js-version'])) ||
217
- typeof getNestedValue(window, ['MobileApp', 'getAppSpecificData']) ===
218
- 'function') {
219
- return Platform.ANDROID;
220
- }
221
- else if ((getNestedValue(window, ['iosData', 'app-agent']) &&
222
- getNestedValue(window, ['iosData', 'js-version'])) ||
223
- (appleDevice && !safariBrowser)) {
224
- return Platform.IOS;
225
- }
226
- return Platform.PWA;
227
- };
228
- var getAppAgent = function () {
229
- var _a, _b;
230
- var platform = getDevicePlatform();
231
- if (platform === Platform.IOS) {
232
- return (_a = getNestedValue(window, ['iosData', 'app-agent'])) !== null && _a !== void 0 ? _a : AppAgent.IOS;
233
- }
234
- else if (platform === Platform.ANDROID) {
235
- return ((_b = getNestedValue(window, ['androidData', 'app-agent'])) !== null && _b !== void 0 ? _b : AppAgent.ANDROID);
236
- }
237
- return AppAgent.PWA;
238
- };
239
- var getJSVersion = function () {
240
- var jsVersion = '';
241
- if (isIOSApp()) {
242
- jsVersion = getNestedValue(window, ['iosData', 'js-version']);
243
- }
244
- else if (isAndroidApp()) {
245
- jsVersion = getNestedValue(window, ['androidData', 'js-version']);
246
- }
247
- if (jsVersion) {
248
- jsVersion = jsVersion.toString().split('.')[0];
249
- }
250
- return jsVersion;
251
- };
252
- var isPwa = function () {
253
- return getDevicePlatform() !== Platform.ANDROID &&
254
- getDevicePlatform() !== Platform.IOS;
255
- };
256
- var isAndroidApp = function () {
257
- return getDevicePlatform() === Platform.ANDROID;
258
- };
259
- var isJSVersionUpdated = function (compareVersion) {
260
- return parseInt(getJSVersion()) >= compareVersion;
261
- };
262
- var isIOSApp = function () { return getDevicePlatform() === Platform.IOS; };
263
-
264
- var API_BASE = getApiDomain();
265
- var getRequestUrl = function (path, params) {
266
- var url = API_ROUTES[path];
267
- if (!url || !url.trim().length) {
268
- return;
269
- }
270
- url = urlJoin(API_BASE, url);
271
- if (params === null || params === void 0 ? void 0 : params.pathParams) {
272
- for (var _i = 0, _a = Object.entries(params.pathParams); _i < _a.length; _i++) {
273
- var _b = _a[_i], key = _b[0], value = _b[1];
274
- url = url.replace(":".concat(key), value);
275
- }
276
- }
277
- if (params === null || params === void 0 ? void 0 : params.queryParams) {
278
- url += "?".concat(new URLSearchParams(params.queryParams).toString());
279
- }
280
- return url;
281
- };
282
- var createAPIRequest = function (path, method, payload, headers, params, useCustomErrorHandler) {
283
- if (method === void 0) { method = RequestMethods.GET; }
284
- if (headers === void 0) { headers = {}; }
285
- if (params === void 0) { params = {}; }
286
- if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
287
- return __awaiter(void 0, void 0, void 0, function () {
288
- var url, API_AUTHORITY, requestOptions, responseData, response, error, message, contentType;
289
- return __generator(this, function (_a) {
290
- switch (_a.label) {
291
- case 0:
292
- url = getRequestUrl(path, params);
293
- if (!url || !url.trim().length) {
294
- return [2, Promise.reject('URL parameter missing')];
295
- }
296
- API_AUTHORITY = getApiDomain();
297
- requestOptions = {
298
- method: method,
299
- headers: __assign({ Caller: API_BASE, Origin: API_BASE, Referer: API_BASE, Authority: API_AUTHORITY, x_ct_sourcetype: 'MOBILE', 'app-agent': getAppAgent(), 'Content-Type': 'application/json' }, headers),
300
- };
301
- if (payload) {
302
- requestOptions.body = JSON.stringify(payload);
303
- }
304
- return [4, fetch(url, requestOptions)];
305
- case 1:
306
- response = _a.sent();
307
- error = {
308
- name: 'API_FAILURE',
309
- status: response.status,
310
- message: 'UNKNOWN_ERROR',
311
- statusText: response.statusText,
312
- };
313
- if (!!(response === null || response === void 0 ? void 0 : response.ok)) return [3, 3];
314
- if (useCustomErrorHandler) {
315
- return [2, Promise.reject(error)];
316
- }
317
- return [4, response.json()];
318
- case 2:
319
- message = (_a.sent()).message;
320
- error.message = message;
321
- throw error;
322
- case 3:
323
- contentType = response.headers.get('content-type');
324
- if (!(contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json'))) return [3, 5];
325
- return [4, response.json()];
326
- case 4:
327
- responseData = _a.sent();
328
- return [3, 9];
329
- case 5:
330
- if (!(contentType === null || contentType === void 0 ? void 0 : contentType.includes('text'))) return [3, 7];
331
- return [4, response.text()];
332
- case 6:
333
- responseData = _a.sent();
334
- return [3, 9];
335
- case 7:
336
- if (!(response.status !== 204)) return [3, 9];
337
- return [4, response.blob()];
338
- case 8:
339
- responseData = _a.sent();
340
- _a.label = 9;
341
- case 9: return [2, {
342
- data: responseData,
343
- status: response.status,
344
- }];
345
- }
346
- });
347
- });
348
- };
349
- var createGetRequest = function (path, headers, params, useCustomErrorHandler) {
350
- if (headers === void 0) { headers = {}; }
351
- if (params === void 0) { params = {}; }
352
- if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
353
- return __awaiter(void 0, void 0, void 0, function () {
354
- return __generator(this, function (_a) {
355
- return [2, createAPIRequest(path, RequestMethods.GET, null, __assign({ expires: '0', accept: 'application/json', 'cache-control': 'no-cache' }, headers), params, useCustomErrorHandler)];
356
- });
357
- });
358
- };
359
- var createPostOrPutRequest = function (path, method, payload, headers, params, useCustomErrorHandler) {
360
- if (method === void 0) { method = RequestMethods.POST; }
361
- if (payload === void 0) { payload = {}; }
362
- if (headers === void 0) { headers = {}; }
363
- if (params === void 0) { params = {}; }
364
- if (useCustomErrorHandler === void 0) { useCustomErrorHandler = false; }
365
- return __awaiter(void 0, void 0, void 0, function () {
366
- return __generator(this, function (_a) {
367
- return [2, createAPIRequest(path, method, payload, __assign({ expires: '0', accept: 'application/json', 'cache-control': 'no-cache' }, headers), params, useCustomErrorHandler)];
368
- });
369
- });
370
- };
371
-
372
- var showMobileNumberHint = function () {
373
- var _a;
374
- if (typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onRequestMobileNumber) === 'function') {
375
- window.MobileApp.onRequestMobileNumber();
376
- var promiseResolver_1;
377
- var mobileNoPromise = new Promise(function (resolve) {
378
- promiseResolver_1 = resolve;
379
- });
380
- window.sendSelectedMobileNumber = function (mobileNum) {
381
- return promiseResolver_1(getAutoDetectedMobile(mobileNum));
382
- };
383
- return mobileNoPromise;
384
- }
385
- return Promise.resolve('');
386
- };
387
- var getAutoDetectedMobile = function (mobileNumber) {
388
- var formattedMobileNo = '';
389
- var matches = mobileNumber.match(MOBILE_CONSTANTS.REGEX);
390
- if (matches) {
391
- formattedMobileNo = matches[0].replace(/\D/g, '');
392
- }
393
- return formattedMobileNo;
394
- };
395
- var autoReadOtp = function () { return __awaiter(void 0, void 0, void 0, function () {
396
- return __generator(this, function (_a) {
397
- return [2, isAndroidApp() ? readOtpAndroid() : readOtpPWA()];
398
- });
399
- }); };
400
- var updateNativeIOSOnSignIn = function () {
401
- var _a, _b, _c;
402
- (_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({
403
- isSignIn: true,
404
- });
405
- };
406
- var updateNativeAndroidOnSignIn = function () {
407
- var _a;
408
- (_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onPWALoginStatus(JSON.stringify({
409
- isSignIn: true,
410
- }));
411
- };
412
- var triggerOTPListener = function () {
413
- var _a;
414
- if (isAndroidApp()) {
415
- (_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onPageStart('OTP_SCREEN');
416
- }
417
- };
418
- var readOtpPWA = function () { return __awaiter(void 0, void 0, void 0, function () {
419
- var abortController;
420
- var _a;
421
- return __generator(this, function (_b) {
422
- if (!((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.get) || !('OTPCredential' in window)) {
423
- return [2, Promise.reject('NOT_SUPPORTED')];
424
- }
425
- abortController = new AbortController();
426
- setTimeout(function () {
427
- abortController.abort();
428
- }, 60000);
429
- return [2, navigator.credentials
430
- .get({
431
- otp: { transport: ['sms'] },
432
- signal: abortController.signal,
433
- })
434
- .then(function (content) { return content === null || content === void 0 ? void 0 : content.code; })];
435
- });
436
- }); };
437
- var readOtpAndroid = function () { return __awaiter(void 0, void 0, void 0, function () {
438
- var promiseResolver, otpPromise;
439
- return __generator(this, function (_a) {
440
- otpPromise = new Promise(function (resolve) {
441
- promiseResolver = resolve;
442
- });
443
- window.sendOtpValue = function (otp) {
444
- promiseResolver(otp);
445
- };
446
- return [2, otpPromise];
447
- });
448
- }); };
449
- var shouldShowPushPrimer = function () { return __awaiter(void 0, void 0, void 0, function () {
450
- var getValue_1, value_1, interval_1;
451
- var _a, _b, _c;
452
- return __generator(this, function (_d) {
453
- switch (_d.label) {
454
- case 0:
455
- if (!(isIOSApp() &&
456
- typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.IS_PN_PERMISSION_ENABLED) === 'function')) return [3, 2];
457
- getValue_1 = function () {
458
- var _a;
459
- return (_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.IS_PN_PERMISSION_ENABLED();
460
- };
461
- return [4, getValue_1()];
462
- case 1:
463
- value_1 = _d.sent();
464
- interval_1 = setInterval(function () { return __awaiter(void 0, void 0, void 0, function () {
465
- return __generator(this, function (_a) {
466
- switch (_a.label) {
467
- case 0: return [4, getValue_1()];
468
- case 1:
469
- value_1 = _a.sent();
470
- if (value_1 !== null) {
471
- clearInterval(interval_1);
472
- }
473
- return [2];
474
- }
475
- });
476
- }); }, 1000);
477
- return [2, value_1];
478
- case 2:
479
- if (isAndroidApp() &&
480
- typeof ((_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.isPNPermissionEnabled) === 'function') {
481
- return [2, (_c = window.MobileApp) === null || _c === void 0 ? void 0 : _c.isPNPermissionEnabled()];
482
- }
483
- _d.label = 3;
484
- case 3: return [2, false];
485
- }
486
- });
487
- }); };
488
- var handlePushPrimerCTA = function (type) {
489
- var _a, _b, _c, _d;
490
- if (isAndroidApp() &&
491
- typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.handlePNPermission) === 'function') {
492
- (_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.handlePNPermission(JSON.stringify({
493
- type: type,
494
- }));
495
- }
496
- else if (isIOSApp() &&
497
- typeof ((_c = window.MobileApp) === null || _c === void 0 ? void 0 : _c.HANDLE_PN_PERMISSION) === 'function') {
498
- (_d = window.MobileApp) === null || _d === void 0 ? void 0 : _d.HANDLE_PN_PERMISSION(JSON.stringify({
499
- type: type,
500
- }));
501
- }
502
- return '';
503
- };
504
-
505
- var sendLoginOtp = function (mobile, personalizationHeaders) { return __awaiter(void 0, void 0, void 0, function () {
506
- var response;
507
- return __generator(this, function (_a) {
508
- switch (_a.label) {
509
- case 0: return [4, createPostOrPutRequest('SEND_OTP', RequestMethods.POST, {
510
- value: mobile,
511
- type: 'MOBILE',
512
- action: 'SIGNIN',
513
- countryCode: MOBILE_CONSTANTS.COUNTRY_CODE,
514
- }, {
515
- 'ab-otp': 'b',
516
- dvid_data: personalizationHeaders,
517
- })];
518
- case 1:
519
- response = _a.sent();
520
- return [2, response === null || response === void 0 ? void 0 : response.data];
521
- }
522
- });
523
- }); };
524
- var validateOtp = function (mobile, otp) { return __awaiter(void 0, void 0, void 0, function () {
525
- var response, data;
526
- return __generator(this, function (_a) {
527
- switch (_a.label) {
528
- case 0: return [4, createPostOrPutRequest('VALIDATE_OTP', RequestMethods.POST, {
529
- otp: otp,
530
- value: mobile,
531
- type: 'MOBILE',
532
- action: 'SIGNIN',
533
- countryCode: '+91',
534
- }, { 'ab-otp': 'b' })];
535
- case 1:
536
- response = _a.sent();
537
- data = response === null || response === void 0 ? void 0 : response.data;
538
- return [2, __assign(__assign({}, response), { signup: (data === null || data === void 0 ? void 0 : data.action) === ValidateOTPAction.SIGNUP, action: data === null || data === void 0 ? void 0 : data.action, status: response === null || response === void 0 ? void 0 : response.status })];
539
- }
540
- });
541
- }); };
542
- var handleFKSSO = function (fallbackUri, signupPageUri, currentPageUri) { return __awaiter(void 0, void 0, void 0, function () {
543
- var redirectionInfo;
544
- return __generator(this, function (_a) {
545
- switch (_a.label) {
546
- case 0:
547
- if (isIOSApp()) {
548
- return [2, Promise.reject()];
549
- }
550
- return [4, sendFKSSORedirectionInfo(fallbackUri, signupPageUri, currentPageUri)];
551
- case 1:
552
- redirectionInfo = _a.sent();
553
- if (isAndroidApp()) {
554
- return [2, handleFKSSOAndroid(redirectionInfo)];
555
- }
556
- else {
557
- return [2, handleFKSSOWeb(redirectionInfo)];
558
- }
559
- }
560
- });
561
- }); };
562
- var isValidMobileNumber = function (text) {
563
- return (text === null || text === void 0 ? void 0 : text.length) === MOBILE_CONSTANTS.LENGTH && /^\d{10}$/.test(text);
564
- };
565
- var updateNativeOnLogin = function () {
566
- if (isIOSApp()) {
567
- updateNativeIOSOnSignIn();
568
- }
569
- else if (isAndroidApp()) {
570
- updateNativeAndroidOnSignIn();
571
- }
572
- };
573
- var isFKSSOEnabled = function () {
574
- return isPwa() || (!isIOSApp() && isJSVersionUpdated(5));
575
- };
576
- var sendFKSSORedirectionInfo = function (fallbackUri, signupPageUri, currentPageUri) { return __awaiter(void 0, void 0, void 0, function () {
577
- var WEBSITE_BASE, response;
578
- return __generator(this, function (_a) {
579
- switch (_a.label) {
580
- case 0:
581
- WEBSITE_BASE = getApiDomain();
582
- return [4, createPostOrPutRequest('FK_REDIRECTION_INFO', RequestMethods.POST, {
583
- provider: 'flipkart',
584
- fallbackUri: urlJoin(WEBSITE_BASE, fallbackUri || getCurrentPathName()),
585
- signupPageUri: urlJoin(WEBSITE_BASE, signupPageUri || 'personal-details'),
586
- currentPageUri: urlJoin(WEBSITE_BASE, currentPageUri),
587
- })];
588
- case 1:
589
- response = _a.sent();
590
- return [2, response === null || response === void 0 ? void 0 : response.data];
591
- }
592
- });
593
- }); };
594
- var handleFKSSOWeb = function (redirectionInfo) {
595
- var _a;
596
- var params = (_a = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.params) !== null && _a !== void 0 ? _a : {};
597
- var redirectUri = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.redirectUri;
598
- if (redirectUri) {
599
- redirectUri += '?';
600
- for (var key in params) {
601
- redirectUri += key + '=' + params[key] + '&';
602
- }
603
- return Promise.resolve(redirectUri);
604
- }
605
- return Promise.reject();
606
- };
607
- var handleFKSSOAndroid = function (redirectionInfo) {
608
- var _a, _b;
609
- var params = redirectionInfo === null || redirectionInfo === void 0 ? void 0 : redirectionInfo.params;
610
- if (isEmpty(params) ||
611
- typeof ((_a = window.MobileApp) === null || _a === void 0 ? void 0 : _a.onNavigationChange) !== 'function') {
612
- return Promise.reject();
613
- }
614
- else {
615
- var FK_REDIRECT_DL = urlJoin(getApiDomain(), 'dl/oauth2');
616
- (_b = window.MobileApp) === null || _b === void 0 ? void 0 : _b.onNavigationChange(JSON.stringify({
617
- type: 'FkSSO',
618
- miscData: __assign(__assign({}, params), { redirectURI: FK_REDIRECT_DL }),
619
- }));
620
- return Promise.resolve();
621
- }
622
- };
623
- function getUserAuthValues(customCookie) {
624
- try {
625
- var _a = decodeURIComponent(getCookie('userid', customCookie) || '').split('|'), email = _a[0], profileName = _a[1], gender = _a[2], photo = _a[3], userId = _a[4];
626
- return {
627
- email: email,
628
- profileName: profileName,
629
- gender: gender,
630
- photo: photo,
631
- userId: userId,
632
- };
633
- }
634
- catch (error) {
635
- return {};
636
- }
637
- }
638
- var isUserSignedIn = function (customCookie) {
639
- var userObject = getUserAuthValues(customCookie) || {};
640
- var usermiscVal = decodeURIComponent(getCookie('usermisc', customCookie) || '').split('|');
641
- var signedIn = usermiscVal.includes('SIGNED_IN') &&
642
- userObject.userId &&
643
- userObject.userId.length > 0
644
- ? true
645
- : false;
646
- return signedIn;
647
- };
648
-
649
- var getUserInsights = function (userId) { return __awaiter(void 0, void 0, void 0, function () {
650
- var response;
651
- return __generator(this, function (_a) {
652
- switch (_a.label) {
653
- case 0:
654
- _a.trys.push([0, 2, , 3]);
655
- return [4, createGetRequest('USER_INSIGHTS', {}, {
656
- pathParams: {
657
- userId: userId,
658
- },
659
- })];
660
- case 1:
661
- response = _a.sent();
662
- return [2, response === null || response === void 0 ? void 0 : response.data];
663
- case 2:
664
- _a.sent();
665
- return [2, Promise.resolve(null)];
666
- case 3: return [2];
667
- }
668
- });
669
- }); };
670
- var getUserInsightsData = function (userId) { return __awaiter(void 0, void 0, void 0, function () {
671
- var _userId, stringifiedData, sessionData, userInsights;
672
- var _a, _b, _c, _d;
673
- return __generator(this, function (_f) {
674
- switch (_f.label) {
675
- case 0:
676
- _f.trys.push([0, 2, , 3]);
677
- _userId = userId !== null && userId !== void 0 ? userId : getUserAuthValues().userId;
678
- if (!_userId) {
679
- (_a = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _a === void 0 ? void 0 : _a.removeItem('martech_user_attributes');
680
- return [2, null];
681
- }
682
- stringifiedData = (_b = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _b === void 0 ? void 0 : _b.getItem('martech_user_attributes');
683
- sessionData = void 0;
684
- if (typeof stringifiedData === 'string') {
685
- sessionData = JSON.parse(stringifiedData);
686
- }
687
- if (_userId !== (sessionData === null || sessionData === void 0 ? void 0 : sessionData.accountId)) {
688
- (_c = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _c === void 0 ? void 0 : _c.removeItem('martech_user_attributes');
689
- }
690
- return [4, getUserInsights(_userId)];
691
- case 1:
692
- userInsights = _f.sent();
693
- if (isEmpty(userInsights === null || userInsights === void 0 ? void 0 : userInsights.data)) {
694
- return [2, null];
695
- }
696
- (_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));
697
- return [2, userInsights === null || userInsights === void 0 ? void 0 : userInsights.data];
698
- case 2:
699
- _f.sent();
700
- return [2, null];
701
- case 3: return [2];
702
- }
703
- });
704
- }); };
705
-
706
- var stringifyPayload = function (payload) {
707
- var keys = Object.keys(payload);
708
- keys.forEach(function (key) {
709
- if (key === 'a_fare_price' ||
710
- key === 'a_ct_discount' ||
711
- key === 'supercoin_balance' ||
712
- key === 'supercoin_earned' ||
713
- key === 'supercoin_burnt' ||
714
- key === 'wallet_balance_used' ||
715
- key === 'convenience_fee')
716
- payload[key] = Number(payload[key]);
717
- else
718
- payload[key] = '' + payload[key];
719
- });
720
- return payload;
721
- };
722
- var ravenSDKTrigger = function (eventName, ravenPayload) {
723
- var _a;
724
- if (window && window['ravenWebManager']) {
725
- var _b = getRavenEventProps(), pageName = _b.pageName, utmSource = _b.utmSource;
726
- var commonPayload = {
727
- page_name: pageName,
728
- u_utm_source: utmSource,
729
- domain: window.location.host,
730
- platform: (_a = getDevicePlatform()) === null || _a === void 0 ? void 0 : _a.toLowerCase(),
731
- login_status: isUserSignedIn() ? 'yes' : 'no',
732
- };
733
- var newRavenPayload = stringifyPayload(ravenPayload);
734
- var RavenWebManager = window['ravenWebManager'];
735
- RavenWebManager === null || RavenWebManager === void 0 ? void 0 : RavenWebManager.triggerRaven(eventName, __assign(__assign({}, commonPayload), newRavenPayload));
736
- }
737
- };
738
- var isAirHomePage = function () {
739
- if (window && typeof window !== 'undefined') {
740
- var pathname = getNestedValue(window, ['location', 'pathname']);
741
- if (pathname === '/' || pathname === '/flights') {
742
- return true;
743
- }
744
- }
745
- return false;
746
- };
747
- var getRavenEventProps = function () {
748
- var _a, _b;
749
- if (window && typeof window !== 'undefined') {
750
- var pathUrl = window.location.pathname;
751
- var redirectionPath = (_a = getQueryParam('service')) !== null && _a !== void 0 ? _a : '';
752
- var utmSource = (_b = getQueryParam('utm_source')) !== null && _b !== void 0 ? _b : 'organic';
753
- var loginForm = isAirHomePage() ? 'skippable_login' : 'account_login';
754
- var vertical = 'air';
755
- var pageName = pathUrl.includes('flights/itinerary') ||
756
- redirectionPath.includes('flights/itinerary')
757
- ? 'a_itinerary'
758
- : 'a_home';
759
- if (redirectionPath.includes('my-account')) {
760
- vertical = 'uar';
761
- pageName = 'account';
762
- }
763
- if (redirectionPath.includes('hotels')) {
764
- vertical = 'hotel';
765
- pageName = redirectionPath.includes('hotels/itinerary')
766
- ? 'h_itinerary'
767
- : 'h_home';
768
- }
769
- if (redirectionPath.includes('bus')) {
770
- vertical = 'bus';
771
- pageName = redirectionPath.includes('bus/itinerary')
772
- ? 'b_itinerary'
773
- : 'b_home';
774
- }
775
- return { loginForm: loginForm, vertical: vertical, pageName: pageName, utmSource: utmSource };
776
- }
777
- return {};
778
- };
779
- var sendEventWithUserInsights = function (eventName, ravenPayload, userId) { return __awaiter(void 0, void 0, void 0, function () {
780
- var userInsights, updatedPayload, loyaltyData, martechAttributes;
781
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
782
- return __generator(this, function (_s) {
783
- switch (_s.label) {
784
- case 0: return [4, getUserInsightsData(userId)];
785
- case 1:
786
- userInsights = _s.sent();
787
- updatedPayload = __assign(__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' });
788
- if (!isEmpty(userInsights)) {
789
- loyaltyData = ((_a = userInsights === null || userInsights === void 0 ? void 0 : userInsights.loyaltyStatus) !== null && _a !== void 0 ? _a : []).reduce(function (prev, curr) {
790
- return __assign(__assign({}, prev), curr);
791
- }, {});
792
- martechAttributes = {
793
- 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(),
794
- ct_postmerger_booking: ((_e = (_d = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _d === void 0 ? void 0 : _d.postmergerBooking) !== null && _e !== void 0 ? _e : 'na').toString(),
795
- ct_last_1year_booking: ((_g = (_f = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _f === void 0 ? void 0 : _f.lastOneYearBooking) !== null && _g !== void 0 ? _g : 'na').toString(),
796
- ct_first_booking_dt: secondsToDateString((_h = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _h === void 0 ? void 0 : _h.firstbookingDate) || 'na',
797
- ct_last_booking_dt: secondsToDateString((_j = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _j === void 0 ? void 0 : _j.lastbookingDate) || 'na',
798
- ct_2nd_last_booking_dt: secondsToDateString((_k = userInsights === null || userInsights === void 0 ? void 0 : userInsights.bookingStatus) === null || _k === void 0 ? void 0 : _k.secondLastbookingDate) || 'na',
799
- fk_loyalty_status: ((_l = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _l === void 0 ? void 0 : _l.program) || 'na',
800
- myntra_loyalty_status: ((_m = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _m === void 0 ? void 0 : _m.program) || 'na',
801
- fk_loyalty_end_dt: secondsToDateString((_o = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _o === void 0 ? void 0 : _o.loyaltyEndDate) || '',
802
- fk_loyalty_start_dt: secondsToDateString((_p = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.fk) === null || _p === void 0 ? void 0 : _p.loyaltyStartDate) || 'na',
803
- myntra_loyalty_start_dt: secondsToDateString((_q = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _q === void 0 ? void 0 : _q.loyaltyStartDate) ||
804
- 'na',
805
- myntra_loyalty_end_dt: secondsToDateString((_r = loyaltyData === null || loyaltyData === void 0 ? void 0 : loyaltyData.myntra) === null || _r === void 0 ? void 0 : _r.loyaltyEndDate) ||
806
- 'na',
807
- };
808
- updatedPayload = __assign(__assign({}, updatedPayload), martechAttributes);
809
- setMartechUserProperties(martechAttributes);
810
- }
811
- ravenSDKTrigger(eventName, updatedPayload);
812
- return [2];
813
- }
814
- });
815
- }); };
816
- var setMartechUserProperties = function (userProperties) {
817
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
818
- if (isEmpty(userProperties) ||
819
- ((_a = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _a === void 0 ? void 0 : _a.getItem('martech_user_props_sent'))) {
820
- return;
821
- }
822
- 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)) {
823
- (_d = window.webkit.messageHandlers.SEND_ATTRIBUTES) === null || _d === void 0 ? void 0 : _d.postMessage({
824
- type: 'GA',
825
- params: userProperties,
826
- });
827
- (_e = window.webkit.messageHandlers.SEND_ATTRIBUTES) === null || _e === void 0 ? void 0 : _e.postMessage({
828
- type: 'Clevertap',
829
- params: userProperties,
830
- });
831
- (_f = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _f === void 0 ? void 0 : _f.setItem('martech_user_props_sent', 'true');
832
- }
833
- else if (isAndroidApp() && ((_g = window === null || window === void 0 ? void 0 : window.MobileApp) === null || _g === void 0 ? void 0 : _g.sendAttributes)) {
834
- window.MobileApp.sendAttributes('GA', JSON.stringify(userProperties));
835
- window.MobileApp.sendAttributes('Clevertap', JSON.stringify(userProperties));
836
- (_h = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _h === void 0 ? void 0 : _h.setItem('martech_user_props_sent', 'true');
837
- }
838
- else if (isPwa() && window.clevertap) {
839
- window.clevertap.profile.push({
840
- Site: userProperties,
841
- });
842
- (_j = window === null || window === void 0 ? void 0 : window.sessionStorage) === null || _j === void 0 ? void 0 : _j.setItem('martech_user_props_sent', 'true');
843
- }
844
- };
845
- var batchRavenEvent = function (eventName, ravenPayload) {
846
- if (typeof window !== 'undefined' &&
847
- typeof window.requestIdleCallback === 'function') {
848
- requestIdleCallback(function () {
849
- ravenSDKTrigger(eventName, ravenPayload);
850
- });
851
- }
852
- else {
853
- setTimeout(function () {
854
- ravenSDKTrigger(eventName, ravenPayload);
855
- }, 0);
856
- }
857
- };
858
-
859
- var getHotelCrossSellRecos = function (vertical, fallbackPageLandingURL, cutoff) {
860
- if (cutoff === void 0) { cutoff = 450; }
861
- return __awaiter(void 0, void 0, void 0, function () {
862
- var userId, fallbackData, timeoutPromise, fetchRecommendationsPromise, result;
863
- var _a, _b;
864
- return __generator(this, function (_c) {
865
- switch (_c.label) {
866
- case 0:
867
- userId = (_b = (_a = getUserAuthValues()) === null || _a === void 0 ? void 0 : _a.userId) !== null && _b !== void 0 ? _b : '';
868
- fallbackData = {
869
- couponCode: '',
870
- offerCallOut: 'FLYER EXCLUSIVE COUPON UNLOCKED FOR YOU',
871
- couponCallOut: 'Offer applied on hotels',
872
- pageLandingUrl: fallbackPageLandingURL,
873
- };
874
- _c.label = 1;
875
- case 1:
876
- _c.trys.push([1, 3, , 4]);
877
- timeoutPromise = new Promise(function (resolve) {
878
- setTimeout(function () {
879
- resolve(fallbackData);
880
- }, cutoff);
881
- });
882
- fetchRecommendationsPromise = createGetRequest('HOTEL_RECOMMENDATIONS', {}, {
883
- queryParams: {
884
- userId: userId,
885
- vertical: vertical,
886
- },
887
- }).then(function (res) { return res.data; });
888
- return [4, Promise.race([
889
- fetchRecommendationsPromise,
890
- timeoutPromise,
891
- ])];
892
- case 2:
893
- result = _c.sent();
894
- return [2, result];
895
- case 3:
896
- _c.sent();
897
- return [2, fallbackData];
898
- case 4: return [2];
899
- }
900
- });
901
- });
902
- };
903
-
904
- export { MULTI_SPACE, autoReadOtp, batchRavenEvent, createAPIRequest, createGetRequest, createPostOrPutRequest, formatCurrency, formatFullDateString, getApiDomain, getAppAgent, getAutoDetectedMobile, getCookie, getCurrentPathName, getCurrentUrl, getDevicePlatform, getDimensionFromImageUrl, getHeightFromImgUrl, getHotelCrossSellRecos, getJSVersion, getNestedValue, getQueryParam, getRavenEventProps, getUserAuthValues, getWidthFromImgUrl, handleFKSSO, handlePushPrimerCTA, isAirHomePage, isAndroidApp, isEmpty, isFKSSOEnabled, isHTMLInputElement, isIOSApp, isJSVersionUpdated, isNumeric, isPwa, isServer, isUserSignedIn, isValidMobileNumber, path, ravenSDKTrigger, secondsToDateString, sendEventWithUserInsights, sendLoginOtp, setMartechUserProperties, shouldShowPushPrimer, showMobileNumberHint, stringifyPayload, triggerOTPListener, updateNativeAndroidOnSignIn, updateNativeIOSOnSignIn, updateNativeOnLogin, urlJoin, validateOtp };
1
+ import{__awaiter as n,__generator as t,__assign as o}from"tslib";import{Platform as e,AppAgent as i,RequestMethods as r,API_ROUTES as a,MOBILE_CONSTANTS as u}from"@cleartrip/ct-platform-constants";import{ValidateOTPAction as l}from"@cleartrip/ct-platform-types";var d=function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var o=n.map((function(n){return n.trim().replace(/^[/]+/,"")})).join("/");return o=o.replace(/\/\?/g,"?")},s=function(){var n="undefined"!=typeof window?window.location.hostname:"";switch(console.log("API_BASE domain",n),n){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"}},c=function(n,t){return t.reduce((function(n,t){return n&&n[t]?n[t]:null}),n)},v=function(n,t){return n.reduce((function(n,t){return n&&n[t]?n[t]:null}),t)},f=/\s\s+/g,w=function(n){if(n instanceof Date)return!1;if(null==n)return!0;var t,o=function(n){return"[object Number]"===Object.prototype.toString.call(n)};if(o(n))return o(t=n)&&"NaN"===t.toString();if(n.length>0)return!1;if(0===n.length)return!0;if("object"!=typeof n)return!0;for(var e=Object.keys(n),i=0,r=e[i];i<e.length;i+=1)if(Object.prototype.hasOwnProperty.call(n,r))return!1;return!0},p=function(n){return"object"==typeof n&&null!==n&&"value"in n&&n instanceof HTMLInputElement},g=function(n){return/^[0-9]*$/.test(n)},m="undefined"!=typeof window?window.location.href:"",_=function(n){return S()?"":new URLSearchParams(window.location.search).get(n)},h=function(){return"undefined"!=typeof window?(window.location.pathname+window.location.search).slice(1):""},y=function(n){if(n){var t=n.match(/h_(\d+)[,\/]/);return t&&t[1]?parseInt(t[1],10):void 0}},b=function(n){if(n){var t=n.match(/w_(\d+)[,\/]/);return t&&t[1]?parseInt(t[1],10):void 0}},S=function(){return"undefined"==typeof window||!window};function I(n,t){var o=t||c(document,["cookie"]);if(o){for(var e=n+"=",i=o.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(e))return a.substring(e.length,a.length)}return""}return""}var N=function(n){void 0===n&&(n="");var t=y(n)||0,o=b(n)||0;return{height:"".concat(t,"px"),width:"".concat(o,"px"),heightInNumber:t,widthInNumber:o}},O=function(n){try{if(!n||Number.isNaN(Number(n)))return"";var t=new Date(1e3*n),o=t.getFullYear(),e=String(t.getDate()).padStart(2,"0"),i=String(t.getMonth()+1).padStart(2,"0");return"".concat(o,"-").concat(i,"-").concat(e)}catch(n){return""}},k=function(n,t,o){void 0===t&&(t="dd-mm-yyyy"),void 0===o&&(o="");try{var e=new Date(n),i=e.getFullYear(),r=String(e.getDate()).padStart(2,"0"),a=String(e.getMonth()+1).padStart(2,"0");return"yyyy-mm-dd"===t?"".concat(i,"-").concat(a,"-").concat(r):"".concat(r,"-").concat(a,"-").concat(i)}catch(n){return o}},D=function(n,t){void 0===t&&(t=!0);try{var o={currency:"INR",minimumFractionDigits:0};return t&&(o.style="currency"),"string"!=typeof n&&(n=null==n?void 0:n.toString()),n=n.replace(/,/g,""),parseInt(n,10).toLocaleString("en-IN",o)}catch(n){return""}},P=function(){var n,t=null===(n=c(window,["navigator","userAgent"]))||void 0===n?void 0:n.toLowerCase(),o=/safari/.test(t),i=/iphone|ipod|ipad/.test(t);return c(window,["androidData","app-agent"])&&c(window,["androidData","js-version"])||"function"==typeof c(window,["MobileApp","getAppSpecificData"])?e.ANDROID:c(window,["iosData","app-agent"])&&c(window,["iosData","js-version"])||i&&!o?e.IOS:e.PWA},A=function(){var n,t,o=P();return o===e.IOS?null!==(n=c(window,["iosData","app-agent"]))&&void 0!==n?n:i.IOS:o===e.ANDROID?null!==(t=c(window,["androidData","app-agent"]))&&void 0!==t?t:i.ANDROID:i.PWA},E=function(){var n="";return M()?n=c(window,["iosData","js-version"]):R()&&(n=c(window,["androidData","js-version"])),n&&(n=n.toString().split(".")[0]),n},T=function(){return P()!==e.ANDROID&&P()!==e.IOS},R=function(){return P()===e.ANDROID},C=function(n){return parseInt(E())>=n},M=function(){return P()===e.IOS},j=s(),U=function(e,i,u,l,c,v){return void 0===i&&(i=r.GET),void 0===l&&(l={}),void 0===c&&(c={}),void 0===v&&(v=!1),n(void 0,void 0,void 0,(function(){var n,r,f,w,p,g,m,_;return t(this,(function(t){switch(t.label){case 0:return n=function(n,t){var o=a[n];if(o&&o.trim().length){if(o=d(j,o),null==t?void 0:t.pathParams)for(var e=0,i=Object.entries(t.pathParams);e<i.length;e++){var r=i[e],u=r[0],l=r[1];o=o.replace(":".concat(u),l)}return(null==t?void 0:t.queryParams)&&(o+="?".concat(new URLSearchParams(t.queryParams).toString())),o}}(e,c),n&&n.trim().length?(r=s(),f={method:i,headers:o({Caller:j,Origin:j,Referer:j,Authority:r,x_ct_sourcetype:"MOBILE","app-agent":A(),"Content-Type":"application/json"},l)},u&&(f.body=JSON.stringify(u)),[4,fetch(n,f)]):[2,Promise.reject("URL parameter missing")];case 1:return p=t.sent(),g={name:"API_FAILURE",status:p.status,message:"UNKNOWN_ERROR",statusText:p.statusText},(null==p?void 0:p.ok)?[3,3]:v?[2,Promise.reject(g)]:[4,p.json()];case 2:throw m=t.sent().message,g.message=m,g;case 3:return(null==(_=p.headers.get("content-type"))?void 0:_.includes("application/json"))?[4,p.json()]:[3,5];case 4:return w=t.sent(),[3,9];case 5:return(null==_?void 0:_.includes("text"))?[4,p.text()]:[3,7];case 6:return w=t.sent(),[3,9];case 7:return 204===p.status?[3,9]:[4,p.blob()];case 8:w=t.sent(),t.label=9;case 9:return[2,{data:w,status:p.status}]}}))}))},L=function(e,i,a,u){return void 0===i&&(i={}),void 0===a&&(a={}),void 0===u&&(u=!1),n(void 0,void 0,void 0,(function(){return t(this,(function(n){return[2,U(e,r.GET,null,o({expires:"0",accept:"application/json","cache-control":"no-cache"},i),a,u)]}))}))},q=function(e,i,a,u,l,d){return void 0===i&&(i=r.POST),void 0===a&&(a={}),void 0===u&&(u={}),void 0===l&&(l={}),void 0===d&&(d=!1),n(void 0,void 0,void 0,(function(){return t(this,(function(n){return[2,U(e,i,a,o({expires:"0",accept:"application/json","cache-control":"no-cache"},u),l,d)]}))}))},G=function(){var n;if("function"==typeof(null===(n=window.MobileApp)||void 0===n?void 0:n.onRequestMobileNumber)){var t;window.MobileApp.onRequestMobileNumber();var o=new Promise((function(n){t=n}));return window.sendSelectedMobileNumber=function(n){return t(x(n))},o}return Promise.resolve("")},x=function(n){var t="",o=n.match(u.REGEX);return o&&(t=o[0].replace(/\D/g,"")),t},B=function(){return n(void 0,void 0,void 0,(function(){return t(this,(function(n){return[2,R()?Y():W()]}))}))},F=function(){var n,t,o;null===(o=null===(t=null===(n=window.webkit)||void 0===n?void 0:n.messageHandlers)||void 0===t?void 0:t.PWA_IS_SIGNIN)||void 0===o||o.postMessage({isSignIn:!0})},H=function(){var n;null===(n=window.MobileApp)||void 0===n||n.onPWALoginStatus(JSON.stringify({isSignIn:!0}))},J=function(){var n;R()&&(null===(n=window.MobileApp)||void 0===n||n.onPageStart("OTP_SCREEN"))},W=function(){return n(void 0,void 0,void 0,(function(){var n,o;return t(this,(function(t){return(null===(o=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===o?void 0:o.get)&&"OTPCredential"in window?(n=new AbortController,setTimeout((function(){n.abort()}),6e4),[2,navigator.credentials.get({otp:{transport:["sms"]},signal:n.signal}).then((function(n){return null==n?void 0:n.code}))]):[2,Promise.reject("NOT_SUPPORTED")]}))}))},Y=function(){return n(void 0,void 0,void 0,(function(){var n,o;return t(this,(function(t){return o=new Promise((function(t){n=t})),window.sendOtpValue=function(t){n(t)},[2,o]}))}))},K=function(o,e){return n(void 0,void 0,void 0,(function(){var n;return t(this,(function(t){switch(t.label){case 0:return[4,q("SEND_OTP",r.POST,{value:o,type:"MOBILE",action:"SIGNIN",countryCode:u.COUNTRY_CODE},{"ab-otp":"b",dvid_data:e})];case 1:return[2,null==(n=t.sent())?void 0:n.data]}}))}))},V=function(e,i){return n(void 0,void 0,void 0,(function(){var n,a;return t(this,(function(t){switch(t.label){case 0:return[4,q("VALIDATE_OTP",r.POST,{otp:i,value:e,type:"MOBILE",action:"SIGNIN",countryCode:"+91"},{"ab-otp":"b"})];case 1:return n=t.sent(),a=null==n?void 0:n.data,[2,o(o({},n),{signup:(null==a?void 0:a.action)===l.SIGNUP,action:null==a?void 0:a.action,status:null==n?void 0:n.status})]}}))}))},X=function(o,e,i){return n(void 0,void 0,void 0,(function(){var n;return t(this,(function(t){switch(t.label){case 0:return M()?[2,Promise.reject()]:[4,Z(o,e,i)];case 1:return n=t.sent(),R()?[2,tn(n)]:[2,nn(n)]}}))}))},$=function(n){return(null==n?void 0:n.length)===u.LENGTH&&/^\d{10}$/.test(n)},z=function(){M()?F():R()&&H()},Q=function(){return T()||!M()&&C(5)},Z=function(o,e,i){return n(void 0,void 0,void 0,(function(){var n,a;return t(this,(function(t){switch(t.label){case 0:return n=s(),[4,q("FK_REDIRECTION_INFO",r.POST,{provider:"flipkart",fallbackUri:d(n,o||h()),signupPageUri:d(n,e||"personal-details"),currentPageUri:d(n,i)})];case 1:return[2,null==(a=t.sent())?void 0:a.data]}}))}))},nn=function(n){var t,o=null!==(t=null==n?void 0:n.params)&&void 0!==t?t:{},e=null==n?void 0:n.redirectUri;if(e){for(var i in e+="?",o)e+=i+"="+o[i]+"&";return Promise.resolve(e)}return Promise.reject()},tn=function(n){var t,e,i=null==n?void 0:n.params;if(w(i)||"function"!=typeof(null===(t=window.MobileApp)||void 0===t?void 0:t.onNavigationChange))return Promise.reject();var r=d(s(),"dl/oauth2");return null===(e=window.MobileApp)||void 0===e||e.onNavigationChange(JSON.stringify({type:"FkSSO",miscData:o(o({},i),{redirectURI:r})})),Promise.resolve()};function on(n){try{var t=decodeURIComponent(I("userid",n)||"").split("|");return{email:t[0],profileName:t[1],gender:t[2],photo:t[3],userId:t[4]}}catch(n){return{}}}var en=function(n){var t=on(n)||{};return!!(decodeURIComponent(I("usermisc",n)||"").split("|").includes("SIGNED_IN")&&t.userId&&t.userId.length>0)},rn=function(o){return n(void 0,void 0,void 0,(function(){var n;return t(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,L("USER_INSIGHTS",{},{pathParams:{userId:o}})];case 1:return[2,null==(n=t.sent())?void 0:n.data];case 2:return t.sent(),[2,Promise.resolve(null)];case 3:return[2]}}))}))},an=function(o){return n(void 0,void 0,void 0,(function(){var n,e,i,r,a,u,l,d;return t(this,(function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),(n=null!=o?o:on().userId)?(e=null===(u=null===window||void 0===window?void 0:window.sessionStorage)||void 0===u?void 0:u.getItem("martech_user_attributes"),i=void 0,"string"==typeof e&&(i=JSON.parse(e)),n!==(null==i?void 0:i.accountId)&&(null===(l=null===window||void 0===window?void 0:window.sessionStorage)||void 0===l||l.removeItem("martech_user_attributes")),[4,rn(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=t.sent(),w(null==r?void 0:r.data)?[2,null]:(null===(d=null===window||void 0===window?void 0:window.sessionStorage)||void 0===d||d.setItem("martech_user_attributes",JSON.stringify(null==r?void 0:r.data)),[2,null==r?void 0:r.data]);case 2:return t.sent(),[2,null];case 3:return[2]}}))}))},un=function(n){return Object.keys(n).forEach((function(t){n[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(n[t]):""+n[t]})),n},ln=function(n,t){var e;if(window&&window.ravenWebManager){var i=sn(),r={page_name:i.pageName,u_utm_source:i.utmSource,domain:window.location.host,platform:null===(e=P())||void 0===e?void 0:e.toLowerCase(),login_status:en()?"yes":"no"},a=un(t),u=window.ravenWebManager;null==u||u.triggerRaven(n,o(o({},r),a))}},dn=function(){if(window&&"undefined"!=typeof window){var n=c(window,["location","pathname"]);if("/"===n||"/flights"===n)return!0}return!1},sn=function(){var n,t;if(window&&"undefined"!=typeof window){var o=window.location.pathname,e=null!==(n=_("service"))&&void 0!==n?n:"",i=null!==(t=_("utm_source"))&&void 0!==t?t:"organic",r=dn()?"skippable_login":"account_login",a="air",u=o.includes("flights/itinerary")||e.includes("flights/itinerary")?"a_itinerary":"a_home";return e.includes("my-account")&&(a="uar",u="account"),e.includes("hotels")&&(a="hotel",u=e.includes("hotels/itinerary")?"h_itinerary":"h_home"),e.includes("bus")&&(a="bus",u=e.includes("bus/itinerary")?"b_itinerary":"b_home"),{loginForm:r,vertical:a,pageName:u,utmSource:i}}return{}},cn=function(e,i,r){return n(void 0,void 0,void 0,(function(){var n,a,u,l,d,s,c,v,f,p,g,m,_,h,y,b,S,I,N,k;return t(this,(function(t){switch(t.label){case 0:return[4,an(r)];case 1:return n=t.sent(),a=o(o({},i),{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"}),w(n)||(u=(null!==(d=null==n?void 0:n.loyaltyStatus)&&void 0!==d?d:[]).reduce((function(n,t){return o(o({},n),t)}),{}),l={ct_lifetime_booking:(null!==(c=null===(s=null==n?void 0:n.bookingStatus)||void 0===s?void 0:s.lifetimeBooking)&&void 0!==c?c:"na").toString(),ct_postmerger_booking:(null!==(f=null===(v=null==n?void 0:n.bookingStatus)||void 0===v?void 0:v.postmergerBooking)&&void 0!==f?f:"na").toString(),ct_last_1year_booking:(null!==(g=null===(p=null==n?void 0:n.bookingStatus)||void 0===p?void 0:p.lastOneYearBooking)&&void 0!==g?g:"na").toString(),ct_first_booking_dt:O(null===(m=null==n?void 0:n.bookingStatus)||void 0===m?void 0:m.firstbookingDate)||"na",ct_last_booking_dt:O(null===(_=null==n?void 0:n.bookingStatus)||void 0===_?void 0:_.lastbookingDate)||"na",ct_2nd_last_booking_dt:O(null===(h=null==n?void 0:n.bookingStatus)||void 0===h?void 0:h.secondLastbookingDate)||"na",fk_loyalty_status:(null===(y=null==u?void 0:u.fk)||void 0===y?void 0:y.program)||"na",myntra_loyalty_status:(null===(b=null==u?void 0:u.myntra)||void 0===b?void 0:b.program)||"na",fk_loyalty_end_dt:O(null===(S=null==u?void 0:u.fk)||void 0===S?void 0:S.loyaltyEndDate)||"",fk_loyalty_start_dt:O(null===(I=null==u?void 0:u.fk)||void 0===I?void 0:I.loyaltyStartDate)||"na",myntra_loyalty_start_dt:O(null===(N=null==u?void 0:u.myntra)||void 0===N?void 0:N.loyaltyStartDate)||"na",myntra_loyalty_end_dt:O(null===(k=null==u?void 0:u.myntra)||void 0===k?void 0:k.loyaltyEndDate)||"na"},a=o(o({},a),l),vn(l)),ln(e,a),[2]}}))}))},vn=function(n){var t,o,e,i,r,a,u,l,d;w(n)||(null===(t=null===window||void 0===window?void 0:window.sessionStorage)||void 0===t?void 0:t.getItem("martech_user_props_sent"))||(M()&&(null===(e=null===(o=null===window||void 0===window?void 0:window.webkit)||void 0===o?void 0:o.messageHandlers)||void 0===e?void 0:e.SEND_ATTRIBUTES)?(null===(i=window.webkit.messageHandlers.SEND_ATTRIBUTES)||void 0===i||i.postMessage({type:"GA",params:n}),null===(r=window.webkit.messageHandlers.SEND_ATTRIBUTES)||void 0===r||r.postMessage({type:"Clevertap",params:n}),null===(a=null===window||void 0===window?void 0:window.sessionStorage)||void 0===a||a.setItem("martech_user_props_sent","true")):R()&&(null===(u=null===window||void 0===window?void 0:window.MobileApp)||void 0===u?void 0:u.sendAttributes)?(window.MobileApp.sendAttributes("GA",JSON.stringify(n)),window.MobileApp.sendAttributes("Clevertap",JSON.stringify(n)),null===(l=null===window||void 0===window?void 0:window.sessionStorage)||void 0===l||l.setItem("martech_user_props_sent","true")):T()&&window.clevertap&&(window.clevertap.profile.push({Site:n}),null===(d=null===window||void 0===window?void 0:window.sessionStorage)||void 0===d||d.setItem("martech_user_props_sent","true")))},fn=function(n,t){"undefined"!=typeof window&&"function"==typeof window.requestIdleCallback?requestIdleCallback((function(){ln(n,t)})):setTimeout((function(){ln(n,t)}),0)},wn=function(o,e,i){return void 0===i&&(i=450),n(void 0,void 0,void 0,(function(){var n,r,a,u,l,d;return t(this,(function(t){switch(t.label){case 0:n=null!==(d=null===(l=on())||void 0===l?void 0:l.userId)&&void 0!==d?d:"",r={couponCode:"",offerCallOut:"FLYER EXCLUSIVE COUPON UNLOCKED FOR YOU",couponCallOut:"Offer applied on hotels",pageLandingUrl:e},t.label=1;case 1:return t.trys.push([1,3,,4]),a=new Promise((function(n){setTimeout((function(){n(r)}),i)})),u=L("HOTEL_RECOMMENDATIONS",{},{queryParams:{userId:n,vertical:o}}).then((function(n){return n.data})),[4,Promise.race([u,a])];case 2:return[2,t.sent()];case 3:return t.sent(),[2,r];case 4:return[2]}}))}))};export{f as MULTI_SPACE,B as autoReadOtp,fn as batchRavenEvent,U as createAPIRequest,L as createGetRequest,q as createPostOrPutRequest,D as formatCurrency,k as formatFullDateString,s as getApiDomain,A as getAppAgent,x as getAutoDetectedMobile,I as getCookie,h as getCurrentPathName,m as getCurrentUrl,P as getDevicePlatform,N as getDimensionFromImageUrl,y as getHeightFromImgUrl,wn as getHotelCrossSellRecos,E as getJSVersion,c as getNestedValue,_ as getQueryParam,sn as getRavenEventProps,on as getUserAuthValues,b as getWidthFromImgUrl,X as handleFKSSO,dn as isAirHomePage,R as isAndroidApp,w as isEmpty,Q as isFKSSOEnabled,p as isHTMLInputElement,M as isIOSApp,C as isJSVersionUpdated,g as isNumeric,T as isPwa,S as isServer,en as isUserSignedIn,$ as isValidMobileNumber,v as path,ln as ravenSDKTrigger,O as secondsToDateString,cn as sendEventWithUserInsights,K as sendLoginOtp,vn as setMartechUserProperties,G as showMobileNumberHint,un as stringifyPayload,J as triggerOTPListener,H as updateNativeAndroidOnSignIn,F as updateNativeIOSOnSignIn,z as updateNativeOnLogin,d as urlJoin,V as validateOtp};
905
2
  //# sourceMappingURL=ct-platform-utils.esm.js.map