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