@cleartrip/ct-platform-utils 3.11.1-beta.5 → 3.11.2

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