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