@cleartrip/ct-platform-utils 3.14.1-beta.0 → 3.15.0

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