UNPKG

@microsoft/omnichannel-chat-sdk

Version:
839 lines 199 kB
"use strict"; /* eslint-disable @typescript-eslint/no-non-null-assertion */ var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); var loggers_1 = require("./utils/loggers"); var ACSClient_1 = require("./core/messaging/ACSClient"); var ChatSDKError_1 = require("./core/ChatSDKError"); var MessagePrinterFactory_1 = require("./utils/printers/MessagePrinterFactory"); var ocsdk_1 = require("@microsoft/ocsdk"); var chatAdapterCreators_1 = require("./utils/chatAdapterCreators"); var CoreServicesUtils_1 = require("./utils/CoreServicesUtils"); var locale_1 = require("./utils/locale"); var exceptionThrowers_1 = require("./utils/exceptionThrowers"); var utilities_1 = require("./utils/utilities"); var WebUtils_1 = require("./utils/WebUtils"); var AMSClientUtils_1 = require("./utils/AMSClientUtils"); var SDKConfigValidators_1 = require("./validators/SDKConfigValidators"); var ACSParticipantDisplayName_1 = require("./core/messaging/ACSParticipantDisplayName"); var AMSClientLoadStates_1 = require("./utils/AMSClientLoadStates"); var AMSFileManager_1 = require("./external/ACSAdapter/AMSFileManager"); var CallingOptionsOptionSetNumber_1 = require("./core/CallingOptionsOptionSetNumber"); var ChatAdapterProtocols_1 = require("./core/messaging/ChatAdapterProtocols"); var ConversationMode_1 = require("./core/ConversationMode"); var DeliveryMode_1 = require("@microsoft/omnichannel-ic3core/lib/model/DeliveryMode"); var FileSharingProtocolType_1 = require("@microsoft/omnichannel-ic3core/lib/model/FileSharingProtocolType"); var HostType_1 = require("@microsoft/omnichannel-ic3core/lib/interfaces/HostType"); var omnichannel_ic3core_1 = require("@microsoft/omnichannel-ic3core"); var LiveChatVersion_1 = require("./core/LiveChatVersion"); var LiveWorkItemState_1 = require("./core/LiveWorkItemState"); var MessageContentType_1 = require("@microsoft/omnichannel-ic3core/lib/model/MessageContentType"); var MessageSource_1 = require("./telemetry/MessageSource"); var MessageType_1 = require("@microsoft/omnichannel-ic3core/lib/model/MessageType"); var OmnichannelErrorCodes_1 = require("./core/OmnichannelErrorCodes"); var PersonType_1 = require("@microsoft/omnichannel-ic3core/lib/model/PersonType"); var ProtocoleType_1 = require("@microsoft/omnichannel-ic3core/lib/interfaces/ProtocoleType"); var ScenarioMarker_1 = require("./telemetry/ScenarioMarker"); var SurveyProvider_1 = require("./core/SurveyProvider"); var TelemetryEvent_1 = require("./telemetry/TelemetryEvent"); var settings_1 = require("./config/settings"); var omnichannel_amsclient_1 = require("@microsoft/omnichannel-amsclient"); var createOcSDKConfiguration_1 = require("./utils/createOcSDKConfiguration"); var createOmnichannelMessage_1 = require("./utils/createOmnichannelMessage"); var createTelemetry_1 = require("./utils/createTelemetry"); var createVoiceVideoCalling_1 = require("./api/createVoiceVideoCalling"); var MessageTags_1 = require("./core/messaging/MessageTags"); var exceptionSuppressors_1 = require("./utils/exceptionSuppressors"); var location_1 = require("./utils/location"); var internalUtils_1 = require("./utils/internalUtils"); var loggerUtils_1 = require("./utils/loggerUtils"); var parsers_1 = require("./utils/parsers"); var platform_1 = require("./utils/platform"); var retrieveCollectorUri_1 = require("./telemetry/retrieveCollectorUri"); var startPolling_1 = require("./commands/startPolling"); var stopPolling_1 = require("./commands/stopPolling"); var urlResolvers_1 = require("./utils/urlResolvers"); var OmnichannelConfigValidator_1 = require("./validators/OmnichannelConfigValidator"); var OmnichannelChatSDK = /** @class */ (function () { function OmnichannelChatSDK(omnichannelConfig, chatSDKConfig) { if (chatSDKConfig === void 0) { chatSDKConfig = SDKConfigValidators_1.defaultChatSDKConfig; } var _this = this; var _a, _b, _c, _d, _e, _f, _g; this.ACSClient = null; this.AMSClient = null; this.sessionId = null; // Operation queue for serializing chat operations this.chatOperationInProgress = false; this.pendingOperations = []; this.unqServicesOrgUrl = null; this.coreServicesOrgUrl = null; this.dynamicsLocationCode = null; this.widgetSnippetBaseUrl = ''; this.dataMaskingRules = { rules: [] }; this.authSettings = null; this.authenticatedUserToken = null; this.conversation = null; this.callingOption = CallingOptionsOptionSetNumber_1.default.NoCalling; this.telemetry = null; this.ic3ClientLogger = null; this.ocSdkLogger = null; this.acsClientLogger = null; this.acsAdapterLogger = null; this.callingSdkLogger = null; this.amsClientLogger = null; this.isPersistentChat = false; this.isChatReconnect = false; this.reconnectId = null; this.refreshTokenTimer = null; this.AMSClientLoadCurrentState = AMSClientLoadStates_1.AMSClientLoadStates.NOT_LOADED; this.isMaskingDisabled = false; this.maskingCharacter = "#"; this.botCSPId = null; this.isAMSClientAllowed = false; this.debugSDK = false; this.debugAMS = false; this.debugACS = false; this.detailedDebugEnabled = false; this.regexCompiledForDataMasking = []; this.populateInitChatOptionalParam = function (requestOptionalParams, optionalParams, telemetryEvent) { requestOptionalParams.initContext.locale = (0, locale_1.getLocaleStringFromId)(_this.localeId); if (optionalParams === null || optionalParams === void 0 ? void 0 : optionalParams.customContext) { // eslint-disable-next-line @typescript-eslint/no-explicit-any var context = optionalParams === null || optionalParams === void 0 ? void 0 : optionalParams.customContext; if (typeof context === "object") { for (var key in context) { if (context[key].value === null || context[key].value === undefined || context[key].value === "") { delete context[key]; } } } requestOptionalParams.initContext.customContextData = optionalParams === null || optionalParams === void 0 ? void 0 : optionalParams.customContext; // eslint-disable-line @typescript-eslint/no-explicit-any } if (optionalParams.browser) { requestOptionalParams.initContext.browser = optionalParams.browser; } if (optionalParams.os) { requestOptionalParams.initContext.os = optionalParams.os; } if (optionalParams.locale) { requestOptionalParams.initContext.locale = optionalParams.locale; } if (optionalParams.device) { requestOptionalParams.initContext.device = optionalParams.device; } if (optionalParams.preChatResponse) { requestOptionalParams.initContext.preChatResponse = optionalParams.preChatResponse; } if (optionalParams.portalContactId) { requestOptionalParams.initContext.portalcontactid = optionalParams.portalContactId; } if (optionalParams.sendDefaultInitContext) { if (platform_1.default.isNode() || platform_1.default.isReactNative()) { var message = "sendDefaultInitContext is only supported on browser"; var telemetryData = { RequestId: _this.requestId, ChatId: _this.chatToken.chatId }; exceptionThrowers_1.default.throwUnsupportedPlatform(_this.scenarioMarker, telemetryEvent, message, telemetryData); } requestOptionalParams.getContext = true; } // Override initContext completely if (optionalParams.initContext) { requestOptionalParams.initContext = optionalParams.initContext; } if (_this.authenticatedUserToken) { requestOptionalParams.authenticatedUserToken = _this.authenticatedUserToken; } if (_this.chatToken.chatId) { // eslint-disable-next-line @typescript-eslint/no-explicit-any requestOptionalParams.initContext.chatId = _this.chatToken.chatId; } return requestOptionalParams; }; this.debug = false; this.debugSDK = false; this.debugAMS = false; this.debugACS = false; this.detailedDebugEnabled = false; this.runtimeId = (0, utilities_1.getRuntimeId)((_b = (_a = chatSDKConfig === null || chatSDKConfig === void 0 ? void 0 : chatSDKConfig.telemetry) === null || _a === void 0 ? void 0 : _a.runtimeId) !== null && _b !== void 0 ? _b : null); this.omnichannelConfig = omnichannelConfig; this.chatSDKConfig = __assign(__assign({}, SDKConfigValidators_1.defaultChatSDKConfig), chatSDKConfig // overrides ); this.isInitialized = false; this.liveChatVersion = LiveChatVersion_1.default.V2; this.localeId = locale_1.defaultLocaleId; this.requestId = (0, ocsdk_1.uuidv4)(); this.chatToken = {}; this.liveChatConfig = {}; this.authSettings = null; this.preChatSurvey = null; this.telemetry = (0, createTelemetry_1.default)(this.debug); this.scenarioMarker = new ScenarioMarker_1.default(this.omnichannelConfig); this.ic3ClientLogger = (0, loggers_1.createIC3ClientLogger)(this.omnichannelConfig); this.ocSdkLogger = (0, loggers_1.createOCSDKLogger)(this.omnichannelConfig); this.acsClientLogger = (0, loggers_1.createACSClientLogger)(this.omnichannelConfig); this.acsAdapterLogger = (0, loggers_1.createACSAdapterLogger)(this.omnichannelConfig); this.callingSdkLogger = (0, loggers_1.createCallingSDKLogger)(this.omnichannelConfig); this.amsClientLogger = (0, loggers_1.createAMSClientLogger)(this.omnichannelConfig); this.scenarioMarker.useTelemetry(this.telemetry); loggerUtils_1.default.useTelemetry(this.telemetry, this.ocSdkLogger, this.acsClientLogger, this.acsAdapterLogger, this.callingSdkLogger, this.amsClientLogger, this.ic3ClientLogger); this.scenarioMarker.setRuntimeId(this.runtimeId); loggerUtils_1.default.setRuntimeId(this.runtimeId, this.ocSdkLogger, this.acsClientLogger, this.acsAdapterLogger, this.callingSdkLogger, this.amsClientLogger, this.ic3ClientLogger); (0, OmnichannelConfigValidator_1.default)(omnichannelConfig); (0, SDKConfigValidators_1.default)(chatSDKConfig); ((_c = this.chatSDKConfig.telemetry) === null || _c === void 0 ? void 0 : _c.disable) && ((_d = this.telemetry) === null || _d === void 0 ? void 0 : _d.disable()); var collectorUri = (0, retrieveCollectorUri_1.default)(this.omnichannelConfig.orgUrl); if ((_e = this.chatSDKConfig.telemetry) === null || _e === void 0 ? void 0 : _e.ariaCollectorUri) { this.telemetry.setCollectorUri((_f = this.chatSDKConfig.telemetry) === null || _f === void 0 ? void 0 : _f.ariaCollectorUri); } else { this.telemetry.setCollectorUri(collectorUri); } if ((_g = this.chatSDKConfig.telemetry) === null || _g === void 0 ? void 0 : _g.ariaTelemetryKey) { this.telemetry.initialize(this.chatSDKConfig.telemetry.ariaTelemetryKey); } if (this.chatSDKConfig.dataMasking) { this.isMaskingDisabled = this.chatSDKConfig.dataMasking.disable; this.maskingCharacter = this.chatSDKConfig.dataMasking.maskingCharacter; } if (omnichannelConfig.cpsBotId) { this.botCSPId = omnichannelConfig.cpsBotId; } loggerUtils_1.default.setRequestId(this.requestId, this.ocSdkLogger, this.acsClientLogger, this.acsAdapterLogger, this.callingSdkLogger, this.amsClientLogger, this.ic3ClientLogger); } /** * Executes an operation with mutual exclusion to prevent race conditions * between startChat and endChat operations */ OmnichannelChatSDK.prototype.executeWithLock = function (operation) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, new Promise(function (resolve, reject) { var wrappedOperation = function () { return __awaiter(_this, void 0, void 0, function () { var result, error_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, 3, 4]); return [4 /*yield*/, operation()]; case 1: result = _a.sent(); resolve(result); return [3 /*break*/, 4]; case 2: error_1 = _a.sent(); reject(error_1); return [3 /*break*/, 4]; case 3: this.chatOperationInProgress = false; this.processNextOperation(); return [7 /*endfinally*/]; case 4: return [2 /*return*/]; } }); }); }; if (_this.chatOperationInProgress) { _this.pendingOperations.push(wrappedOperation); } else { _this.chatOperationInProgress = true; wrappedOperation(); } })]; }); }); }; /** * Processes the next pending operation in the queue */ OmnichannelChatSDK.prototype.processNextOperation = function () { if (this.pendingOperations.length > 0) { this.chatOperationInProgress = true; var nextOperation = this.pendingOperations.shift(); nextOperation(); } }; /** * * @param flag Flag to enable/disable debug log telemetry, will be applied to all components * @description Set the debug flag to enable/disable debug log telemetry */ /* istanbul ignore next */ OmnichannelChatSDK.prototype.setDebug = function (flag) { var _a; this.detailedDebugEnabled = false; this.debug = flag; (_a = this.telemetry) === null || _a === void 0 ? void 0 : _a.setDebug(flag); this.scenarioMarker.setDebug(flag); if (this.AMSClient) { this.AMSClient.setDebug(flag); } loggerUtils_1.default.setDebug(flag, this.ocSdkLogger, this.acsClientLogger, this.acsAdapterLogger, this.callingSdkLogger, this.amsClientLogger, this.ic3ClientLogger); }; /** * @description Allow to target specific components to enable/disable debug log telemetry, reducing the noise in the logs. * @param flagSDK Flag to enable disable SDK debug log telemetry * @param flagAcs Flag to enable/disable debugg log telemetry for Acs components (ACSClient and ACSAdapter) * @param flagAttachment Flag to enable/disable debug log telemetry for Attachment components) */ /* istanbul ignore next */ OmnichannelChatSDK.prototype.setDebugDetailed = function (optionalParams) { var _a; this.detailedDebugEnabled = true; this.debug = (optionalParams === null || optionalParams === void 0 ? void 0 : optionalParams.flagSDK) === true; this.debugACS = (optionalParams === null || optionalParams === void 0 ? void 0 : optionalParams.flagACS) === true; this.debugAMS = (optionalParams === null || optionalParams === void 0 ? void 0 : optionalParams.flagAttachment) === true; (_a = this.telemetry) === null || _a === void 0 ? void 0 : _a.setDebug(this.debug); this.scenarioMarker.setDebug(this.debug); if (this.AMSClient) { this.AMSClient.setDebug(this.debugAMS); } loggerUtils_1.default.setDebugDetailed(this.debug, this.debugACS, this.debugAMS, this.ocSdkLogger, this.acsClientLogger, this.acsAdapterLogger, this.callingSdkLogger, this.amsClientLogger); }; OmnichannelChatSDK.prototype.retryLoadAMSClient = function () { return __awaiter(this, void 0, void 0, function () { var RETRY_DELAY_MS, MAX_RETRY_COUNT, retryCount; return __generator(this, function (_a) { switch (_a.label) { case 0: RETRY_DELAY_MS = 1000; MAX_RETRY_COUNT = 30; retryCount = 0; _a.label = 1; case 1: if (!(retryCount < MAX_RETRY_COUNT)) return [3 /*break*/, 3]; if (this.AMSClient) { return [2 /*return*/, this.AMSClient]; } return [4 /*yield*/, (0, WebUtils_1.sleep)(RETRY_DELAY_MS)]; case 2: _a.sent(); retryCount++; return [3 /*break*/, 1]; case 3: return [2 /*return*/, null]; } }); }); }; OmnichannelChatSDK.prototype.getAMSClient = function () { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: //return null to do not break promise creation if (this.isAMSClientAllowed === false) { return [2 /*return*/, null]; } if (this.AMSClientLoadCurrentState === AMSClientLoadStates_1.AMSClientLoadStates.NOT_LOADED && this.liveChatVersion === LiveChatVersion_1.default.V1) { return [2 /*return*/, null]; } _a = this.AMSClientLoadCurrentState; switch (_a) { case AMSClientLoadStates_1.AMSClientLoadStates.LOADED: return [3 /*break*/, 1]; case AMSClientLoadStates_1.AMSClientLoadStates.LOADING: return [3 /*break*/, 2]; case AMSClientLoadStates_1.AMSClientLoadStates.ERROR: return [3 /*break*/, 4]; case AMSClientLoadStates_1.AMSClientLoadStates.NOT_LOADED: return [3 /*break*/, 4]; } return [3 /*break*/, 6]; case 1: this.debug && console.log("Attachment handler is already loaded"); return [2 /*return*/, this.AMSClient]; case 2: this.debug && console.log("Attachment handler is loading, waiting for it to be ready"); return [4 /*yield*/, this.retryLoadAMSClient()]; case 3: return [2 /*return*/, _b.sent()]; case 4: this.debug && console.log("Attachment handler is not loaded, loading now"); return [4 /*yield*/, this.loadAmsClient()]; case 5: _b.sent(); return [2 /*return*/, this.AMSClient]; case 6: return [2 /*return*/, null]; } }); }); }; OmnichannelChatSDK.prototype.loadInitComponents = function () { return __awaiter(this, void 0, void 0, function () { var supportedLiveChatVersions, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: this.scenarioMarker.startScenario(TelemetryEvent_1.default.InitializeComponents); supportedLiveChatVersions = [LiveChatVersion_1.default.V1, LiveChatVersion_1.default.V2]; if (!supportedLiveChatVersions.includes(this.liveChatVersion)) { exceptionThrowers_1.default.throwUnsupportedLiveChatVersionFailure(new Error(ChatSDKError_1.ChatSDKErrorName.UnsupportedLiveChatVersion), this.scenarioMarker, TelemetryEvent_1.default.InitializeComponents); } if (!(this.liveChatVersion === LiveChatVersion_1.default.V2)) return [3 /*break*/, 1]; this.ACSClient = new ACSClient_1.default(this.acsClientLogger); return [3 /*break*/, 3]; case 1: _a = this; return [4 /*yield*/, this.getIC3Client()]; case 2: _a.IC3Client = _b.sent(); _b.label = 3; case 3: this.scenarioMarker.completeScenario(TelemetryEvent_1.default.InitializeComponents); return [2 /*return*/]; } }); }); }; OmnichannelChatSDK.prototype.evaluateAMSAvailability = function () { var _a, _b, _c, _d; // it will load AMS only if enabled for Customer or Agent support for attachments, based on configuration if (((_b = (_a = this.liveChatConfig) === null || _a === void 0 ? void 0 : _a.LiveWSAndLiveChatEngJoin) === null || _b === void 0 ? void 0 : _b.msdyn_enablefileattachmentsforcustomers) === "true" || ((_d = (_c = this.liveChatConfig) === null || _c === void 0 ? void 0 : _c.LiveWSAndLiveChatEngJoin) === null || _d === void 0 ? void 0 : _d.msdyn_enablefileattachmentsforagents) === "true") { if (this.liveChatVersion === LiveChatVersion_1.default.V2) { //override of this value, since it will be needed to control access to attachment operations this.isAMSClientAllowed = true; return this.isAMSClientAllowed; } } return this.isAMSClientAllowed; }; OmnichannelChatSDK.prototype.loadAmsClient = function () { return __awaiter(this, void 0, void 0, function () { var disableAMSWhitelistedUrls, disableAMSRegionBasedUrl, framedMode, _a, e_1; var _b, _c, _d, _e; return __generator(this, function (_f) { switch (_f.label) { case 0: this.scenarioMarker.startScenario(TelemetryEvent_1.default.InitializeMessagingClient); _f.label = 1; case 1: _f.trys.push([1, 4, , 5]); if (!this.isAMSClientAllowed) return [3 /*break*/, 3]; if (!(this.AMSClientLoadCurrentState === AMSClientLoadStates_1.AMSClientLoadStates.NOT_LOADED)) return [3 /*break*/, 3]; this.AMSClientLoadCurrentState = AMSClientLoadStates_1.AMSClientLoadStates.LOADING; this.debug && console.time("ams_creation"); disableAMSWhitelistedUrls = ((_c = (_b = this.chatSDKConfig) === null || _b === void 0 ? void 0 : _b.internalConfig) === null || _c === void 0 ? void 0 : _c.disableAMSWhitelistedUrls) !== false; disableAMSRegionBasedUrl = ((_e = (_d = this.chatSDKConfig) === null || _d === void 0 ? void 0 : _d.internalConfig) === null || _e === void 0 ? void 0 : _e.disableAMSRegionBasedUrl) === true; framedMode = (0, AMSClientUtils_1.shouldUseFramedMode)(disableAMSWhitelistedUrls); _a = this; return [4 /*yield*/, (0, omnichannel_amsclient_1.default)({ framedMode: framedMode, multiClient: true, debug: (this.detailedDebugEnabled ? this.debugAMS : this.debug), logger: this.amsClientLogger, baseUrl: framedMode && !disableAMSRegionBasedUrl ? (0, AMSClientUtils_1.retrieveRegionBasedUrl)(this.widgetSnippetBaseUrl) : '' })]; case 2: _a.AMSClient = _f.sent(); this.debug && console.timeEnd("ams_creation"); this.AMSClientLoadCurrentState = AMSClientLoadStates_1.AMSClientLoadStates.LOADED; _f.label = 3; case 3: this.scenarioMarker.completeScenario(TelemetryEvent_1.default.InitializeMessagingClient); return [3 /*break*/, 5]; case 4: e_1 = _f.sent(); this.AMSClientLoadCurrentState = AMSClientLoadStates_1.AMSClientLoadStates.ERROR; exceptionThrowers_1.default.throwMessagingClientCreationFailure(e_1, this.scenarioMarker, TelemetryEvent_1.default.InitializeMessagingClient); return [3 /*break*/, 5]; case 5: return [2 /*return*/]; } }); }); }; OmnichannelChatSDK.prototype.parallelInitialization = function () { return __awaiter(this, arguments, void 0, function (optionalParams) { var error_2, telemetryData; if (optionalParams === void 0) { optionalParams = {}; } return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); this.scenarioMarker.startScenario(TelemetryEvent_1.default.InitializeChatSDKParallel); if (this.isInitialized) { this.scenarioMarker.completeScenario(TelemetryEvent_1.default.InitializeChatSDKParallel); return [2 /*return*/, this.liveChatConfig]; } this.useCoreServicesOrgUrlIfNotSet(); return [4 /*yield*/, Promise.all([this.loadInitComponents(), this.loadChatConfig(optionalParams)])]; case 1: _a.sent(); // this will load ams in the background, without holding the load this.loadAmsClient(); this.isInitialized = true; this.scenarioMarker.completeScenario(TelemetryEvent_1.default.InitializeChatSDKParallel); return [3 /*break*/, 3]; case 2: error_2 = _a.sent(); telemetryData = { RequestId: this.requestId, ExceptionDetails: (error_2 instanceof ChatSDKError_1.ChatSDKError) ? JSON.stringify(error_2.exceptionDetails) : "".concat(error_2) }; this.scenarioMarker.failScenario(TelemetryEvent_1.default.InitializeChatSDKParallel, telemetryData); throw error_2; case 3: return [2 /*return*/, this.liveChatConfig]; } }); }); }; // We will keep this logic for backward compatibility for customers with unknown implementation, so they can test before fully adoption OmnichannelChatSDK.prototype.sequentialInitialization = function () { return __awaiter(this, arguments, void 0, function (optionalParams) { var useCoreServices, _a, e_2, getLiveChatConfigOptionalParams, e_3, supportedLiveChatVersions, disableAMSWhitelistedUrls, disableAMSRegionBasedUrl, framedMode, _b, _c, e_4; var _d, _e, _f, _g, _h; if (optionalParams === void 0) { optionalParams = {}; } return __generator(this, function (_j) { switch (_j.label) { case 0: this.scenarioMarker.startScenario(TelemetryEvent_1.default.InitializeChatSDK); if (this.isInitialized) { this.scenarioMarker.completeScenario(TelemetryEvent_1.default.InitializeChatSDK); return [2 /*return*/, this.liveChatConfig]; } this.useCoreServicesOrgUrlIfNotSet(); useCoreServices = (0, CoreServicesUtils_1.isCoreServicesOrgUrl)(this.omnichannelConfig.orgUrl); _j.label = 1; case 1: _j.trys.push([1, 3, , 4]); this.OCSDKProvider = ocsdk_1.SDKProvider; _a = this; return [4 /*yield*/, ocsdk_1.SDKProvider.getSDK(this.omnichannelConfig, (0, createOcSDKConfiguration_1.default)(useCoreServices, (_d = this.chatSDKConfig) === null || _d === void 0 ? void 0 : _d.ocUserAgent), this.ocSdkLogger)]; case 2: _a.OCClient = _j.sent(); return [3 /*break*/, 4]; case 3: e_2 = _j.sent(); exceptionThrowers_1.default.throwOmnichannelClientInitializationFailure(e_2, this.scenarioMarker, TelemetryEvent_1.default.InitializeChatSDK); return [3 /*break*/, 4]; case 4: _j.trys.push([4, 6, , 7]); getLiveChatConfigOptionalParams = optionalParams.getLiveChatConfigOptionalParams; return [4 /*yield*/, this.getChatConfig(getLiveChatConfigOptionalParams || {})]; case 5: _j.sent(); return [3 /*break*/, 7]; case 6: e_3 = _j.sent(); exceptionThrowers_1.default.throwChatConfigRetrievalFailure(e_3, this.scenarioMarker, TelemetryEvent_1.default.InitializeChatSDK); return [3 /*break*/, 7]; case 7: supportedLiveChatVersions = [LiveChatVersion_1.default.V1, LiveChatVersion_1.default.V2]; if (!supportedLiveChatVersions.includes(this.liveChatVersion)) { exceptionThrowers_1.default.throwUnsupportedLiveChatVersionFailure(new Error(ChatSDKError_1.ChatSDKErrorName.UnsupportedLiveChatVersion), this.scenarioMarker, TelemetryEvent_1.default.InitializeChatSDK); } _j.label = 8; case 8: _j.trys.push([8, 14, , 15]); if (!(this.liveChatVersion === LiveChatVersion_1.default.V2)) return [3 /*break*/, 11]; this.ACSClient = new ACSClient_1.default(this.acsClientLogger); if (!(this.isAMSClientAllowed && this.AMSClientLoadCurrentState === AMSClientLoadStates_1.AMSClientLoadStates.NOT_LOADED)) return [3 /*break*/, 10]; this.AMSClientLoadCurrentState = AMSClientLoadStates_1.AMSClientLoadStates.LOADING; this.debug && console.time("ams_seq_creation"); disableAMSWhitelistedUrls = ((_f = (_e = this.chatSDKConfig) === null || _e === void 0 ? void 0 : _e.internalConfig) === null || _f === void 0 ? void 0 : _f.disableAMSWhitelistedUrls) !== false; disableAMSRegionBasedUrl = ((_h = (_g = this.chatSDKConfig) === null || _g === void 0 ? void 0 : _g.internalConfig) === null || _h === void 0 ? void 0 : _h.disableAMSRegionBasedUrl) === true; framedMode = (0, AMSClientUtils_1.shouldUseFramedMode)(disableAMSWhitelistedUrls); _b = this; return [4 /*yield*/, (0, omnichannel_amsclient_1.default)({ framedMode: framedMode, multiClient: true, debug: (this.detailedDebugEnabled ? this.debugAMS : this.debug), logger: this.amsClientLogger, baseUrl: framedMode && !disableAMSRegionBasedUrl ? (0, AMSClientUtils_1.retrieveRegionBasedUrl)(this.widgetSnippetBaseUrl) : '' })]; case 9: _b.AMSClient = _j.sent(); this.debug && console.timeEnd("ams_seq_creation"); this.AMSClientLoadCurrentState = AMSClientLoadStates_1.AMSClientLoadStates.LOADED; _j.label = 10; case 10: return [3 /*break*/, 13]; case 11: if (!(this.liveChatVersion === LiveChatVersion_1.default.V1)) return [3 /*break*/, 13]; _c = this; return [4 /*yield*/, this.getIC3Client()]; case 12: _c.IC3Client = _j.sent(); _j.label = 13; case 13: this.isInitialized = true; this.scenarioMarker.completeScenario(TelemetryEvent_1.default.InitializeChatSDK); return [3 /*break*/, 15]; case 14: e_4 = _j.sent(); this.AMSClientLoadCurrentState = AMSClientLoadStates_1.AMSClientLoadStates.ERROR; exceptionThrowers_1.default.throwMessagingClientCreationFailure(e_4, this.scenarioMarker, TelemetryEvent_1.default.InitializeChatSDK); return [3 /*break*/, 15]; case 15: return [2 /*return*/, this.liveChatConfig]; } }); }); }; /** * * @param optionalParams * @param parallel if true , it will run in parallel (fastest version) with components loaded in the background * @returns livechatConfig */ OmnichannelChatSDK.prototype.initialize = function () { return __awaiter(this, arguments, void 0, function (optionalParams) { var useParallelLoad; if (optionalParams === void 0) { optionalParams = {}; } return __generator(this, function (_a) { switch (_a.label) { case 0: useParallelLoad = optionalParams.useParallelLoad; if (!(useParallelLoad === true)) return [3 /*break*/, 2]; return [4 /*yield*/, this.parallelInitialization(optionalParams)]; case 1: return [2 /*return*/, _a.sent()]; case 2: return [4 /*yield*/, this.sequentialInitialization(optionalParams)]; case 3: return [2 /*return*/, _a.sent()]; } }); }); }; OmnichannelChatSDK.prototype.loadChatConfig = function () { return __awaiter(this, arguments, void 0, function (optionalParams) { var useCoreServices, getLiveChatConfigOptionalParams, e_5; var _a; if (optionalParams === void 0) { optionalParams = {}; } return __generator(this, function (_b) { switch (_b.label) { case 0: this.scenarioMarker.startScenario(TelemetryEvent_1.default.InitializeLoadChatConfig); useCoreServices = (0, CoreServicesUtils_1.isCoreServicesOrgUrl)(this.omnichannelConfig.orgUrl); try { this.OCSDKProvider = ocsdk_1.SDKProvider; this.OCClient = ocsdk_1.SDKProvider.getSDK(this.omnichannelConfig, (0, createOcSDKConfiguration_1.default)(useCoreServices, (_a = this.chatSDKConfig) === null || _a === void 0 ? void 0 : _a.ocUserAgent), this.ocSdkLogger); } catch (e) { exceptionThrowers_1.default.throwOmnichannelClientInitializationFailure(e, this.scenarioMarker, TelemetryEvent_1.default.InitializeLoadChatConfig); } _b.label = 1; case 1: _b.trys.push([1, 3, , 4]); getLiveChatConfigOptionalParams = optionalParams.getLiveChatConfigOptionalParams; return [4 /*yield*/, this.getChatConfig(getLiveChatConfigOptionalParams || {})]; case 2: _b.sent(); return [3 /*break*/, 4]; case 3: e_5 = _b.sent(); exceptionThrowers_1.default.throwChatConfigRetrievalFailure(e_5, this.scenarioMarker, TelemetryEvent_1.default.InitializeLoadChatConfig); return [3 /*break*/, 4]; case 4: this.scenarioMarker.completeScenario(TelemetryEvent_1.default.InitializeLoadChatConfig); return [2 /*return*/]; } }); }); }; OmnichannelChatSDK.prototype.getChatReconnectContextWithAuthToken = function () { return __awaiter(this, void 0, void 0, function () { var context, reconnectableChatsParams, reconnectableChatsResponse, error_3, exceptionDetails, telemetryData; return __generator(this, function (_a) { switch (_a.label) { case 0: this.scenarioMarker.startScenario(TelemetryEvent_1.default.GetChatReconnectContextWithAuthToken, { RequestId: this.requestId, ChatId: this.chatToken.chatId }); context = { reconnectId: null, redirectURL: null }; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); reconnectableChatsParams = { authenticatedUserToken: this.authenticatedUserToken, requestId: this.requestId }; return [4 /*yield*/, this.OCClient.getReconnectableChats(reconnectableChatsParams)]; case 2: reconnectableChatsResponse = _a.sent(); if (reconnectableChatsResponse && reconnectableChatsResponse.reconnectid) { context.reconnectId = reconnectableChatsResponse.reconnectid; } this.scenarioMarker.completeScenario(TelemetryEvent_1.default.GetChatReconnectContextWithAuthToken, { RequestId: this.requestId, ChatId: this.chatToken.chatId }); return [3 /*break*/, 4]; case 3: error_3 = _a.sent(); exceptionDetails = { response: "OCClientGetReconnectableChatsFailed" }; telemetryData = { RequestId: this.requestId, ChatId: this.chatToken.chatId, ExceptionDetails: JSON.stringify(exceptionDetails) }; if ((0, utilities_1.isClientIdNotFoundErrorMessage)(error_3)) { exceptionThrowers_1.default.throwAuthContactIdNotFoundFailure(error_3, this.scenarioMarker, TelemetryEvent_1.default.GetChatReconnectContextWithAuthToken, telemetryData); } this.scenarioMarker.failScenario(TelemetryEvent_1.default.GetChatReconnectContextWithAuthToken, telemetryData); console.error("OmnichannelChatSDK/GetChatReconnectContextWithAuthToken/error ".concat(error_3)); return [3 /*break*/, 4]; case 4: return [2 /*return*/, context]; } }); }); }; OmnichannelChatSDK.prototype.getChatReconnectContextWithReconnectId = function () { return __awaiter(this, arguments, void 0, function (optionalParams) { var context, reconnectAvailabilityResponse, error_4, exceptionDetails; if (optionalParams === void 0) { optionalParams = {}; } return __generator(this, function (_a) { switch (_a.label) { case 0: this.scenarioMarker.startScenario(TelemetryEvent_1.default.GetChatReconnectContextWithReconnectId, { RequestId: this.requestId, ChatId: this.chatToken.chatId }); context = { reconnectId: null, redirectURL: null }; if (!optionalParams.reconnectId) return [3 /*break*/, 4]; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this.OCClient.getReconnectAvailability(optionalParams.reconnectId, { requestId: this.requestId })]; case 2: reconnectAvailabilityResponse = _a.sent(); // isReconnectAvailable , indicates if the chat is still valid, or the token has expired if (reconnectAvailabilityResponse && !reconnectAvailabilityResponse.isReconnectAvailable) { if (reconnectAvailabilityResponse.reconnectRedirectionURL) { context.redirectURL = reconnectAvailabilityResponse.reconnectRedirectionURL; } } else { context.reconnectId = optionalParams.reconnectId; } this.scenarioMarker.completeScenario(TelemetryEvent_1.default.GetChatReconnectContextWithReconnectId, { RequestId: this.requestId, ChatId: this.chatToken.chatId }); return [3 /*break*/, 4]; case 3: error_4 = _a.sent(); exceptionDetails = { response: "OCClientGetReconnectAvailabilityFailed" }; this.scenarioMarker.failScenario(TelemetryEvent_1.default.GetChatReconnectContextWithReconnectId, { RequestId: this.requestId, ChatId: this.chatToken.chatId, ExceptionDetails: JSON.stringify(exceptionDetails) }); console.error("OmnichannelChatSDK/GetChatReconnectContextWithReconnectId/error ".concat(error_4)); return [3 /*break*/, 4]; case 4: //here the context contains recconnectionId if valid, or redirectionURL if not valid return [2 /*return*/, context]; } }); }); }; OmnichannelChatSDK.prototype.getChatReconnectContext = function () { return __awaiter(this, arguments, void 0, function (optionalParams) { var context; if (optionalParams === void 0) { optionalParams = {}; } return __generator(this, function (_a) { switch (_a.label) { case 0: this.scenarioMarker.startScenario(TelemetryEvent_1.default.GetChatReconnectContext, { RequestId: this.requestId, ChatId: this.chatToken.chatId }); if (!this.isInitialized) { exceptionThrowers_1.default.throwUninitializedChatSDK(this.scenarioMarker, TelemetryEvent_1.default.GetChatReconnectContext); } if (!this.requestId) { this.requestId = (0, ocsdk_1.uuidv4)(); } context = { reconnectId: null, redirectURL: null }; return [4 /*yield*/, this.getChatReconnectContextWithReconnectId(optionalParams)]; case 1: // if necessary to make this call, to validate if the token is valid. context = _a.sent(); // if redirectURL is present, it means the token is not longer valid. if (context.redirectURL && context.redirectURL.length > 0) { return [2 /*return*/, context]; } if (!this.authenticatedUserToken) return [3 /*break*/, 3]; return [4 /*yield*/, this.getChatReconnectContextWithAuthToken()]; case 2: context = _a.sent(); _a.label = 3; case 3: this.scenarioMarker.completeScenario(TelemetryEvent_1.default.GetChatReconnectContext, { RequestId: this.requestId, ChatId: this.chatToken.chatId }); return [2 /*return*/, context]; } }); }); }; OmnichannelChatSDK.prototype.startChat = function () { return __awaiter(this, arguments, void 0, function (optionalParams) { var _this = this; if (optionalParams === void 0) { optionalParams = {}; } return __generator(this, func