/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 578: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { ActivityRoutes: () => (/* reexport */ ActivityRoutes), ActivityTopicKeys: () => (/* reexport */ ActivityTopicKeys), SessionExpirationWarningClient: () => (/* reexport */ SessionExpirationWarningClient), activityNamespace: () => (/* reexport */ activityNamespace), sendActivity: () => (/* reexport */ sendActivity) }); ;// ./node_modules/@amazon-connect/activity/lib-esm/activity-namespace.js const activityNamespace = "aws.connect.activity"; //# sourceMappingURL=activity-namespace.js.map ;// ./node_modules/@amazon-connect/activity/lib-esm/routes.js var ActivityRoutes; (function (ActivityRoutes) { ActivityRoutes["sendActivity"] = "sendActivity"; })(ActivityRoutes || (ActivityRoutes = {})); //# sourceMappingURL=routes.js.map // EXTERNAL MODULE: ./node_modules/@amazon-connect/core/lib-esm/index.js + 55 modules var lib_esm = __webpack_require__(238); // EXTERNAL MODULE: ./node_modules/lodash.debounce/index.js var lodash_debounce = __webpack_require__(181); var lodash_debounce_default = /*#__PURE__*/__webpack_require__.n(lodash_debounce); ;// ./node_modules/@amazon-connect/activity/lib-esm/send-activity-callback.js var __awaiter = (undefined && undefined.__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()); }); }; const DEFAULT_DEBOUNCE_TIME = 1000; let loggerCount = 0; let logger; let debouncedSendActivity; /** * Sends activity signals to keep agent active * @param provider */ function sendActivity(provider) { if (!debouncedSendActivity) { logger = new lib_esm/* ConnectLogger */.pg({ provider, source: activityNamespace, }); logger.debug("Creating activity callback.."); const action = () => { void sendActivityRequest({ provider }); }; debouncedSendActivity = lodash_debounce_default()(action, DEFAULT_DEBOUNCE_TIME, { leading: true, trailing: false, }); } debouncedSendActivity(); } function sendActivityRequest(_a) { return __awaiter(this, arguments, void 0, function* ({ provider, }) { try { yield provider .getProxy() .request(activityNamespace, ActivityRoutes.sendActivity); loggerCount = 0; } catch (error) { if (loggerCount < 5) { logger.error("Failed to record agent activity", { error, errorCount: loggerCount, }); loggerCount++; } } }); } //# sourceMappingURL=send-activity-callback.js.map ;// ./node_modules/@amazon-connect/activity/lib-esm/topic-keys.js var ActivityTopicKeys; (function (ActivityTopicKeys) { ActivityTopicKeys["expirationWarning"] = "expiration-warning"; ActivityTopicKeys["expirationWarningCleared"] = "expiration-warning-cleared"; ActivityTopicKeys["sessionExtensionError"] = "session-extension-error"; })(ActivityTopicKeys || (ActivityTopicKeys = {})); //# sourceMappingURL=topic-keys.js.map ;// ./node_modules/@amazon-connect/activity/lib-esm/session-expiration-warning-client.js class SessionExpirationWarningClient extends lib_esm/* ConnectClient */.C$ { constructor(config) { super(activityNamespace, config); } onExpirationWarning(handler) { this.context.proxy.subscribe({ key: ActivityTopicKeys.expirationWarning }, handler); } offExpirationWarning(handler) { this.context.proxy.unsubscribe({ key: ActivityTopicKeys.expirationWarning }, handler); } onExpirationWarningCleared(handler) { this.context.proxy.subscribe({ key: ActivityTopicKeys.expirationWarningCleared }, handler); } offExpirationWarningCleared(handler) { this.context.proxy.unsubscribe({ key: ActivityTopicKeys.expirationWarningCleared }, handler); } onSessionExtensionError(handler) { this.context.proxy.subscribe({ key: ActivityTopicKeys.sessionExtensionError }, handler); } offSessionExtensionError(handler) { this.context.proxy.unsubscribe({ key: ActivityTopicKeys.sessionExtensionError }, handler); } } //# sourceMappingURL=session-expiration-warning-client.js.map ;// ./node_modules/@amazon-connect/activity/lib-esm/index.js //# sourceMappingURL=index.js.map /***/ }), /***/ 791: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { AgentClient: () => (/* reexport */ AgentClient), AgentRoutes: () => (/* reexport */ AgentRoutes), AgentTopicKey: () => (/* reexport */ AgentTopicKey), ContactClient: () => (/* reexport */ ContactClient), ContactLifecycleTopicKey: () => (/* reexport */ ContactLifecycleTopicKey), ContactRoutes: () => (/* reexport */ ContactRoutes), ContactStateType: () => (/* reexport */ ContactStateType), ContactTopicKey: () => (/* reexport */ ContactTopicKey), ParticipantStateType: () => (/* reexport */ ParticipantStateType), contactNamespace: () => (/* reexport */ contactNamespace) }); // EXTERNAL MODULE: ./node_modules/@amazon-connect/core/lib-esm/index.js + 55 modules var lib_esm = __webpack_require__(238); ;// ./node_modules/@amazon-connect/contact/lib-esm/namespace.js const contactNamespace = "aws.connect.contact"; //# sourceMappingURL=namespace.js.map ;// ./node_modules/@amazon-connect/contact/lib-esm/routes.js var AgentRoutes; (function (AgentRoutes) { AgentRoutes["getARN"] = "agent/getARN"; AgentRoutes["getName"] = "agent/getName"; AgentRoutes["getState"] = "agent/getState"; AgentRoutes["getRoutingProfile"] = "agent/getRoutingProfile"; AgentRoutes["getChannelConcurrency"] = "agent/getChannelConcurrency"; AgentRoutes["getExtension"] = "agent/getExtension"; AgentRoutes["getDialableCountries"] = "agent/getDialableCountries"; AgentRoutes["setAvailabilityState"] = "agent/setAvailabilityState"; AgentRoutes["setAvailabilityStateByName"] = "agent/setAvailabilityStateByName"; AgentRoutes["setOffline"] = "agent/setOffline"; AgentRoutes["listAvailabilityStates"] = "agent/listAvailabilityStates"; AgentRoutes["listQuickConnects"] = "agent/listQuickConnects"; })(AgentRoutes || (AgentRoutes = {})); var ContactRoutes; (function (ContactRoutes) { ContactRoutes["getAttributes"] = "contact/getAttributes"; ContactRoutes["getInitialContactId"] = "contact/getInitialContactId"; ContactRoutes["getType"] = "contact/getType"; ContactRoutes["getStateDuration"] = "contact/getStateDuration"; ContactRoutes["getQueue"] = "contact/getQueue"; ContactRoutes["getQueueTimestamp"] = "contact/getQueueTimestamp"; ContactRoutes["getDescription"] = "contact/getDescription"; ContactRoutes["getReferences"] = "contact/getReferences"; ContactRoutes["getChannelType"] = "contact/getChannelType"; ContactRoutes["addParticipant"] = "contact/addParticipant"; ContactRoutes["transfer"] = "contact/transfer"; ContactRoutes["accept"] = "contact/accept"; ContactRoutes["clear"] = "contact/clear"; ContactRoutes["isPreviewMode"] = "contact/isPreviewMode"; ContactRoutes["getPreviewConfiguration"] = "contact/getPreviewConfiguration"; ContactRoutes["engagePreviewContact"] = "contact/engagePreviewContact"; })(ContactRoutes || (ContactRoutes = {})); //# sourceMappingURL=routes.js.map ;// ./node_modules/@amazon-connect/contact/lib-esm/topic-keys.js var ContactLifecycleTopicKey; (function (ContactLifecycleTopicKey) { ContactLifecycleTopicKey["StartingACW"] = "contact/acw"; ContactLifecycleTopicKey["Connected"] = "contact/connected"; ContactLifecycleTopicKey["Destroyed"] = "contact/destroy"; ContactLifecycleTopicKey["Missed"] = "contact/missed"; ContactLifecycleTopicKey["Cleared"] = "contact/cleared"; ContactLifecycleTopicKey["Incoming"] = "contact/incoming"; })(ContactLifecycleTopicKey || (ContactLifecycleTopicKey = {})); var AgentTopicKey; (function (AgentTopicKey) { AgentTopicKey["StateChanged"] = "agent/stateChange"; AgentTopicKey["RoutingProfileChanged"] = "agent/routingProfileChanged"; AgentTopicKey["EnabledChannelListChanged"] = "agent/enabledChannelListChanged"; })(AgentTopicKey || (AgentTopicKey = {})); var ContactTopicKey; (function (ContactTopicKey) { })(ContactTopicKey || (ContactTopicKey = {})); //# sourceMappingURL=topic-keys.js.map ;// ./node_modules/@amazon-connect/contact/lib-esm/agent-client.js var __awaiter = (undefined && undefined.__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()); }); }; class AgentClient extends lib_esm/* ConnectClientWithOptionalConfig */.uU { constructor(config) { super(contactNamespace, config); } getARN() { return __awaiter(this, void 0, void 0, function* () { const { ARN } = yield this.context.proxy.request(AgentRoutes.getARN); return ARN; }); } getName() { return __awaiter(this, void 0, void 0, function* () { const { name } = yield this.context.proxy.request(AgentRoutes.getName); return name; }); } getState() { return this.context.proxy.request(AgentRoutes.getState); } getRoutingProfile() { return this.context.proxy.request(AgentRoutes.getRoutingProfile); } getChannelConcurrency() { return this.context.proxy.request(AgentRoutes.getChannelConcurrency); } getExtension() { return __awaiter(this, void 0, void 0, function* () { const { extension } = yield this.context.proxy.request(AgentRoutes.getExtension); return extension; }); } /** * @deprecated Use `VoiceClient.listDialableCountries` instead. */ getDialableCountries() { return __awaiter(this, void 0, void 0, function* () { const { dialableCountries } = yield this.context.proxy.request(AgentRoutes.getDialableCountries); return dialableCountries; }); } onStateChanged(handler) { this.context.proxy.subscribe({ key: AgentTopicKey.StateChanged }, handler); } offStateChanged(handler) { this.context.proxy.unsubscribe({ key: AgentTopicKey.StateChanged }, handler); } setAvailabilityState(agentStateARN) { return this.context.proxy.request(AgentRoutes.setAvailabilityState, { agentStateARN, }); } setAvailabilityStateByName(agentStateName) { return this.context.proxy.request(AgentRoutes.setAvailabilityStateByName, { agentStateName, }); } setOffline() { return this.context.proxy.request(AgentRoutes.setOffline, {}); } listAvailabilityStates() { return this.context.proxy.request(AgentRoutes.listAvailabilityStates); } listQuickConnects(queueARNs, options) { return this.context.proxy.request(AgentRoutes.listQuickConnects, { queueARNs, options, }); } onEnabledChannelListChanged(handler) { this.context.proxy.subscribe({ key: AgentTopicKey.EnabledChannelListChanged }, handler); } offEnabledChannelListChanged(handler) { this.context.proxy.unsubscribe({ key: AgentTopicKey.EnabledChannelListChanged }, handler); } onRoutingProfileChanged(handler) { this.context.proxy.subscribe({ key: AgentTopicKey.RoutingProfileChanged }, handler); } offRoutingProfileChanged(handler) { this.context.proxy.unsubscribe({ key: AgentTopicKey.RoutingProfileChanged }, handler); } } //# sourceMappingURL=agent-client.js.map ;// ./node_modules/@amazon-connect/contact/lib-esm/contact-client.js var contact_client_awaiter = (undefined && undefined.__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()); }); }; class ContactClient extends lib_esm/* ConnectClientWithOptionalConfig */.uU { constructor(config) { super(contactNamespace, config); } // requests getAttributes(contactId, attributes) { const requestData = { contactId, attributes, }; return this.context.proxy.request(ContactRoutes.getAttributes, requestData); } getAttribute(contactId, attribute) { return contact_client_awaiter(this, void 0, void 0, function* () { const result = yield this.getAttributes(contactId, [attribute]); return result[attribute]; }); } getInitialContactId(contactId) { return contact_client_awaiter(this, void 0, void 0, function* () { const data = yield this.context.proxy.request(ContactRoutes.getInitialContactId, { contactId }); return data.initialContactId; }); } /** * @deprecated Use `getChannelType` instead. */ getType(contactId) { return contact_client_awaiter(this, void 0, void 0, function* () { const data = yield this.context.proxy.request(ContactRoutes.getType, { contactId }); return data.type; }); } getStateDuration(contactId) { return contact_client_awaiter(this, void 0, void 0, function* () { const data = yield this.context.proxy.request(ContactRoutes.getStateDuration, { contactId }); return data.stateDuration; }); } getQueue(contactId) { return this.context.proxy.request(ContactRoutes.getQueue, { contactId, }); } getQueueTimestamp(contactId) { return contact_client_awaiter(this, void 0, void 0, function* () { const data = yield this.context.proxy.request(ContactRoutes.getQueueTimestamp, { contactId }); return data.queueTimestamp; }); } onStartingAcw(handler, contactId) { this.context.proxy.subscribe({ key: ContactLifecycleTopicKey.StartingACW, parameter: contactId }, handler); } /** * @deprecated Use `onCleared` instead. */ onDestroyed(handler, contactId) { this.context.proxy.subscribe({ key: ContactLifecycleTopicKey.Destroyed, parameter: contactId }, handler); } onConnected(handler, contactId) { this.context.proxy.subscribe({ key: ContactLifecycleTopicKey.Connected, parameter: contactId }, handler); } onMissed(handler, contactId) { this.context.proxy.subscribe({ key: ContactLifecycleTopicKey.Missed, parameter: contactId }, handler); } onIncoming(handler, contactId) { this.context.proxy.subscribe({ key: ContactLifecycleTopicKey.Incoming, parameter: contactId }, handler); } offStartingAcw(handler, contactId) { this.context.proxy.unsubscribe({ key: ContactLifecycleTopicKey.StartingACW, parameter: contactId }, handler); } /** * @deprecated Use `offCleared` instead. */ offDestroyed(handler, contactId) { this.context.proxy.unsubscribe({ key: ContactLifecycleTopicKey.Destroyed, parameter: contactId }, handler); } offMissed(handler, contactId) { this.context.proxy.unsubscribe({ key: ContactLifecycleTopicKey.Missed, parameter: contactId }, handler); } offIncoming(handler, contactId) { this.context.proxy.unsubscribe({ key: ContactLifecycleTopicKey.Incoming, parameter: contactId }, handler); } offConnected(handler, contactId) { this.context.proxy.unsubscribe({ key: ContactLifecycleTopicKey.Connected, parameter: contactId }, handler); } getChannelType(contactId) { return contact_client_awaiter(this, void 0, void 0, function* () { return yield this.context.proxy.request(ContactRoutes.getChannelType, { contactId, }); }); } addParticipant(contactId, quickConnect) { return this.context.proxy.request(ContactRoutes.addParticipant, { contactId, quickConnect, }); } transfer(contactId, quickConnect) { return this.context.proxy.request(ContactRoutes.transfer, { contactId, quickConnect, }); } onCleared(handler, contactId) { this.context.proxy.subscribe({ key: ContactLifecycleTopicKey.Cleared, parameter: contactId }, handler); } offCleared(handler, contactId) { this.context.proxy.unsubscribe({ key: ContactLifecycleTopicKey.Cleared, parameter: contactId }, handler); } accept(contactId) { return this.context.proxy.request(ContactRoutes.accept, { contactId, }); } clear(contactId) { return this.context.proxy.request(ContactRoutes.clear, { contactId, }); } isPreviewMode(contactId) { return contact_client_awaiter(this, void 0, void 0, function* () { const response = yield this.context.proxy.request(ContactRoutes.isPreviewMode, { contactId }); return response.isPreviewMode; }); } getPreviewConfiguration(contactId) { return contact_client_awaiter(this, void 0, void 0, function* () { const response = yield this.context.proxy.request(ContactRoutes.getPreviewConfiguration, { contactId, }); return response; }); } engagePreviewContact(contactId) { return contact_client_awaiter(this, void 0, void 0, function* () { return this.context.proxy.request(ContactRoutes.engagePreviewContact, { contactId, }); }); } } //# sourceMappingURL=contact-client.js.map ;// ./node_modules/@amazon-connect/contact/lib-esm/states.js /** * States that a contact can be in. */ var ContactStateType; (function (ContactStateType) { })(ContactStateType || (ContactStateType = {})); /** * States that a participant can be in. */ var ParticipantStateType; (function (ParticipantStateType) { })(ParticipantStateType || (ParticipantStateType = {})); //# sourceMappingURL=states.js.map ;// ./node_modules/@amazon-connect/contact/lib-esm/index.js //# sourceMappingURL=index.js.map /***/ }), /***/ 238: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; // EXPORTS __webpack_require__.d(__webpack_exports__, { Lt: () => (/* reexport */ AmazonConnectProviderBase), C$: () => (/* reexport */ ConnectClient), uU: () => (/* reexport */ ConnectClientWithOptionalConfig), pg: () => (/* reexport */ connect_logger_ConnectLogger), by: () => (/* reexport */ Proxy), Lz: () => (/* reexport */ getGlobalProvider), xQ: () => (/* reexport */ getOriginAndPath) }); // UNUSED EXPORTS: AsyncEventEmitter, ConnectError, ConnectMetricRecorder, Context, DurationMetricRecorder, Emitter, EventEmitter, LogLevel, ModuleContext, RequestManager, SubscriptionHandlerRelay, SubscriptionMap, SubscriptionSet, TimeoutTracker, createLogMessage, createMetricMessage, createModuleProxy, createRequestMessage, deepClone, formatClientTimeoutError, generateStringId, generateUUID, handlerNotFoundResponseErrorKey, isAmazonConnectProvider, isClientTimeoutResponseError, isConnectError, isNoResultResponseError, logToConsole, noResultResponseErrorKey, resetGlobalProvider, sdkVersion ;// ./node_modules/@amazon-connect/core/lib-esm/provider/global-provider.js let _provider; function setGlobalProvider(provider) { if (_provider) throw new Error("Global Provider is already set"); _provider = provider; } function resetGlobalProvider(provider) { _provider = provider; } function getGlobalProvider(notSetMessage) { if (!_provider) { throw new Error(notSetMessage !== null && notSetMessage !== void 0 ? notSetMessage : "Attempted to get Global AmazonConnectProvider that has not been set."); } return _provider; } //# sourceMappingURL=global-provider.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/provider/is-provider.js /** * Type guard to verify that a value represents an AmazonConnectProvider interface. * Checks for the presence of required getters and methods without performing * runtime validation of the on/off error handling functionality. */ /** * Type guard function that verifies if a given value implements the * basic AmazonConnectProvider interface structure. * * @param value - The value to check for provider interface compliance * @returns True if the value has the required provider interface properties * * @example * ```typescript * const someValue = getUnknownValue(); * if (isAmazonConnectProvider(someValue)) { * // someValue is now typed as having provider interface * console.log(someValue.id); * const proxy = someValue.getProxy(); * } * ``` */ function isAmazonConnectProvider(value) { if (typeof value !== "object" || value === null) { return false; } const candidate = value; // Check for id getter - should be a string if (typeof candidate.id !== "string") { return false; } // Check for config getter - should exist (any type acceptable) if (!("config" in candidate)) { return false; } // Check for getProxy method - should be a function if (typeof candidate.getProxy !== "function") { return false; } return true; } //# sourceMappingURL=is-provider.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/error/connect-error.js class ConnectError extends Error { constructor({ reason, namespace, errorKey, details, }) { super(`ConnectError with error key "${errorKey}"`); this.errorType = ConnectError.ErrorType; this.namespace = namespace; this.errorKey = errorKey; this.reason = reason; this.details = details !== null && details !== void 0 ? details : {}; } } ConnectError.ErrorType = "ConnectError"; function isConnectError(error) { return Boolean(error instanceof ConnectError || (error && typeof error === "object" && "errorType" in error && error.errorType === ConnectError.ErrorType)); } //# sourceMappingURL=connect-error.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/error/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/deep-clone.js function deepClone(object) { try { return structuredClone(object); } catch (_a) { try { // Falls back to JSON parse/stringify if structureClone does not exist return JSON.parse(JSON.stringify(object)); } catch (cloneError) { throw new ConnectError({ errorKey: "deepCloneFailed", details: { actualError: cloneError, }, }); } } } //# sourceMappingURL=deep-clone.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/emitter/emitter-base.js class emitter_base_EmitterBase { constructor({ provider, loggerKey }) { this.events = new Map(); this.logger = new connect_logger_ConnectLogger({ provider, source: "emitter", mixin: () => ({ emitterLoggerKey: loggerKey, }), }); } on(parameter, handler) { const set = this.events.get(parameter); if (set) set.add(handler); else this.events.set(parameter, new Set([handler])); } off(parameter, handler) { const set = this.events.get(parameter); if (set) { set.delete(handler); if (set.size < 1) this.events.delete(parameter); } } getHandlers(parameter) { var _a; return Array.from((_a = this.events.get(parameter)) !== null && _a !== void 0 ? _a : []); } } //# sourceMappingURL=emitter-base.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/emitter/async-event-emitter.js var __awaiter = (undefined && undefined.__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()); }); }; class AsyncEventEmitter extends emitter_base_EmitterBase { emit(parameter, event) { return __awaiter(this, void 0, void 0, function* () { const handlers = this.getHandlers(parameter); yield Promise.allSettled(handlers.map((handler) => __awaiter(this, void 0, void 0, function* () { try { yield handler(event); } catch (error) { this.logger.error("An error occurred when invoking event handler", { error, parameter, }); } }))); }); } } //# sourceMappingURL=async-event-emitter.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/emitter/emitter.js class Emitter extends (/* unused pure expression or super */ null && (EmitterBase)) { emit(parameter) { for (const handler of this.getHandlers(parameter)) { try { handler(); } catch (error) { this.logger.error("An error occurred when invoking handler", { error, parameter, }); } } } } //# sourceMappingURL=emitter.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/emitter/event-emitter.js class EventEmitter extends (/* unused pure expression or super */ null && (EmitterBase)) { emit(parameter, event) { const handlers = this.getHandlers(parameter); for (const handler of handlers) { try { handler(event); } catch (error) { this.logger.error("An error occurred when invoking event handler", { error, parameter, }); } } } } //# sourceMappingURL=event-emitter.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/emitter/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/id-generator.js function generateStringId(length) { const a = new Uint8Array(Math.ceil(length / 2)); crypto.getRandomValues(a); return Array.from(a, (d) => d.toString(16).padStart(2, "0")) .join("") .substring(0, length); } function generateUUID() { if ("randomUUID" in crypto) { return crypto.randomUUID(); } else { return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => { const d = parseInt(c); return (d ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (d / 4)))).toString(16); }); } } //# sourceMappingURL=id-generator.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/location-helpers.js function getOriginAndPath() { var _a, _b, _c, _d; return { origin: (_b = (_a = document === null || document === void 0 ? void 0 : document.location) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : "unknown", path: (_d = (_c = document === null || document === void 0 ? void 0 : document.location) === null || _c === void 0 ? void 0 : _c.pathname) !== null && _d !== void 0 ? _d : "unknown", }; } //# sourceMappingURL=location-helpers.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/proxy/module-proxy-factory.js function module_proxy_factory_createModuleProxy(proxy, namespace) { return { request: (command, data) => proxy.request(namespace, command, data), subscribe: (topic, handler) => proxy.subscribe(Object.assign(Object.assign({}, topic), { namespace }), handler), unsubscribe: (topic, handler) => proxy.unsubscribe(Object.assign(Object.assign({}, topic), { namespace }), handler), getProxyInfo: () => ({ connectionStatus: proxy.connectionStatus, proxyType: proxy.proxyType, }), onConnectionStatusChange: (h) => proxy.onConnectionStatusChange(h), offConnectionStatusChange: (h) => proxy.offConnectionStatusChange(h), }; } //# sourceMappingURL=module-proxy-factory.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/messaging/subscription/subscription-handler-id-map.js class SubscriptionHandlerIdMap { constructor() { this.idsByHandler = new Map(); this.handlersById = new Map(); } add(handler) { const existingId = this.idsByHandler.get(handler); if (existingId) { return { handlerId: existingId }; } const handlerId = generateUUID(); this.idsByHandler.set(handler, handlerId); this.handlersById.set(handlerId, handler); return { handlerId }; } getIdByHandler(handler) { var _a; return (_a = this.idsByHandler.get(handler)) !== null && _a !== void 0 ? _a : null; } getHandlerById(id) { var _a; return (_a = this.handlersById.get(id)) !== null && _a !== void 0 ? _a : null; } get() { return [...this.idsByHandler.entries()].map(([handler, handlerId]) => ({ handler, handlerId, })); } delete(handler) { const handlerId = this.idsByHandler.get(handler); if (handlerId) this.handlersById.delete(handlerId); this.idsByHandler.delete(handler); return { isEmpty: this.idsByHandler.size < 1 }; } size() { return this.idsByHandler.size; } } //# sourceMappingURL=subscription-handler-id-map.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/messaging/subscription/subscription-map.js class SubscriptionMap { constructor() { this.simpleSubscriptions = new Map(); this.paramSubscriptions = new Map(); } add({ namespace, key, parameter: param }, value) { var _a, _b, _c, _d, _e; if (param) { if (!this.paramSubscriptions.has(namespace)) { this.paramSubscriptions.set(namespace, new Map([[key, new Map([[param, value]])]])); return; } if (!((_a = this.paramSubscriptions.get(namespace)) === null || _a === void 0 ? void 0 : _a.has(key))) { (_b = this.paramSubscriptions .get(namespace)) === null || _b === void 0 ? void 0 : _b.set(key, new Map([[param, value]])); return; } (_d = (_c = this.paramSubscriptions.get(namespace)) === null || _c === void 0 ? void 0 : _c.get(key)) === null || _d === void 0 ? void 0 : _d.set(param, value); } else { if (!this.simpleSubscriptions.has(namespace)) { this.simpleSubscriptions.set(namespace, new Map([[key, value]])); return; } else (_e = this.simpleSubscriptions.get(namespace)) === null || _e === void 0 ? void 0 : _e.set(key, value); } } delete({ namespace, key, parameter: param }) { var _a, _b, _c, _d; if (param) { if ((_b = (_a = this.paramSubscriptions.get(namespace)) === null || _a === void 0 ? void 0 : _a.get(key)) === null || _b === void 0 ? void 0 : _b.delete(param)) { if (this.paramSubscriptions.get(namespace).get(key).size < 1) { (_c = this.paramSubscriptions.get(namespace)) === null || _c === void 0 ? void 0 : _c.delete(key); if (this.paramSubscriptions.get(namespace).size < 1) { this.paramSubscriptions.delete(namespace); } } } } else { if ((_d = this.simpleSubscriptions.get(namespace)) === null || _d === void 0 ? void 0 : _d.delete(key)) { if (this.simpleSubscriptions.get(namespace).size < 1) { this.simpleSubscriptions.delete(namespace); } } } } get({ namespace, key, parameter: param }) { var _a, _b, _c; if (!param) { return (_a = this.simpleSubscriptions.get(namespace)) === null || _a === void 0 ? void 0 : _a.get(key); } else { return (_c = (_b = this.paramSubscriptions.get(namespace)) === null || _b === void 0 ? void 0 : _b.get(key)) === null || _c === void 0 ? void 0 : _c.get(param); } } getOrAdd(topic, addFactory) { let value = this.get(topic); if (!value) { value = addFactory(); this.add(topic, value); } return value; } addOrUpdate(topic, addFactory, updateAction) { let value = this.get(topic); if (value) { value = updateAction(value); } else { value = addFactory(); } this.add(topic, value); return value; } getAllSubscriptions() { const noParam = Array.from(this.simpleSubscriptions.keys()).flatMap((namespace) => Array.from(this.simpleSubscriptions.get(namespace).keys()).flatMap((key) => ({ namespace, key, }))); const withParam = Array.from(this.paramSubscriptions.keys()).flatMap((namespace) => Array.from(this.paramSubscriptions.get(namespace).keys()).flatMap((key) => Array.from(this.paramSubscriptions.get(namespace).get(key).keys()).flatMap((parameter) => ({ namespace, key, parameter, })))); return [...noParam, ...withParam]; } } //# sourceMappingURL=subscription-map.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/messaging/subscription/subscription-manager.js class SubscriptionManager { constructor() { this.subscriptions = new SubscriptionMap(); } add(topic, handler) { return this.subscriptions .getOrAdd(topic, () => new SubscriptionHandlerIdMap()) .add(handler); } get(topic) { var _a, _b; return (_b = (_a = this.subscriptions.get(topic)) === null || _a === void 0 ? void 0 : _a.get()) !== null && _b !== void 0 ? _b : []; } getById(topic, handlerId) { var _a, _b; return (_b = (_a = this.subscriptions.get(topic)) === null || _a === void 0 ? void 0 : _a.getHandlerById(handlerId)) !== null && _b !== void 0 ? _b : null; } delete(topic, handler) { var _a, _b; if ((_b = (_a = this.subscriptions.get(topic)) === null || _a === void 0 ? void 0 : _a.delete(handler).isEmpty) !== null && _b !== void 0 ? _b : false) { this.subscriptions.delete(topic); } } size(topic) { var _a, _b; return (_b = (_a = this.subscriptions.get(topic)) === null || _a === void 0 ? void 0 : _a.size()) !== null && _b !== void 0 ? _b : 0; } isEmpty(topic) { return this.size(topic) === 0; } getAllSubscriptions() { return this.subscriptions.getAllSubscriptions(); } getAllSubscriptionHandlerIds() { return this.subscriptions .getAllSubscriptions() .reduce((acc, topic) => acc.concat(this.get(topic).map(({ handlerId }) => ({ topic, handlerId, }))), []); } } //# sourceMappingURL=subscription-manager.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/messaging/subscription/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/metric/duration-metric-recorder.js /** * @classdesc DurationMetricRecorder class provides APIs to emit duration metrics based on users' need */ class DurationMetricRecorder { /** * Constructor for DurationMetricRecorder * @param {(metric: MetricData) => void} sendMetric- The method that sends metric * @param {string} metricName - The name of the duration metric * @param {Record} dimensions - The dimensions of the duration metric with keys and values (optional) * @param {Record} optionalDimensions - The optional dimensions of the duration metric with keys and values (optional) */ constructor({ sendMetric, metricName, metricOptions, }) { this.unit = "Milliseconds"; this.sendMetric = sendMetric; this.startTime = performance.now(); this.metricName = metricName; this.dimensions = (metricOptions === null || metricOptions === void 0 ? void 0 : metricOptions.dimensions) ? metricOptions.dimensions : {}; this.optionalDimensions = (metricOptions === null || metricOptions === void 0 ? void 0 : metricOptions.optionalDimensions) ? metricOptions.optionalDimensions : {}; } /** * Stop recording of the duration metric and emit it * @returns {durationCount: number} - The duration being recorded */ stopDurationCounter() { const durationResult = Math.round(performance.now() - this.startTime); this.sendMetric({ metricName: this.metricName, unit: this.unit, value: durationResult, dimensions: this.dimensions, optionalDimensions: this.optionalDimensions, }); return { duration: durationResult }; } } //# sourceMappingURL=duration-metric-recorder.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/metric/metric-helpers.js const MAX_METRIC_DIMENSIONS = 30; /** * Check if the the sum of the length of dimensions and optional dimentions is exceeding maximum dimension length acceptable by back-end * @param {Record} dimensions - The dimensions of the duration metric with keys and values * @param {Record} optionalDimensions -The optional dimensions of the duration metric with keys and values */ function checkDimensionLength(dimensions, optionalDimensions) { if (Object.keys(dimensions).length + Object.keys(optionalDimensions !== null && optionalDimensions !== void 0 ? optionalDimensions : {}).length > MAX_METRIC_DIMENSIONS) { throw new Error("Cannot add more than 30 dimensions to a metric"); } } /** * Transform the metric message into the format acceptable by back-end * @param {MetricData} metricData - The metric data * @param {string} timestamp - The timestamp of the metric * @param {string} namespace - The namespace of the metric * @param {UpstreamMessageOrigin} messageOrigin - The origin of the metric message * @return {MetricMessage} - Return a MetricMessage object */ function createMetricMessage({ metricData, time, namespace }, messageOrigin) { var _a, _b; return { type: "metric", namespace: namespace, metricName: metricData.metricName, unit: metricData.unit, value: metricData.value, time: time, dimensions: (_a = metricData.dimensions) !== null && _a !== void 0 ? _a : {}, optionalDimensions: (_b = metricData.optionalDimensions) !== null && _b !== void 0 ? _b : {}, messageOrigin, }; } //# sourceMappingURL=metric-helpers.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/metric/connect-metric-recorder.js /** * @classdesc ConnectMetricRecorder class provides APIs to emit metrics based on users' need */ class ConnectMetricRecorder { /** * Constructor for ConnectMetricRecorder * @param {ConnectRecorderMetricParams} params - The namespace and provider(optional) */ constructor(params) { this._proxy = null; this.namespace = params.namespace; if (params.provider && typeof params.provider === "function") this.providerFactory = params.provider; else this.provider = params.provider; } /** * Emit a metric that counts success * @param {string} metricName - The name of the metric * @param {Record} dimensions - The dimensions of a metric with keys and values (optional) * @param {Record} optionalDimensions - The optional dimensions of a metric with keys and values (optional) */ recordSuccess(metricName, metricOptions) { var _a; const processedDimensions = Object.assign({}, ((_a = metricOptions === null || metricOptions === void 0 ? void 0 : metricOptions.dimensions) !== null && _a !== void 0 ? _a : {})); const processedMetricOptions = Object.assign(Object.assign({}, metricOptions), { dimensions: processedDimensions }); this.recordCount(metricName, 0, processedMetricOptions); } /** * Emit a metric that counts error. Add default dimension { name: "Metric", value: "Error" } to the metric if not added * @param {string} metricName - The name of the metric * @param {Record} dimensions - The dimensions of a metric with keys and values (optional) * @param {Record} optionalDimensions - The optional dimensions of a metric with keys and values (optional) */ recordError(metricName, metricOptions) { var _a; const processedDimensions = Object.assign({}, ((_a = metricOptions === null || metricOptions === void 0 ? void 0 : metricOptions.dimensions) !== null && _a !== void 0 ? _a : {})); const processedMetricOptions = Object.assign(Object.assign({}, metricOptions), { dimensions: processedDimensions }); this.recordCount(metricName, 1, processedMetricOptions); } /** * Emit a counting metric * @param {string} metricName - The name of the metric * @param {number} count - The count of the metric * @param {Record} dimensions - The dimensions of a metric with keys and values (optional) * @param {Record} optionalDimensions - The optional dimensions of a metric with keys and values (optional) */ recordCount(metricName, count, metricOptions) { this.sendMetric({ metricName, unit: "Count", value: count, dimensions: metricOptions === null || metricOptions === void 0 ? void 0 : metricOptions.dimensions, optionalDimensions: metricOptions === null || metricOptions === void 0 ? void 0 : metricOptions.optionalDimensions, }); } /** * Start a duration metric * @param {string} metricName - The name of the metric * @param {Record} dimensions - The dimensions of a metric with keys and values (optional) * @param {Record} optionalDimensions - The optional dimensions of a metric with keys and values (optional) * @returns {DurationMetricRecorder} - The DurationMetricRecorder object being created */ startDurationCounter(metricName, metricOptions) { return new DurationMetricRecorder({ sendMetric: this.sendMetric.bind(this), metricName, metricOptions, }); } /** * Emit metric * @param {string} metricName - The name of the metric * @param {unit} unit - The unit of the metric * @param {number} value - The value of the metric * @param {Record} dimensions - The dimensions of a metric with keys and values (optional) * @param {Record} optionalDimensions - The optional dimensions of a metric with keys and values (optional) */ sendMetric({ metricName, unit, value, dimensions, optionalDimensions, }) { if (dimensions) { checkDimensionLength(dimensions, optionalDimensions); } const metricData = { metricName, unit, value, dimensions, optionalDimensions, }; const time = new Date(); this.getProxy().sendMetric({ metricData, time, namespace: this.namespace, }); } /** * Get the provider of the ConnectMetricRecorder instance */ getProvider() { if (!this.provider) { this.provider = this.providerFactory ? this.providerFactory() : getGlobalProvider(); } return this.provider; } /** * Get the proxy of the ConnectMetricRecorder instance */ getProxy() { if (!this._proxy) { this._proxy = this.getProvider().getProxy(); } return this._proxy; } } //# sourceMappingURL=connect-metric-recorder.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/metric/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/request/client-timeout-error.js const clientTimeoutResponseErrorKey = "clientTimeout"; function formatClientTimeoutError(request, timeoutMs) { const { namespace, command, data: requestData } = request; return { namespace, reason: "Client Timeout", details: { command, requestData, timeoutMs, }, errorKey: clientTimeoutResponseErrorKey, }; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function isClientTimeoutResponseError(err) { return ( // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access typeof err === "object" && err.errorKey === clientTimeoutResponseErrorKey); } //# sourceMappingURL=client-timeout-error.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/request/request-handler-factory.js const DEFAULT_TIMEOUT_MS = 30 * 1000; function createRequestHandler(request, onStart, onTimeout, timeoutMs) { const adjustedTimeoutMs = Math.max(1, timeoutMs !== null && timeoutMs !== void 0 ? timeoutMs : DEFAULT_TIMEOUT_MS); return new Promise((resolve, reject) => { let isTimedOut = false; const timeout = setTimeout(() => { onTimeout({ timeoutMs: adjustedTimeoutMs, request }); // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors reject(formatClientTimeoutError(request, adjustedTimeoutMs)); isTimedOut = true; }, adjustedTimeoutMs); const handler = (msg) => { clearTimeout(timeout); if (!isTimedOut) { if (msg.isError) { reject(new ConnectError(msg)); } else { resolve(msg.data); } } }; onStart(handler); }); } //# sourceMappingURL=request-handler-factory.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/request/request-manager.js class RequestManager { constructor(provider) { this.requestMap = new Map(); this.logger = new connect_logger_ConnectLogger({ provider, source: "core.requestManager", }); } processRequest(request) { const { requestId } = request; return createRequestHandler(request, (handler) => this.requestMap.set(requestId, handler), ({ request, timeoutMs }) => this.handleTimeout(request, timeoutMs)); } processResponse(response) { const { requestId } = response; const handler = this.requestMap.get(requestId); if (!handler) { // The proxy is implemented such that this should never happen this.logger.error("Returned a response message with no handler", { message: response, }); return; } handler(response); this.requestMap.delete(requestId); } handleTimeout(request, timeoutMs) { const { requestId, namespace, command } = request; this.requestMap.delete(requestId); this.logger.error("Client request timeout", { requestId, namespace, command, timeoutMs, }); } } //# sourceMappingURL=request-manager.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/request/request-message-factory.js function createRequestMessage(namespace, command, data, messageOrigin) { const requestId = generateUUID(); return { type: "request", namespace, command, requestId, data, messageOrigin, }; } //# sourceMappingURL=request-message-factory.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/request/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/messaging/downstream-message-sanitizer.js var __rest = (undefined && undefined.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; function sanitizeDownstreamMessage(message) { try { switch (message.type) { case "acknowledge": case "error": case "childConnectionClose": return message; case "childDownstreamMessage": return Object.assign(Object.assign({}, message), { message: sanitizeDownstreamMessage(message.message) }); case "publish": { const { data } = message, other = __rest(message, ["data"]); return Object.assign({}, other); } case "response": { if (message.isError) return Object.assign(Object.assign({}, message), { details: { command: message.details.command } }); else { const { data } = message, other = __rest(message, ["data"]); return Object.assign({}, other); } } default: return message; } } catch (error) { return { messageDetails: "error when sanitizing downstream message", message, error, }; } } //# sourceMappingURL=downstream-message-sanitizer.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/messaging/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/proxy/channel-manager.js /** * Manages communication channels between the proxy and child entities. * * The ChannelManager supports two types of communication channels: * 1. Iframe channels - Use browser MessagePort API for communication across different execution contexts * 2. Component channels - Use direct function calls when both entities exist in the same execution context * * Key responsibilities: * - Adding and removing child channels * - Routing downstream messages from proxy to child entities * - Relaying upstream messages from child entities back to the proxy * - Managing MessagePort lifecycle (opening, closing, cleanup) * - Validating provider IDs to ensure secure message routing * * @example Iframe Channel * ```typescript * const { port1, port2 } = new MessageChannel(); * channelManager.addChannel({ * connectionId: "child-uuid", * providerId: "provider-uuid", * type: "iframe", * port: port1 * }); * // port2 gets transferred to child entity * ``` * * @example Component Channel * ```typescript * channelManager.addChannel({ * connectionId: "child-uuid", * providerId: "provider-uuid", * type: "component", * sendDownstreamMessage: (msg) => childEntity.receive(msg), * setUpstreamMessageHandler: (handler) => childEntity.onUpstream = handler * }); * ``` */ class ChannelManager { constructor(provider, relayChildUpstreamMessage) { this.provider = provider; this.relayChildUpstreamMessage = relayChildUpstreamMessage; this.channels = new Map(); this.logger = new connect_logger_ConnectLogger({ provider, source: "childConnectionManager", }); } /** * Adds a new communication channel for a child entity. * * Supports both iframe and component channel types. For iframe channels, * sets up message event listeners and starts the port. For component channels, * configures the upstream message handler. Both types send a "childConnectionReady" * message upstream to notify the proxy that the channel is established. * * @param params - Channel configuration parameters * @param params.connectionId - UUID identifier for this channel connection * @param params.providerId - UUID of the provider that owns this channel * @param params.type - Channel type: "iframe" or "component" * * @example Iframe Channel * ```typescript * const { port1, port2 } = new MessageChannel(); * channelManager.addChannel({ * connectionId: "550e8400-e29b-41d4-a716-446655440000", * providerId: "6ba7b810-9dad-11d1-80b4-00c04fd430c8", * type: "iframe", * port: port1 * }); * ``` * * @example Component Channel * ```typescript * channelManager.addChannel({ * connectionId: "550e8400-e29b-41d4-a716-446655440001", * providerId: "6ba7b810-9dad-11d1-80b4-00c04fd430c8", * type: "component", * sendDownstreamMessage: (msg) => childEntity.receive(msg), * setUpstreamMessageHandler: (handler) => childEntity.onUpstream = handler * }); * ``` */ addChannel(params) { const { connectionId } = params; if (this.channels.has(connectionId)) { this.logger.error("Attempted to add child connection that already exists. No action", { connectionId, }); return; } if (params.type === "iframe") { this.setupIframe(params); } else { this.setupComponent(params); } this.logger.debug("Child channel added", { connectionId, type: params.type, }); } /** * Updates an existing MessagePort channel with a new MessagePort. * * This method is only applicable to MessagePort channels. Direct channels cannot * be updated and will result in an error. The old MessagePort is properly cleaned up * (event listeners removed, port closed) before the new port is configured. * * @param params - Update parameters * @param params.connectionId - UUID identifier for the channel to update * @param params.port - New MessagePort instance to replace the existing one * @param params.providerId - UUID of the provider that owns this channel * * @throws Logs error if connectionId doesn't exist or channel is Direct type * * @example * ```typescript * const { port1, port2 } = new MessageChannel(); * channelManager.updateChannelPort({ * connectionId: "550e8400-e29b-41d4-a716-446655440000", * port: port1, * providerId: "6ba7b810-9dad-11d1-80b4-00c04fd430c8" * }); * ``` */ updateChannelPort(params) { const { connectionId } = params; const existingChannel = this.channels.get(connectionId); if (!existingChannel) { this.logger.error("Attempted to update child connection that does not exist No action", { connectionId, }); return; } if (existingChannel.type === "component") { this.logger.error("Attempted to update a component channel connection as MessagePort. This is not supported.", { connectionId, }); return; } const originalChannel = existingChannel; originalChannel.port.onmessage = null; originalChannel.port.close(); const setupParams = Object.assign(Object.assign({}, params), { type: "iframe" }); this.setupIframe(setupParams); this.logger.info("Updated child port", { connectionId }); } setupIframe(params) { const { connectionId, port, providerId } = params; const handler = this.createMessageHandler(connectionId, providerId); port.addEventListener("message", handler); port.start(); this.channels.set(connectionId, { type: "iframe", port, handler, providerId, }); this.relayChildUpstreamMessage({ type: "childUpstream", connectionId, sourceProviderId: providerId, parentProviderId: this.provider.id, message: { type: "childConnectionReady", }, }); } setupComponent(params) { const { connectionId, providerId, sendDownstreamMessage, setUpstreamMessageHandler, } = params; const upstreamHandler = (message) => { this.relayChildUpstreamMessage({ type: "childUpstream", sourceProviderId: providerId, parentProviderId: this.provider.id, connectionId, message, }); }; setUpstreamMessageHandler(upstreamHandler); this.channels.set(connectionId, { type: "component", providerId, sendDownstreamMessage, setUpstreamMessageHandler, }); this.relayChildUpstreamMessage({ type: "childUpstream", connectionId, sourceProviderId: providerId, parentProviderId: this.provider.id, message: { type: "childConnectionReady", }, }); } /** * Routes a downstream message from the proxy to the appropriate child channel. * * Validates that the target channel exists and that the provider ID matches * (for security). For MessagePort channels, uses postMessage(). For Direct * channels, calls the sendDownstreamMessage function. * * @param params - Downstream message parameters * @param params.connectionId - UUID of the target channel * @param params.message - The message to send to the child entity * @param params.targetProviderId - Expected provider ID for validation * * @example * ```typescript * channelManager.handleDownstreamMessage({ * connectionId: "550e8400-e29b-41d4-a716-446655440000", * message: { type: "request", data: "some data" }, * targetProviderId: "6ba7b810-9dad-11d1-80b4-00c04fd430c8" * }); * ``` */ handleDownstreamMessage({ connectionId, message, targetProviderId, }) { const channelData = this.channels.get(connectionId); if (!channelData) { this.logger.warn("Attempted to route downstream message to child channel that does not exist", { connectionId, message: sanitizeDownstreamMessage(message) }); return; } const { providerId } = channelData; // Older versions of the SDK do not provide a provider id. This // check is ignored for versions without a providerId. if (providerId && providerId !== targetProviderId) { this.logger.error("Downstream target message did not match target provider id. Not sending message.", { connectionId, targetProviderId, actualProviderId: providerId, message: sanitizeDownstreamMessage(message), }); return; } if (channelData.type === "iframe") { channelData.port.postMessage(message); } else { channelData.sendDownstreamMessage(message); } } /** * Handles closing a child channel and performs appropriate cleanup. * * For MessagePort channels, removes event listeners and closes the port. * For Direct channels, simply removes the channel from the internal map * since no port cleanup is needed. The channel is always removed from * the channels map regardless of type. * * @param params - Close message parameters * @param params.connectionId - UUID of the channel to close * * @example * ```typescript * channelManager.handleCloseMessage({ * connectionId: "550e8400-e29b-41d4-a716-446655440000" * }); * ``` */ handleCloseMessage({ connectionId }) { const channelData = this.channels.get(connectionId); if (!channelData) { this.logger.warn("Attempted to close child channel that was not found", { connectionId, }); return; } if (channelData.type === "iframe") { const { port, handler } = channelData; port.removeEventListener("message", handler); port.close(); } // For component channels, no cleanup of ports/handlers is needed this.channels.delete(connectionId); this.logger.debug("Removed child channel", { connectionId, type: channelData.type, }); } createMessageHandler(connectionId, providerId) { return (message) => this.relayChildUpstreamMessage({ type: "childUpstream", sourceProviderId: providerId, parentProviderId: this.provider.id, connectionId, message: message.data, }); } } //# sourceMappingURL=channel-manager.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/proxy/error/error-service.js class ErrorService { constructor(provider) { this.errorHandlers = new Set(); this.logger = new connect_logger_ConnectLogger({ provider, source: "core.proxy.error", }); } invoke(error) { const { message, key, details, isFatal, connectionStatus } = error; this.logger.error(message, { key, details, isFatal, connectionStatus, }, { duplicateMessageToConsole: true, remoteIgnore: true }); [...this.errorHandlers].forEach((handler) => { try { handler(error); } catch (handlerError) { this.logger.error("An error occurred within a AmazonConnectErrorHandler", { handlerError, originalError: error, }); } }); } onError(handler) { this.errorHandlers.add(handler); } offError(handler) { this.errorHandlers.delete(handler); } } //# sourceMappingURL=error-service.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/proxy/error/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/proxy/health-check/health-check-manager.js class HealthCheckManager { constructor({ provider, sendHealthCheck, getUpstreamMessageOrigin, }) { this.connectionId = null; this.healthCheckInterval = null; this.healthCheckTimeout = null; this.sendHealthCheck = sendHealthCheck; this.getUpstreamMessageOrigin = getUpstreamMessageOrigin; this.sendHealthCheckInterval = null; this.lastHealthCheckResponse = null; this._status = "unknown"; this.logger = new connect_logger_ConnectLogger({ source: "core.proxy.health-check", provider: provider, mixin: () => ({ connectionId: this.connectionId, }), }); this.events = new AsyncEventEmitter({ provider, loggerKey: "core.proxy.health-check", }); } get status() { return this._status; } get isRunning() { return this.sendHealthCheckInterval !== null; } get lastCheckCounter() { var _a, _b; return (_b = (_a = this.lastHealthCheckResponse) === null || _a === void 0 ? void 0 : _a.counter) !== null && _b !== void 0 ? _b : null; } get lastCheckTime() { var _a, _b; return (_b = (_a = this.lastHealthCheckResponse) === null || _a === void 0 ? void 0 : _a.time) !== null && _b !== void 0 ? _b : null; } start({ healthCheckInterval: interval, connectionId, }) { this.connectionId = connectionId; this.healthCheckInterval = interval; this.clearInterval(); if (interval <= 0) { this.logger.debug("Health check disabled"); return; } if (interval < 1000) { this.logger.error("Health check interval is less than 1 second. Not running", { interval }); return; } this.sendHealthCheckMessage(); this.sendHealthCheckInterval = setInterval(() => this.sendHealthCheckMessage(), interval); this.startTimeout(); } stop() { this.clearInterval(); this.clearTimeout(); } handleResponse(message) { this.setHealthy({ time: message.time, counter: message.counter, }); } sendHealthCheckMessage() { this.sendHealthCheck({ type: "healthCheck", messageOrigin: this.getUpstreamMessageOrigin(), }); } startTimeout() { if (!this.healthCheckInterval) { this.logger.error("Health check interval not set. Cannot start timeout"); return; } // Cancels a preexisting timeout to be replaced with new timeout this.clearTimeout(); this.healthCheckTimeout = setTimeout(() => { this.setUnhealthy(); }, this.healthCheckInterval * 3); } clearInterval() { if (this.sendHealthCheckInterval) { clearInterval(this.sendHealthCheckInterval); this.sendHealthCheckInterval = null; } } clearTimeout() { if (this.healthCheckTimeout) { clearTimeout(this.healthCheckTimeout); this.healthCheckTimeout = null; } } setUnhealthy() { if (this._status !== "unhealthy") { const previousStatus = this._status; this.logger.info("Connection unhealthy", { previousStatus, }); this._status = "unhealthy"; this.emitStatusChanged("unhealthy", previousStatus); } } setHealthy(result) { this.lastHealthCheckResponse = Object.assign({}, result); if (this._status !== "healthy") { const previousStatus = this._status; this.logger.debug("Connection healthy", { previousStatus, }); this._status = "healthy"; this.emitStatusChanged("healthy", previousStatus); } this.startTimeout(); } emitStatusChanged(status, previousStatus) { var _a, _b, _c, _d; void this.events.emit(HealthCheckManager.statusChangedKey, { status, previousStatus, lastCheckTime: (_b = (_a = this.lastHealthCheckResponse) === null || _a === void 0 ? void 0 : _a.time) !== null && _b !== void 0 ? _b : null, lastCheckCounter: (_d = (_c = this.lastHealthCheckResponse) === null || _c === void 0 ? void 0 : _c.counter) !== null && _d !== void 0 ? _d : null, }); } onStatusChanged(handler) { this.events.on(HealthCheckManager.statusChangedKey, handler); } offStatusChanged(handler) { this.events.off(HealthCheckManager.statusChangedKey, handler); } } HealthCheckManager.statusChangedKey = "statusChanged"; //# sourceMappingURL=health-check-manager.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/proxy/health-check/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/proxy/proxy-connection/proxy-connection-status-manager.js class ProxyConnectionStatusManager { constructor(provider) { this.status = "notConnected"; this.changeHandlers = new Set(); this.logger = new connect_logger_ConnectLogger({ source: "core.proxy.connection-status-manager", provider, mixin: () => ({ status: this.status }), }); } getStatus() { return this.status; } update(evt) { this.status = evt.status; this.logger.trace("Proxy Connection Status Changed", { status: evt.status, }); [...this.changeHandlers].forEach((handler) => { try { handler(evt); } catch (error) { this.logger.error("An error occurred within a ProxyConnectionChangedHandler", { error }); } }); } onChange(handler) { this.changeHandlers.add(handler); } offChange(handler) { this.changeHandlers.delete(handler); } } //# sourceMappingURL=proxy-connection-status-manager.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/proxy/proxy-connection/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/proxy/proxy.js var proxy_awaiter = (undefined && undefined.__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 proxy_rest = (undefined && undefined.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; class Proxy { constructor(provider) { this.provider = provider; this.logger = new connect_logger_ConnectLogger({ source: "core.proxy", provider, mixin: () => ({ proxyType: this.proxyType, connectionId: this.connectionId, }), }); this.requestManager = new RequestManager(provider); this.status = new ProxyConnectionStatusManager(provider); this.errorService = new ErrorService(provider); this.upstreamMessageQueue = []; this.connectionEstablished = false; this.isInitialized = false; this.subscriptions = new SubscriptionManager(); this.connectionId = null; this.channelManager = new ChannelManager(provider, this.sendOrQueueMessageToSubject.bind(this)); this.healthCheck = new HealthCheckManager({ provider, sendHealthCheck: this.sendOrQueueMessageToSubject.bind(this), getUpstreamMessageOrigin: this.getUpstreamMessageOrigin.bind(this), }); } init() { if (this.isInitialized) throw new Error("Proxy already initialized"); this.isInitialized = true; this.initProxy(); } request(namespace, command, data, origin) { const msg = createRequestMessage(namespace, command, data, origin !== null && origin !== void 0 ? origin : this.getUpstreamMessageOrigin()); const resp = this.requestManager.processRequest(msg); this.sendOrQueueMessageToSubject(msg); return resp; } subscribe(topic, handler, origin) { const { handlerId } = this.subscriptions.add(topic, handler); const msg = { type: "subscribe", topic, messageOrigin: origin !== null && origin !== void 0 ? origin : this.getUpstreamMessageOrigin(), handlerId, }; this.sendOrQueueMessageToSubject(msg); } unsubscribe(topic, handler, origin) { this.subscriptions.delete(topic, handler); if (this.subscriptions.isEmpty(topic)) { const msg = { type: "unsubscribe", topic, messageOrigin: origin !== null && origin !== void 0 ? origin : this.getUpstreamMessageOrigin(), }; this.sendOrQueueMessageToSubject(msg); } } log(logData) { const logMsg = createLogMessage(logData, this.addContextToLogger(), this.getUpstreamMessageOrigin()); this.sendOrQueueMessageToSubject(logMsg); } sendLogMessage(message) { if (message.type !== "log") { this.logger.error("Attempted to send invalid log message", { message, }); return; } message.context = Object.assign(Object.assign({}, message.context), this.addContextToLogger()); this.sendOrQueueMessageToSubject(message); } sendMetric({ metricData, time, namespace }) { const metricMessage = createMetricMessage({ metricData, time, namespace, }, this.getUpstreamMessageOrigin()); this.sendOrQueueMessageToSubject(metricMessage); } sendMetricMessage(metricMessage) { if (metricMessage.type !== "metric") { this.logger.error("Attempted to send invalid metric message", { metricMessage, }); return; } this.sendOrQueueMessageToSubject(metricMessage); } sendOrQueueMessageToSubject(message) { if (this.connectionEstablished) { this.sendMessageToSubject(message); } else { this.upstreamMessageQueue.push(message); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any consumerMessageHandler(evt) { if (!this.isInitialized) { this.logger.error("Attempted to process message from subject prior to proxy being initializing. Message not processed", { originalMessageEventData: evt.data }); return; } // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const { data } = evt; if (!("type" in data)) { // TODO Clean this up... probably safe to ignore without logging this.logger.warn("Unknown inbound message", { originalMessageEventData: data, }); return; } // Naming of type confusing because outbound to worker is inbound to client const msg = data; this.handleMessageFromSubject(msg); } handleMessageFromSubject(msg) { this.handleDefaultMessageFromSubject(msg); } handleDefaultMessageFromSubject(msg) { switch (msg.type) { case "acknowledge": this.handleConnectionAcknowledge(msg); break; case "response": this.handleResponse(msg); break; case "publish": this.handlePublish(msg); break; case "error": this.handleError(msg); break; case "childDownstreamMessage": this.channelManager.handleDownstreamMessage(msg); break; case "childConnectionClose": this.channelManager.handleCloseMessage(msg); break; case "healthCheckResponse": this.healthCheck.handleResponse(msg); break; default: this.logger.error("Unknown inbound message", { originalMessageEventData: msg, }); return; } } handleConnectionAcknowledge(msg) { this.connectionId = msg.connectionId; this.logger.debug("Connection acknowledged by subject", { connectionId: msg.connectionId, queuedMessageCount: this.upstreamMessageQueue.length, status: msg.status, }); this.status.update({ status: "ready", connectionId: msg.connectionId, }); this.connectionEstablished = true; // Sends any messages in queue while (this.upstreamMessageQueue.length) { const msg = this.upstreamMessageQueue.shift(); this.sendMessageToSubject(msg); } this.healthCheck.start(msg); this.logger.debug("Proxy connection ready", { connectionId: this.connectionId, }); } handleResponse(msg) { this.requestManager.processResponse(msg); } handlePublish(msg) { const { handlerId, topic } = msg; if (handlerId) { const handler = this.subscriptions.getById(topic, handlerId); if (handler) { void this.handleAsyncSubscriptionHandlerInvoke({ handler, handlerId }, msg); } } else { this.subscriptions .get(topic) .map((handlerIdMapping) => void this.handleAsyncSubscriptionHandlerInvoke(handlerIdMapping, msg)); } } handleError(msg) { if (msg.isFatal) { const { message: reason, type: _ } = msg, details = proxy_rest(msg, ["message", "type"]); this.status.update({ status: "error", reason: reason, details }); } this.publishError({ message: msg.message, key: msg.key, details: msg.details, isFatal: msg.isFatal, proxyStatus: msg.status, }); } publishError(error) { const fullError = Object.assign(Object.assign({}, error), { connectionStatus: this.connectionStatus }); this.errorService.invoke(fullError); } handleAsyncSubscriptionHandlerInvoke(_a, _b) { return proxy_awaiter(this, arguments, void 0, function* ({ handler, handlerId }, { topic, data }) { try { yield handler(data); } catch (error) { this.logger.error("An error occurred when handling subscription", { topic, error, handlerId, }); } }); } get connectionStatus() { return this.status.getStatus(); } onError(handler) { this.errorService.onError(handler); } offError(handler) { this.errorService.offError(handler); } onConnectionStatusChange(handler) { this.status.onChange(handler); } offConnectionStatusChange(handler) { this.status.offChange(handler); } onHealthCheckStatusChanged(handler) { this.healthCheck.onStatusChanged(handler); } offHealthCheckStatusChanged(handler) { this.healthCheck.offStatusChanged(handler); } /** * @deprecated Use addChildIframeChannel instead. This method will be removed in a future version. */ addChildChannel(params) { // Legacy method that only supports MessagePort channels this.addChildIframeChannel(params); } /** * Adds a component-based child channel to the proxy. * * This method establishes a communication channel using component function calls instead * of MessagePorts. This is useful when both the proxy and child entity exist in the same * execution context, such as within the same browser window or iframe. * * Component channels provide better performance than iframe channels since they avoid * the overhead of serialization and can support synchronous communication patterns. * * @param params - Component channel configuration * @param params.connectionId - UUID identifier for this channel connection * @param params.providerId - UUID of the provider that owns this channel * @param params.sendDownstreamMessage - Function to send messages to the child entity * @param params.setUpstreamMessageHandler - Function to register upstream message handler * * @example * ```typescript * proxy.addChildComponentChannel({ * connectionId: "child-uuid", * providerId: "provider-uuid", * sendDownstreamMessage: (message) => childComponent.receive(message), * setUpstreamMessageHandler: (handler) => childComponent.onUpstream = handler * }); * ``` */ addChildIframeChannel(params) { this.channelManager.addChannel(Object.assign(Object.assign({}, params), { type: "iframe" })); } /** * Adds a component-based child channel for communication with child entities. * * This method establishes a communication channel using direct function calls instead * of MessagePorts. This is useful when both the proxy and child entity exist in the same * execution context and can directly reference each other's functions. * * @param params - Configuration parameters for the component function channel * @param params.connectionId - Unique UUID identifier for this channel connection * @param params.providerId - UUID of the provider that owns this channel connection * @param params.sendDownstreamMessage - Function to send messages from proxy to child entity * @param params.setUpstreamMessageHandler - Function to register handler for messages from child entity * * @example * ```typescript * // Child entity exposes these functions * const childAPI = { * receive: (message) => { }, * onUpstream: null as ((message) => void) | null * }; * * proxy.addChildComponentChannel({ * connectionId: "550e8400-e29b-41d4-a716-446655440001", // UUID * providerId: "6ba7b810-9dad-11d1-80b4-00c04fd430c8", // UUID * sendDownstreamMessage: (message) => { * childAPI.receive(message); * }, * setUpstreamMessageHandler: (handler) => { * childAPI.onUpstream = handler; * } * }); * ``` */ addChildComponentChannel(params) { this.channelManager.addChannel(Object.assign(Object.assign({}, params), { type: "component" })); } /** * Updates an existing iframe channel with a new MessagePort. * * This method is only applicable to iframe channels. Component channels cannot * be updated and will result in an error. The old MessagePort is properly cleaned up * (event listeners removed, port closed) before the new port is configured. * * @param params - Update parameters * @param params.connectionId - UUID identifier for the channel to update * @param params.port - New MessagePort instance to replace the existing one * @param params.providerId - UUID of the provider that owns this channel * * @example * ```typescript * const { port1, port2 } = new MessageChannel(); * proxy.updateChildIframeChannelPort({ * connectionId: "550e8400-e29b-41d4-a716-446655440000", * port: port1, * providerId: "6ba7b810-9dad-11d1-80b4-00c04fd430c8" * }); * ``` */ updateChildIframeChannelPort(params) { this.channelManager.updateChannelPort(params); } /** * @deprecated Use updateChildIframeChannelPort instead. This method will be removed in a future version. */ updateChildChannelPort(params) { this.updateChildIframeChannelPort(params); } getConnectionId() { if (this.connectionId) return Promise.resolve(this.connectionId); return new Promise((resolve, reject) => { let timeout = undefined; const handler = (evt) => { if (evt.status === "ready") { this.offConnectionStatusChange(handler); clearInterval(timeout); resolve(evt.connectionId); } }; timeout = setTimeout(() => { this.logger.error("Timeout getting connection id"); this.offConnectionStatusChange(handler); reject(new Error("Timeout getting connectionId")); }, 10 * 1000); this.onConnectionStatusChange(handler); }); } resetConnection(reason) { this.logger.debug("Resetting connection", { reason, connectionId: this.connectionId, }); this.connectionEstablished = false; this.status.update({ status: "reset", reason, }); const { subscriptionHandlerCount } = this.restoreAllHandler(); this.logger.info("Resetting proxy", { reason, subscriptionHandlerCount, }); this.logger.debug("Connection reset complete, restoring handlers", { subscriptionHandlerCount, }); } restoreAllHandler() { var _a; const subscriptionHandlerIds = this.subscriptions.getAllSubscriptionHandlerIds(); // Restore all subscriptions subscriptionHandlerIds === null || subscriptionHandlerIds === void 0 ? void 0 : subscriptionHandlerIds.map(({ topic, handlerId }) => ({ type: "subscribe", topic, messageOrigin: this.getUpstreamMessageOrigin(), handlerId, })).forEach((msg) => this.sendOrQueueMessageToSubject(msg)); return { subscriptionHandlerCount: (_a = subscriptionHandlerIds === null || subscriptionHandlerIds === void 0 ? void 0 : subscriptionHandlerIds.length) !== null && _a !== void 0 ? _a : -1 }; } unsubscribeAllHandlers() { var _a; const subscriptionHandlerIds = this.subscriptions.getAllSubscriptionHandlerIds(); this.logger.info("Unsubscribing all handlers from proxy", { subscriptionHandlerCount: (_a = subscriptionHandlerIds === null || subscriptionHandlerIds === void 0 ? void 0 : subscriptionHandlerIds.length) !== null && _a !== void 0 ? _a : -1, }); subscriptionHandlerIds === null || subscriptionHandlerIds === void 0 ? void 0 : subscriptionHandlerIds.map(({ topic }) => ({ type: "unsubscribe", topic, messageOrigin: this.getUpstreamMessageOrigin(), })).forEach((msg) => this.sendOrQueueMessageToSubject(msg)); } } //# sourceMappingURL=proxy.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/proxy/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/subscription-handler-relay.js var subscription_handler_relay_awaiter = (undefined && undefined.__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()); }); }; class SubscriptionHandlerRelay { constructor(provider) { this.handlersMap = new Map(); this.provider = provider; this.logger = new ConnectLogger({ source: "subscription-handler-relay", provider, mixin: () => ({ namespace: this.namespace, topicKey: this.topicKey, }), }); } get supportsParameter() { return true; } on(handler, parameter) { if (parameter && !this.supportsParameter) { throw new Error("on provided unsupported parameter"); } const parameterHandlerMap = this.getParameterInternalHandlerMap(handler); // Do not add when handler / parameter pair already exists if (parameterHandlerMap.has(parameter)) return; const internalHandler = ((evt) => subscription_handler_relay_awaiter(this, void 0, void 0, function* () { if (this.skipRelay(evt)) return; let externalEvent; try { externalEvent = yield this.translate(evt); } catch (error) { this.logger.error("An error occurred when translating event", { error, parameter, }); // Stop execution. Rethrowing would produce a duplicate error message. return; } try { yield handler(externalEvent); } catch (error) { this.logger.error("Error in event handler", { error, parameter, }); } })); parameterHandlerMap.set(parameter, internalHandler); this.getProxy().subscribe({ key: this.topicKey, parameter }, internalHandler); } off(handler, parameter) { var _a; if (parameter && !this.supportsParameter) { throw new Error("off provided unsupported parameter"); } const internalHandler = (_a = this.handlersMap.get(handler)) === null || _a === void 0 ? void 0 : _a.get(parameter); if (!internalHandler) return; const parameterMap = this.handlersMap.get(handler); if ((parameterMap === null || parameterMap === void 0 ? void 0 : parameterMap.delete(parameter)) && parameterMap.size < 1) this.handlersMap.delete(handler); this.getProxy().unsubscribe({ key: this.topicKey, parameter }, internalHandler); } // eslint-disable-next-line @typescript-eslint/no-unused-vars skipRelay(event) { return false; } destroy() { const proxy = this.getProxy(); for (const [externalHandler, parameterMapping] of this.handlersMap) { for (const [parameter, internalHandler] of parameterMapping) { proxy.unsubscribe({ key: this.topicKey, parameter }, internalHandler); parameterMapping.delete(parameter); } this.handlersMap.delete(externalHandler); } } getParameterInternalHandlerMap(externalHandler) { if (!this.handlersMap.has(externalHandler)) { this.handlersMap.set(externalHandler, new Map()); } return this.handlersMap.get(externalHandler); } getProxy() { if (!this.proxy) { const proxy = this.provider.getProxy(); this.proxy = createModuleProxy(proxy, this.namespace); } return this.proxy; } } //# sourceMappingURL=subscription-handler-relay.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/timeout-tracker.js class TimeoutTracker { constructor(onCancelled, timeoutMs) { this.timeoutMs = timeoutMs; this.onCancelled = onCancelled; this.timeout = setTimeout(() => this.handleCancel(), this.timeoutMs); this.status = "running"; this.logger = new ConnectLogger({ source: "core.utility.timeout-tracker", mixin: () => ({ timeoutMs: this.timeoutMs, timeoutTrackerStatus: this.status, }), }); } static start(onCancelled, ms) { return new TimeoutTracker(onCancelled, ms); } complete() { switch (this.status) { case "running": return this.handleComplete(); case "completed": this.logger.debug("TimeoutTracker already marked complete. No action."); return true; case "cancelled": this.logger.info("Attempted to complete a TimeoutTracker that has already been cancelled"); return false; } } isCancelled() { return this.status === "cancelled"; } getStatus() { return this.status; } handleCancel() { switch (this.status) { case "running": this.status = "cancelled"; this.logger.info("TimeoutTracker has timed out. Invoking onCancelled Handler"); this.invokeOnCancelled(); break; case "completed": this.logger.debug("Cancel operation for TimerTracker invoked after already completed. No action."); break; default: throw new Error("Cancel operation in TimerTracker called during an unexpected time."); } } handleComplete() { this.status = "completed"; clearTimeout(this.timeout); return true; } invokeOnCancelled() { try { this.onCancelled({ timeoutMs: this.timeoutMs }); } catch (error) { this.logger.error("Error when attempting to invoke TimeoutTrackerCancelledHandler", { error }); } } } //# sourceMappingURL=timeout-tracker.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/utility/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/logging/log-level.js var LogLevel; (function (LogLevel) { LogLevel[LogLevel["trace"] = 1] = "trace"; LogLevel[LogLevel["debug"] = 2] = "debug"; LogLevel[LogLevel["info"] = 3] = "info"; LogLevel[LogLevel["warn"] = 4] = "warn"; LogLevel[LogLevel["error"] = 5] = "error"; })(LogLevel || (LogLevel = {})); //# sourceMappingURL=log-level.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/logging/log-data-console-writer.js /* eslint-disable no-console */ function logToConsole(level, message, data) { if (data) { switch (level) { case LogLevel.error: console.error(message, data); break; case LogLevel.warn: console.warn(message, data); break; case LogLevel.info: console.info(message, data); break; case LogLevel.debug: console.debug(message, data); break; case LogLevel.trace: console.trace(message, data); break; default: console.log(message, data); break; } } else { switch (level) { case LogLevel.error: console.error(message); break; case LogLevel.warn: console.warn(message); break; case LogLevel.info: console.info(message); break; case LogLevel.debug: console.debug(message); break; case LogLevel.trace: console.trace(message); break; default: console.log(message); break; } } } //# sourceMappingURL=log-data-console-writer.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/logging/log-data-transformer.js class LogDataTransformer { constructor(mixin) { this.mixin = mixin; } getTransformedData(level, data) { if (!this.mixin) return data; return Object.assign(Object.assign({}, (data !== null && data !== void 0 ? data : {})), this.mixin(data !== null && data !== void 0 ? data : {}, level)); } } //# sourceMappingURL=log-data-transformer.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/logging/connect-logger.js class connect_logger_ConnectLogger { constructor(param) { this._proxy = null; this._logToConsoleLevel = null; this.loggerId = generateStringId(8); if (typeof param === "string") { this.source = param; this.dataTransformer = new LogDataTransformer(undefined); } else { this.source = param.source; if (param.provider && typeof param.provider === "function") this.providerFactory = param.provider; else this.provider = param.provider; this.dataTransformer = new LogDataTransformer(param.mixin); this.logOptions = param.options; } } trace(message, data, options) { this.log(LogLevel.trace, message, data, options); } debug(message, data, options) { this.log(LogLevel.debug, message, data, options); } info(message, data, options) { this.log(LogLevel.info, message, data, options); } warn(message, data, options) { this.log(LogLevel.warn, message, data, options); } error(message, data, options) { this.log(LogLevel.error, message, data, options); } log(level, message, data, options) { const transformedData = this.dataTransformer.getTransformedData(level, data); if (!this.ignoreRemote(options)) { this.getProxy().log({ level, source: this.source, loggerId: this.loggerId, message, data: transformedData, }); } if (this.applyDuplicateMessageToConsole(level, options)) { logToConsole(level, message, transformedData); } } getProvider() { if (!this.provider) { this.provider = this.providerFactory ? this.providerFactory() : getGlobalProvider(); } return this.provider; } getProxy() { if (!this._proxy) { this._proxy = this.getProvider().getProxy(); } return this._proxy; } applyDuplicateMessageToConsole(level, options) { return ((options === null || options === void 0 ? void 0 : options.duplicateMessageToConsole) || this.getLogConsoleLevel() <= level); } getLogConsoleLevel() { var _a, _b, _c, _d; if (!this._logToConsoleLevel) { this._logToConsoleLevel = ((_a = this.logOptions) === null || _a === void 0 ? void 0 : _a.minLogToConsoleLevelOverride) ? this.logOptions.minLogToConsoleLevelOverride : ((_d = (_c = (_b = this.getProvider().config) === null || _b === void 0 ? void 0 : _b.logging) === null || _c === void 0 ? void 0 : _c.minLogToConsoleLevel) !== null && _d !== void 0 ? _d : LogLevel.error); } return this._logToConsoleLevel; } ignoreRemote(options) { var _a, _b, _c; return (((_b = (_a = this.logOptions) === null || _a === void 0 ? void 0 : _a.remoteIgnore) !== null && _b !== void 0 ? _b : false) || ((_c = options === null || options === void 0 ? void 0 : options.remoteIgnore) !== null && _c !== void 0 ? _c : false)); } } //# sourceMappingURL=connect-logger.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/logging/sanitize-data.js function sanitizeData(data) { if (!data) return undefined; try { return deepClone(data); } catch (_a) { return { error: "Data failed to sanitize. The original data is not available", }; } } //# sourceMappingURL=sanitize-data.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/logging/log-message-factory.js function createLogMessage({ level, source, message, loggerId, data }, context, messageOrigin) { // Sanitize guards against a caller provided data object containing a // non-cloneable object which will fail if sent through a message channel const sanitizedData = sanitizeData(data); return { type: "log", level, time: new Date(), source, message, loggerId, data: sanitizedData, context, messageOrigin, }; } //# sourceMappingURL=log-message-factory.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/logging/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/provider/provider-base.js class AmazonConnectProviderBase { constructor({ config, proxyFactory }) { this._id = generateUUID(); if (!proxyFactory) { throw new Error("Attempted to get Proxy before setting up factory"); } if (!config) { throw new Error("Failed to include config"); } this.proxyFactory = proxyFactory; this._config = config; } get id() { return this._id; } getProxy() { if (!this.proxy) { this.proxy = this.proxyFactory(this); this.proxy.init(); } return this.proxy; } get config() { return Object.assign({}, this._config); } onError(handler) { this.getProxy().onError(handler); } offError(handler) { this.getProxy().offError(handler); } static initializeProvider(provider) { if (this.isInitialized) { const msg = "Attempted to initialize provider more than one time."; const details = {}; try { // Attempts to get the existing provider for logging const existingProvider = getGlobalProvider(); const logger = new connect_logger_ConnectLogger({ source: "core.amazonConnectProvider.init", provider: existingProvider, }); logger.error(msg); } catch (e) { // In the event of a error when logging or attempting // to get provider when logging, capture the message // in the error being thrown details.loggingError = e === null || e === void 0 ? void 0 : e.message; } throw new ConnectError({ errorKey: "attemptInitializeMultipleProviders", reason: msg, details, }); } setGlobalProvider(provider); this.isInitialized = true; // Getting the proxy sets up the connection with subject provider.getProxy(); return provider; } } AmazonConnectProviderBase.isInitialized = false; //# sourceMappingURL=provider-base.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/provider/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/context/module-context.js class ModuleContext { constructor(engineContext, moduleNamespace) { this.engineContext = engineContext; this.moduleNamespace = moduleNamespace; } get proxy() { if (!this.moduleProxy) { const proxy = this.engineContext.getProvider().getProxy(); const moduleNamespace = this.moduleNamespace; this.moduleProxy = module_proxy_factory_createModuleProxy(proxy, moduleNamespace); } return this.moduleProxy; } getProvider() { return this.engineContext.getProvider(); } createLogger(params) { if (typeof params === "object") { return new connect_logger_ConnectLogger(Object.assign(Object.assign({}, params), { provider: () => this.engineContext.getProvider() })); } else { return new connect_logger_ConnectLogger({ source: params, provider: () => this.engineContext.getProvider(), }); } } createMetricRecorder(params) { if (typeof params === "object") { return new ConnectMetricRecorder(Object.assign(Object.assign({}, params), { provider: () => this.engineContext.getProvider() })); } else { return new ConnectMetricRecorder({ namespace: params, provider: () => this.engineContext.getProvider(), }); } } } //# sourceMappingURL=module-context.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/context/context.js class Context { constructor(provider) { this._provider = provider; } getProvider() { if (this._provider) return this._provider; else return getGlobalProvider(); } getModuleContext(namespace) { return new ModuleContext(this, namespace); } } //# sourceMappingURL=context.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/context/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/client/get-module-context.js function getModuleContext({ namespace, config, }) { if (config && "context" in config && config.context) { return config.context; } else if (isAmazonConnectProvider(config)) { return new Context(config).getModuleContext(namespace); } else { return new Context(config === null || config === void 0 ? void 0 : config.provider).getModuleContext(namespace); } } //# sourceMappingURL=get-module-context.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/client/connect-client.js class ConnectClient { constructor(namespace, config) { this.namespace = namespace; this.context = getModuleContext({ namespace, config }); } } class ConnectClientWithOptionalConfig { constructor(namespace, config) { this.namespace = namespace; this.context = getModuleContext({ namespace, config }); } } //# sourceMappingURL=connect-client.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/client/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/core/lib-esm/index.js //# sourceMappingURL=index.js.map /***/ }), /***/ 275: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { AmazonConnectGRStreamsSite: () => (/* reexport */ AmazonConnectGRStreamsSite), AmazonConnectStreamsSite: () => (/* reexport */ AmazonConnectStreamsSite), GlobalResiliencyRegion: () => (/* reexport */ GlobalResiliencyRegion) }); // EXTERNAL MODULE: ./node_modules/@amazon-connect/core/lib-esm/index.js + 55 modules var lib_esm = __webpack_require__(238); ;// ./node_modules/@amazon-connect/site/lib-esm/proxy/site-proxy.js class SiteProxy extends lib_esm/* Proxy */.by { constructor(provider, instanceUrl) { super(provider); if (instanceUrl !== undefined) { // Two-parameter constructor: use the explicit instanceUrl parameter this.instanceUrl = instanceUrl; } else { // Single-parameter constructor: get instanceUrl from config this.instanceUrl = provider.config.instanceUrl; } this.postMessageHandler = this.listenForInitialMessage.bind(this); this.proxyLogger = new lib_esm/* ConnectLogger */.pg({ source: "siteProxy", provider, }); } initProxy() { this.status.update({ status: "connecting" }); window.addEventListener("message", this.postMessageHandler); } resetConnection(reason) { super.resetConnection(reason); this.messagePort = undefined; this.status.update({ status: "connecting" }); } sendMessageToSubject(message) { if (this.messagePort) { this.messagePort.postMessage(message); } else { // This could ever be reached if the setup did not occur and the // acknowledge process was initiated by non supported means. this.proxyLogger.error("Failed to send UpstreamMessage. MessagePort not set", { messageType: message.type, }); } } addContextToLogger() { return {}; } listenForInitialMessage(evt) { // Verify origin if (!this.verifyOrigin(evt)) { // Log message is handled in the function with the actual reason for failure return; } if (this.verifyEventSource(evt)) { // Verify message if (evt.data.type !== "cross-domain-adapter-init") { this.invalidInitMessageHandler(evt.data); return; } // When a message port already exists if (this.messagePort) { this.resetConnection("Subsequent Message Port Detected"); this.proxyLogger.info("Subsequent message port received. Resetting connection"); } this.messagePort = evt.ports[0]; if (!this.messagePort) { throw new Error("message port not provided by iframe"); } this.messagePort.onmessage = this.consumerMessageHandler.bind(this); this.status.update({ status: "initializing" }); this.messagePort.postMessage({ type: "cross-domain-site-ready", providerId: this.provider.id, }); this.proxyLogger.debug("CDA Post message handler removed"); } } verifyOrigin(evt) { const eventOrigin = evt.origin; if (!eventOrigin) { this.proxyLogger.warn("No origin provided in event. Ignoring event."); return false; } let expectedOrigin; try { expectedOrigin = new URL(this.instanceUrl).origin; } catch (error) { this.proxyLogger.error("Unable to parse expected origin from instanceUrl. Cannot match", { error, eventOrigin, instanceUrl: this.instanceUrl, }, { duplicateMessageToConsole: true }); return false; } if (eventOrigin !== expectedOrigin) { if (evt.data.type === "cross-domain-adapter-init") { // Only logging for the specific handshake message. Otherwise just ignore this.proxyLogger.warn("Origin of message with type 'cross-domain-adapter-init' did not expected instance value. Ignoring", { expectedOrigin, eventOrigin, }, { duplicateMessageToConsole: true }); } return false; } return true; } } //# sourceMappingURL=site-proxy.js.map ;// ./node_modules/@amazon-connect/site/lib-esm/proxy/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/site/lib-esm/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/site-streams/lib-esm/streams-site-proxy.js class StreamsSiteProxy extends SiteProxy { constructor(provider) { super(provider); this.ccpIFrame = null; this.unexpectedIframeWarningCount = 0; } get proxyType() { return "streams-site"; } setCCPIframe(iframe) { const isCcpIFrameSet = Boolean(this.ccpIFrame); this.ccpIFrame = iframe; this.unexpectedIframeWarningCount = 0; if (isCcpIFrameSet) this.resetConnection("CCP IFrame Updated"); } getUpstreamMessageOrigin() { return Object.assign({ _type: "streams-site", providerId: this.provider.id }, (0,lib_esm/* getOriginAndPath */.xQ)()); } verifyEventSource(evt) { const ccpIFrame = this.ccpIFrame; if (!ccpIFrame) { this.proxyLogger.error("CCP Iframe not provided to proxy. Unable to verify event to Connect to CCP.", { origin: evt.origin, }); return false; } const valid = evt.source === ccpIFrame.contentWindow; if (!valid) { this.unexpectedIframeWarningCount++; if (this.unexpectedIframeWarningCount < 5) { this.proxyLogger.warn("Message came from unexpected iframe. Not a valid CCP. Will not connect", { origin: evt.origin, unexpectedIframeWarningCount: this.unexpectedIframeWarningCount, }); } } return valid; } invalidInitMessageHandler() { // CCP sends messages via Streams // Take no action here } } //# sourceMappingURL=streams-site-proxy.js.map ;// ./node_modules/@amazon-connect/site-streams/lib-esm/amazon-connect-streams-site.js class AmazonConnectStreamsSite extends lib_esm/* AmazonConnectProviderBase */.Lt { constructor(config) { super({ config, proxyFactory: (p) => new StreamsSiteProxy(p), }); } static init(config) { const provider = new AmazonConnectStreamsSite(config); AmazonConnectStreamsSite.initializeProvider(provider); return { provider }; } static get default() { return (0,lib_esm/* getGlobalProvider */.Lz)("AmazonConnectStreamsSite has not been initialized"); } setCCPIframe(iframe) { this.getProxy().setCCPIframe(iframe); } } //# sourceMappingURL=amazon-connect-streams-site.js.map ;// ./node_modules/@amazon-connect/site-streams/lib-esm/global-resiliency/global-resiliency-region.js var GlobalResiliencyRegion; (function (GlobalResiliencyRegion) { GlobalResiliencyRegion["Primary"] = "primary"; GlobalResiliencyRegion["Secondary"] = "secondary"; })(GlobalResiliencyRegion || (GlobalResiliencyRegion = {})); //# sourceMappingURL=global-resiliency-region.js.map ;// ./node_modules/@amazon-connect/site-streams/lib-esm/global-resiliency/regional-proxy.js class RegionalProxy extends SiteProxy { constructor({ provider, region, getUpstreamMessageOrigin, relayToGlobalResiliencyProxy, }) { super(provider, region === GlobalResiliencyRegion.Primary ? provider.config.primaryInstanceUrl : provider.config.secondaryInstanceUrl); this.getParentUpstreamMessageOrigin = getUpstreamMessageOrigin; this.relayToGlobalResiliencyProxy = relayToGlobalResiliencyProxy; this.ccpIFrame = null; this.region = region; this.unexpectedIframeWarningCount = 0; } get proxyType() { return "acgr-regional-proxy"; } setCCPIframe(iframe) { const isCcpIFrameSet = Boolean(this.ccpIFrame); this.ccpIFrame = iframe; this.unexpectedIframeWarningCount = 0; if (isCcpIFrameSet) this.resetConnection("CCP IFrame Updated"); } handleMessageFromSubject(msg) { switch (msg.type) { case "response": case "publish": case "error": this.relayToGlobalResiliencyProxy(msg); break; default: // All other messages handled by this proxy super.handleMessageFromSubject(msg); } } getUpstreamMessageOrigin() { return this.getParentUpstreamMessageOrigin(); } verifyEventSource(evt) { const ccpIFrame = this.ccpIFrame; if (!ccpIFrame) { this.proxyLogger.error("CCP Iframe not provided to proxy. Unable to verify event to Connect to CCP.", { origin: evt.origin, }); return false; } const valid = evt.source === ccpIFrame.contentWindow; if (!valid) { this.unexpectedIframeWarningCount++; if (this.unexpectedIframeWarningCount < 5) { this.proxyLogger.warn("Message came from unexpected iframe. Not a valid CCP. Will not connect", { origin: evt.origin, unexpectedIframeWarningCount: this.unexpectedIframeWarningCount, }); } } return valid; } sendOrQueueMessageToSubject(message) { super.sendOrQueueMessageToSubject(message); } invalidInitMessageHandler() { // CCP sends messages via Streams // Take no action here } } //# sourceMappingURL=regional-proxy.js.map ;// ./node_modules/@amazon-connect/site-streams/lib-esm/global-resiliency/verify-region.js function verifyRegion(region) { const validValues = Object.values(GlobalResiliencyRegion); if (!validValues.includes(region)) { throw new Error(`Invalid region: ${region}. Valid regions are: ${validValues.join(", ")}`); } } //# sourceMappingURL=verify-region.js.map ;// ./node_modules/@amazon-connect/site-streams/lib-esm/global-resiliency/global-resiliency-proxy.js class GlobalResiliencyProxy extends lib_esm/* Proxy */.by { constructor(provider) { super(provider); this.activeRegion = GlobalResiliencyRegion.Primary; this.regionProxies = { [GlobalResiliencyRegion.Primary]: new RegionalProxy({ provider, region: GlobalResiliencyRegion.Primary, getUpstreamMessageOrigin: this.getUpstreamMessageOrigin.bind(this), relayToGlobalResiliencyProxy: this.handleMessageFromSubject.bind(this), }), [GlobalResiliencyRegion.Secondary]: new RegionalProxy({ provider, region: GlobalResiliencyRegion.Secondary, getUpstreamMessageOrigin: this.getUpstreamMessageOrigin.bind(this), relayToGlobalResiliencyProxy: this.handleMessageFromSubject.bind(this), }), }; this.proxyLogger = new lib_esm/* ConnectLogger */.pg({ source: "globalResiliencyProxy", provider, }); } initProxy() { Object.values(this.regionProxies).forEach((proxy) => proxy.init()); } setCCPIframe({ iframe, region }) { verifyRegion(region); this.regionProxies[region].setCCPIframe(iframe); } setActiveRegion(region) { verifyRegion(region); if (region !== this.activeRegion) { const previousRegionProxy = this.regionProxies[this.activeRegion]; const currentRegionProxy = this.regionProxies[region]; // Removes subscriptions from original engine this.unsubscribeAllHandlers(); this.proxyLogger.info("Active region changed", { current: region, instanceUrl: currentRegionProxy.instanceUrl, previousInstanceUrl: previousRegionProxy.instanceUrl, }); this.activeRegion = region; // Adds subscriptions to new engine this.restoreAllHandler(); const currentStatus = this.status.getStatus(); const activeRegionStatus = currentRegionProxy.connectionStatus; switch (activeRegionStatus) { case "ready": this.proxyLogger.info("Active region is ready", { activeRegionStatus, }); this.status.update({ status: "ready", connectionId: currentRegionProxy["connectionId"], }); break; case "connecting": case "initializing": if (currentStatus !== activeRegionStatus) { this.status.update({ status: activeRegionStatus }); } break; case "error": if (currentStatus !== activeRegionStatus) { this.status.update({ status: "error", reason: "new active region in error on transition", details: { region: this.activeRegion }, }); } break; } } } get proxyType() { return "global-resiliency-proxy"; } // Override the normal sendOrQueueMessageToSubject to rely on the // of the regional proxy sendOrQueueMessageToSubject(message) { this.regionProxies[this.activeRegion].sendOrQueueMessageToSubject(message); } addContextToLogger() { return { activeRegion: this.activeRegion }; } // When sending a message, it goes to the sendOrQueueMessageToSubject of the // active region sendMessageToSubject(message) { this.regionProxies[this.activeRegion].sendOrQueueMessageToSubject(message); } getUpstreamMessageOrigin() { return Object.assign(Object.assign({ _type: "global-resiliency-streams-site", providerId: this.provider.id }, (0,lib_esm/* getOriginAndPath */.xQ)()), { activeRegion: this.activeRegion }); } addChildIframeChannel(params) { this.regionProxies[this.activeRegion].addChildIframeChannel(params); } addChildComponentChannel(params) { this.regionProxies[this.activeRegion].addChildComponentChannel(params); } updateChildIframeChannelPort(params) { this.regionProxies[this.activeRegion].updateChildIframeChannelPort(params); } } //# sourceMappingURL=global-resiliency-proxy.js.map ;// ./node_modules/@amazon-connect/site-streams/lib-esm/global-resiliency/amazon-connect-gr-streams-site.js class AmazonConnectGRStreamsSite extends lib_esm/* AmazonConnectProviderBase */.Lt { constructor(config) { super({ config, proxyFactory: (p) => new GlobalResiliencyProxy(p), }); } static init(config) { const provider = new AmazonConnectGRStreamsSite(config); AmazonConnectGRStreamsSite.initializeProvider(provider); return { provider }; } static get default() { return (0,lib_esm/* getGlobalProvider */.Lz)("AmazonConnectGRStreamsSite has not been initialized"); } // This should be called for each region on startup setCCPIframe(iframe) { this.getProxy().setCCPIframe(iframe); } setActiveRegion(region) { this.getProxy().setActiveRegion(region); } } //# sourceMappingURL=amazon-connect-gr-streams-site.js.map ;// ./node_modules/@amazon-connect/site-streams/lib-esm/global-resiliency/index.js //# sourceMappingURL=index.js.map ;// ./node_modules/@amazon-connect/site-streams/lib-esm/index.js //# sourceMappingURL=index.js.map /***/ }), /***/ 825: /***/ (() => { (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; connect.agentApp = {}; var APP = { CCP: 'ccp', GUIDES: 'customviews' }; connect.agentApp.initCCP = connect.core.initCCP; connect.agentApp.isInitialized = function (instanceAlias) {}; connect.agentApp.initAppCommunication = function (iframeId, endpoint) { var iframe = document.getElementById(iframeId); var iframeConduit = new connect.IFrameConduit(endpoint, window, iframe); var BROADCAST_TYPE = [connect.AgentEvents.UPDATE, connect.ContactEvents.VIEW, connect.EventType.ACKNOWLEDGE, connect.EventType.TERMINATED, connect.TaskEvents.CREATED, connect.EmailEvents.CREATED]; iframe.addEventListener('load', function (e) { BROADCAST_TYPE.forEach(function (type) { connect.core.getUpstream().onUpstream(type, function (data) { iframeConduit.sendUpstream(type, data); }); }); }); }; var getConnectUrl = function getConnectUrl(ccpUrl) { var pos = ccpUrl.indexOf('ccp-v2'); return ccpUrl.slice(0, pos - 1); }; var signOutThroughCCP = function signOutThroughCCP(ccpUrl) { var logoutUrl = getConnectUrl(ccpUrl) + '/logout'; return connect.fetch(logoutUrl, { credentials: 'include' }).then(function () { var eventBus = connect.core.getEventBus(); eventBus.trigger(connect.EventType.TERMINATE); return true; })["catch"](function (e) { connect.getLog().error('An error occured on logout.' + e).withException(e); window.location.href = logoutUrl; return false; }); }; var removeAppData = function removeAppData(appName) { connect.agentApp.AppRegistry["delete"](appName); }; /** * Initializes custom views application for a given contact. It sets up the iframe for the custom view and * creates the lifecycle hook of the custom view based on the contact's status. * Extended to support deduplication. * Works whether the contact ID is passed directly in config or derived from a live connect.Contact object. * * @param {string} connectUrl - The URL for the custom view. * @param {string} containerDOM - The DOM container for the view iframe. * @param {AppOptions} config - Configuration object containing contact details and other settings. */ var initCustomViewsApp = function initCustomViewsApp(connectUrl, containerDOM, config) { var _config$customViewsPa = config.customViewsParams, contact = _config$customViewsPa.contact, disableAutoDestroy = _config$customViewsPa.disableAutoDestroy, iframeSuffix = _config$customViewsPa.iframeSuffix, _config$customViewsPa2 = _config$customViewsPa.terminateCustomViewOptions, terminateCustomViewOptions = _config$customViewsPa2 === void 0 ? {} : _config$customViewsPa2, _config$customViewsPa3 = _config$customViewsPa.deduplicate, deduplicate = _config$customViewsPa3 === void 0 ? true : _config$customViewsPa3; var contactFlowId = config.customViewsParams.contactFlowId; var contactId = extractContactId(contact); var agentConnectionId; var contactStatus; var resolveContactObject = function resolveContactObject(callback) { if (typeof contact === 'string') { console.debug('[CustomViews] Resolving contact ID string...'); connect.agent(function (agent) { var matchedContact = agent.getContacts().find(function (c) { try { var _c$getContactId; return ((_c$getContactId = c.getContactId) === null || _c$getContactId === void 0 ? void 0 : _c$getContactId.call(c)) === contact; } catch (_unused) { return false; } }); if (!matchedContact) { console.warn('[CustomViews] Unable to resolve contact ID to live contact object.'); } callback(matchedContact); }); } else { callback(contact); } }; var bindOnDestroy = function bindOnDestroy(resolvedContact) { if (disableAutoDestroy) return; resolvedContact.onDestroy(function () { var _terminateCustomViewO, _terminateCustomViewO2, _terminateCustomViewO3; connect.core.terminateCustomView(connectUrl, iframeSuffix, { timeout: (_terminateCustomViewO = terminateCustomViewOptions.timeout) !== null && _terminateCustomViewO !== void 0 ? _terminateCustomViewO : 5000, hideIframe: (_terminateCustomViewO2 = terminateCustomViewOptions.hideIframe) !== null && _terminateCustomViewO2 !== void 0 ? _terminateCustomViewO2 : true, resolveIframe: (_terminateCustomViewO3 = terminateCustomViewOptions.resolveIframe) !== null && _terminateCustomViewO3 !== void 0 ? _terminateCustomViewO3 : true }); }); console.debug('[CustomViews] onDestroy handler registered.'); }; var extractAgentConnectionId = function extractAgentConnectionId(resolvedContact) { try { var connections = resolvedContact.toSnapshot().contactData.connections; var agentConn = connections.find(function (conn) { return conn.type === 'agent'; }); return agentConn === null || agentConn === void 0 ? void 0 : agentConn.connectionId; } catch (err) { console.warn('[CustomViews] Failed to extract agentConnectionId.'); return undefined; } }; var extractContactStatus = function extractContactStatus(resolvedContact) { try { return resolvedContact.toSnapshot().contactData.state.type; } catch (err) { console.warn('[CustomViews] Failed to extract contact status.'); return undefined; } }; var continueInit = function continueInit(contactId, agentConnectionId, status) { var _window$top; var appName = iframeSuffix ? "".concat(APP.GUIDES).concat(iframeSuffix) : APP.GUIDES; var iframe = (containerDOM === null || containerDOM === void 0 ? void 0 : containerDOM.querySelector("iframe[id='".concat(appName, "']"))) || document.getElementById(appName) || ((_window$top = window.top) === null || _window$top === void 0 ? void 0 : _window$top.document.getElementById(appName)); if (!iframe) { throw new Error("[CustomViews] Iframe not found for app: ".concat(appName)); } var tabId = AWS.util.uuid.v4(); var params = new URLSearchParams({ agentAppTabId: "".concat(tabId, "-tab") }); if (contactFlowId) params.set('contactFlowId', contactFlowId); if (contactId) params.set('currentContactId', contactId); if (agentConnectionId) params.set('agentConnectionId', agentConnectionId); var dedupId = deduplicate ? status ? status.toUpperCase() : 'DEFAULT' : 'ADHOC'; params.set('duplicateCustomViewsAppId', dedupId); iframe.src = "".concat(connectUrl, "?").concat(params.toString()); console.debug('[CustomViews] Iframe source initialized with state identifier: ', dedupId); }; resolveContactObject(function (resolvedContact) { if (resolvedContact) { contactStatus = extractContactStatus(resolvedContact); contactId = extractContactId(resolvedContact); agentConnectionId = extractAgentConnectionId(resolvedContact); if (agentConnectionId) { console.debug('[CustomViews] Agent connection ID derived from contact object'); } bindOnDestroy(resolvedContact); } continueInit(contactId, agentConnectionId, contactStatus); }); }; var extractContactId = function extractContactId(contact) { if (typeof contact === 'string') { return contact; } try { return contact.getContactId(); } catch (_unused2) { console.error('[CustomViews]: Invalid Contact Provided: ', contact); return undefined; } }; var signInThroughinitCCP = function signInThroughinitCCP(ccpUrl, container, config) { var defaultParams = { ccpUrl: ccpUrl, ccpLoadTimeout: 10000, loginPopup: true, loginUrl: getConnectUrl(ccpUrl) + '/login', softphone: { allowFramedSoftphone: true, disableRingtone: false, allowFramedVideoCall: true, allowFramedScreenSharing: true, allowFramedScreenSharingPopUp: false } }; var ccpParams = connect.merge(defaultParams, config.ccpParams); connect.core.initCCP(container, ccpParams); }; var hasAnySearchParameter = function hasAnySearchParameter(url) { var regex = /[?&]?[^=?&]+=[^=?&]+/g; return regex.test(url); }; connect.agentApp.initApp = function (name, containerId, appUrl, config) { config = config ? config : {}; var endpoint = appUrl.endsWith('/') || hasAnySearchParameter(appUrl) ? appUrl : appUrl + '/'; var onLoad = config.onLoad ? config.onLoad : null; var registerConfig = { endpoint: endpoint, style: config.style, onLoad: onLoad }; var filteredName; if (name === APP.CCP_DR) { filteredName = APP.CCP; } else if (name === APP.GUIDES && config.customViewsParams) { var iframeSuffix = config.customViewsParams.iframeSuffix; if (iframeSuffix) { filteredName = "".concat(APP.GUIDES).concat(iframeSuffix); } else { filteredName = "".concat(APP.GUIDES); } if (connect.agentApp.AppRegistry.get(filteredName) !== undefined) { throw new Error('[CustomViews]: Custom views application with the same name already exists. Please provide a different iframeSuffix for the custom views application.'); } } else { filteredName = name; } var containerElement = typeof containerId === 'string' ? document.getElementById(containerId) : containerId; connect.agentApp.AppRegistry.register(filteredName, registerConfig, containerElement); connect.agentApp.AppRegistry.start(filteredName, function (moduleData) { var endpoint = moduleData.endpoint; var containerDOM = moduleData.containerDOM; return { init: function init() { switch (name) { case APP.CCP: config.ccpParams = config.ccpParams ? config.ccpParams : {}; if (config.style) config.ccpParams.style = config.style; return signInThroughinitCCP(endpoint, containerDOM, config); case APP.GUIDES: if (config.customViewsParams !== undefined) { connect.agentApp.initAppCommunication(filteredName, endpoint, containerDOM); return initCustomViewsApp(endpoint, containerDOM, config); } else { return connect.agentApp.initAppCommunication(filteredName, endpoint, containerDOM); } default: return connect.agentApp.initAppCommunication(filteredName, endpoint, containerDOM); } }, destroy: function destroy() { switch (name) { case APP.CCP: return signOutThroughCCP(endpoint); case APP.GUIDES: if (config.customViewsParams !== undefined) { return removeAppData(filteredName); } else { return null; } default: return null; } } }; }); }; connect.agentApp.stopApp = function (name) { return connect.agentApp.AppRegistry.stop(name); }; })(); /***/ }), /***/ 961: /***/ (() => { (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; var APP = { CCP: 'ccp' }; function AppRegistry() { var moduleData = {}; var makeAppIframe = function makeAppIframe(appName, endpoint, style, onLoad) { var iframe = document.createElement('iframe'); iframe.src = endpoint; iframe.style = style || 'width: 100%; height:100%;'; iframe.id = appName; iframe['aria-label'] = appName; iframe.onload = onLoad; iframe.allow = "clipboard-read; clipboard-write"; iframe.setAttribute("sandbox", "allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"); // TODO: Update sandbox option for 3P widget return iframe; }; return { register: function register(appName, config, containerDOM) { moduleData[appName] = { containerDOM: containerDOM, endpoint: config.endpoint, style: config.style, instance: undefined, onLoad: config.onLoad }; }, start: function start(appName, creator) { if (!moduleData[appName]) return; var containerDOM = moduleData[appName].containerDOM; var endpoint = moduleData[appName].endpoint; var style = moduleData[appName].style; var onLoad = moduleData[appName].onLoad; if (appName !== APP.CCP) { var app = makeAppIframe(appName, endpoint, style, onLoad); containerDOM.appendChild(app); } moduleData[appName].instance = creator(moduleData[appName]); return moduleData[appName].instance.init(); }, get: function get(appName) { return moduleData[appName]; }, "delete": function _delete(appName) { delete moduleData[appName]; }, stop: function stop(appName) { if (!moduleData[appName]) return; var data = moduleData[appName]; var app = data.containerDOM.querySelector('iframe'); if (appName.includes('customviews')) { var iframeIdSelector = "iframe[id='".concat(appName, "']"); app = data.containerDOM.querySelector(iframeIdSelector); } data.containerDOM.removeChild(app); var result; if (data.instance) { result = data.instance.destroy(); delete data.instance; } return result; } }; } global.connect.agentApp.AppRegistry = AppRegistry(); })(); /***/ }), /***/ 610: /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; var _require = __webpack_require__(578), SessionExpirationWarningClient = _require.SessionExpirationWarningClient, sendActivity = _require.sendActivity; var _require2 = __webpack_require__(791), ContactClient = _require2.ContactClient; /*---------------------------------------------------------------- * enum AgentStateType */ connect.AgentStateType = connect.makeEnum(['init', 'routable', 'not_routable', 'offline', 'system', 'error']); connect.AgentStatusType = connect.AgentStateType; /** * enum AgentAvailStates */ connect.AgentAvailStates = connect.makeEnum(['Init', 'Busy', 'AfterCallWork', 'CallingCustomer', 'Dialing', 'Joining', 'PendingAvailable', 'PendingBusy']); /** * enum AgentErrorStates */ connect.AgentErrorStates = connect.makeEnum(['Error', 'AgentHungUp', 'BadAddressAgent', 'BadAddressCustomer', 'Default', 'FailedConnectAgent', 'FailedConnectCustomer', 'InvalidLocale', 'LineEngagedAgent', 'LineEngagedCustomer', 'MissedCallAgent', 'MissedCallCustomer', 'MultipleCcpWindows', 'RealtimeCommunicationError']); /*---------------------------------------------------------------- * enum AddressType */ connect.EndpointType = connect.makeEnum(['phone_number', 'agent', 'queue']); connect.AddressType = connect.EndpointType; /*---------------------------------------------------------------- * enum ConnectionType */ connect.ConnectionType = connect.makeEnum(['agent', 'inbound', 'outbound', 'monitoring']); /*---------------------------------------------------------------- * enum ConnectionStateType */ connect.ConnectionStateType = connect.makeEnum(['init', 'connecting', 'connected', 'hold', 'disconnected', 'silent_monitor', 'barge']); connect.ConnectionStatusType = connect.ConnectionStateType; connect.CONNECTION_ACTIVE_STATES = connect.set([connect.ConnectionStateType.CONNECTING, connect.ConnectionStateType.CONNECTED, connect.ConnectionStateType.HOLD, connect.ConnectionStateType.SILENT_MONITOR, connect.ConnectionStateType.BARGE]); connect.CONNECTION_CONNECTED_STATES = connect.set([connect.ConnectionStateType.CONNECTED, connect.ConnectionStateType.SILENT_MONITOR, connect.ConnectionStateType.BARGE]); /*---------------------------------------------------------------- * enum ContactStateType */ connect.ContactStateType = connect.makeEnum(['init', 'incoming', 'pending', 'connecting', 'connected', 'missed', 'error', 'ended', 'rejected', 'paused']); connect.ContactStatusType = connect.ContactStateType; connect.CONTACT_ACTIVE_STATES = connect.makeEnum(["paused", 'incoming', 'pending', 'connecting', 'connected']); /*---------------------------------------------------------------- * enum ContactType */ connect.ContactType = connect.makeEnum(['voice', 'queue_callback', 'chat', 'task', 'email']); /*---------------------------------------------------------------- * enum ContactInitiationMethod */ connect.ContactInitiationMethod = connect.makeEnum(['inbound', 'outbound', 'transfer', 'queue_transfer', 'callback', 'api', 'disconnect', 'webrtc_api', 'agent_reply']); /*---------------------------------------------------------------- * enum for MonitoringMode */ connect.MonitoringMode = connect.makeEnum(['SILENT_MONITOR', 'BARGE']); /*---------------------------------------------------------------- * enum for MonitoringErrorTypes */ connect.MonitoringErrorTypes = connect.makeEnum(['invalid_target_state']); /*---------------------------------------------------------------- * enum ChannelType */ connect.ChannelType = connect.makeEnum(['VOICE', 'CHAT', 'TASK']); /*---------------------------------------------------------------- * enum MediaType */ connect.MediaType = connect.makeEnum(['softphone', 'chat', 'task', 'email']); /*---------------------------------------------------------------- * enum SoftphoneCallType */ connect.SoftphoneCallType = connect.makeEnum(['audio_video', 'video_only', 'audio_only', 'none']); /*---------------------------------------------------------------- * enum for SoftphoneErrorTypes */ connect.SoftphoneErrorTypes = connect.makeEnum(['unsupported_browser', 'microphone_not_shared', 'signalling_handshake_failure', 'signalling_connection_failure', 'ice_collection_timeout', 'user_busy_error', 'webrtc_error', 'realtime_communication_error', 'vdi_strategy_not_supported', 'vdi_redir_not_supported', 'other']); /*---------------------------------------------------------------- * enum for ClickType */ connect.ClickType = connect.makeEnum(['Accept', 'Reject', 'Hangup']); /*---------------------------------------------------------------- * enum for VoiceIdErrorTypes */ connect.VoiceIdErrorTypes = connect.makeEnum(['no_speaker_id_found', 'speaker_id_not_enrolled', 'get_speaker_id_failed', 'get_speaker_status_failed', 'opt_out_speaker_failed', 'opt_out_speaker_in_lcms_failed', 'delete_speaker_failed', 'start_session_failed', 'evaluate_speaker_failed', 'session_not_exists', 'describe_session_failed', 'enroll_speaker_failed', 'update_speaker_id_failed', 'update_speaker_id_in_lcms_failed', 'not_supported_on_conference_calls', 'enroll_speaker_timeout', 'evaluate_speaker_timeout', 'get_domain_id_failed', 'no_domain_id_found']); /*---------------------------------------------------------------- * enum for CTI exceptions */ connect.CTIExceptions = connect.makeEnum(["AccessDeniedException", "InvalidStateException", "BadEndpointException", "InvalidAgentARNException", "InvalidConfigurationException", "InvalidContactTypeException", "PaginationException", "RefreshTokenExpiredException", "SendDataFailedException", "UnauthorizedException", "QuotaExceededException"]); /*---------------------------------------------------------------- * enum for VoiceId streaming status */ connect.VoiceIdStreamingStatus = connect.makeEnum(["ONGOING", "ENDED", "PENDING_CONFIGURATION"]); /*---------------------------------------------------------------- * enum for VoiceId authentication decision */ connect.VoiceIdAuthenticationDecision = connect.makeEnum(["ACCEPT", "REJECT", "NOT_ENOUGH_SPEECH", "SPEAKER_NOT_ENROLLED", "SPEAKER_OPTED_OUT", "SPEAKER_ID_NOT_PROVIDED", "SPEAKER_EXPIRED"]); /*---------------------------------------------------------------- * enum for VoiceId fraud detection decision */ connect.VoiceIdFraudDetectionDecision = connect.makeEnum(["NOT_ENOUGH_SPEECH", "HIGH_RISK", "LOW_RISK"]); /*---------------------------------------------------------------- * enum for contact flow authentication decision */ connect.ContactFlowAuthenticationDecision = connect.makeEnum(["Authenticated", "NotAuthenticated", "Inconclusive", "NotEnrolled", "OptedOut", "NotEnabled", "Error"]); /*---------------------------------------------------------------- * enum for contact flow fraud detection decision */ connect.ContactFlowFraudDetectionDecision = connect.makeEnum(["HighRisk", "LowRisk", "Inconclusive", "NotEnabled", "Error"]); /*---------------------------------------------------------------- * enum for contact flow authentication decision */ connect.CustomerAuthenticationStatus = connect.makeEnum(["AUTHENTICATED", "FAILED", "TIMEOUT"]); /*---------------------------------------------------------------- * enum for Video Capability */ connect.VideoCapability = connect.makeEnum(["SEND"]); /*---------------------------------------------------------------- * enum for Screen Share Capability */ connect.ScreenShareCapability = connect.makeEnum(["SEND"]); /*---------------------------------------------------------------- * enum for VoiceId EnrollmentRequest Status */ connect.VoiceIdEnrollmentRequestStatus = connect.makeEnum(["NOT_ENOUGH_SPEECH", "IN_PROGRESS", "COMPLETED", "FAILED"]); /*---------------------------------------------------------------- * enum for VoiceId Speaker status */ connect.VoiceIdSpeakerStatus = connect.makeEnum(["OPTED_OUT", "ENROLLED", "PENDING"]); connect.VoiceIdConstants = { EVALUATE_SESSION_DELAY: 10000, EVALUATION_MAX_POLL_TIMES: 24, // EvaluateSpeaker is Polling for maximum 2 mins. EVALUATION_POLLING_INTERVAL: 5000, ENROLLMENT_MAX_POLL_TIMES: 120, // EnrollmentSpeaker is Polling for maximum 10 mins. ENROLLMENT_POLLING_INTERVAL: 5000, START_SESSION_DELAY: 8000 }; /*---------------------------------------------------------------- * constants for AgentPermissions */ connect.AgentPermissions = { OUTBOUND_CALL: 'outboundCall', VOICE_ID: 'voiceId' }; /*---------------------------------------------------------------- * Quick Responses APIs (utilizes public api proxy -- No shared worker involvement) */ var QuickResponses = /*#__PURE__*/_createClass(function QuickResponses() { _classCallCheck(this, QuickResponses); }); _defineProperty(QuickResponses, "isEnabled", function () { var client = connect.isCRM() ? connect.core.getClient() : connect.core.getApiProxyClient(); return new Promise(function (resolve, reject) { client.call(connect.ApiProxyClientMethods.QR_INTEGRATION_EXISTS, null, { success: function success(data) { connect.getLog().info("Quick Responses isEnabled succeeded").withObject(data).sendInternalLogToServer(); resolve(data); }, failure: function failure(err) { connect.getLog().error("Quick Responses isEnabled failed").withException(err).sendInternalLogToServer(); reject(err); } }); }); }); _defineProperty(QuickResponses, "searchQuickResponses", function (params) { var client = connect.isCRM() ? connect.core.getClient() : connect.core.getApiProxyClient(); var attributes = params !== null && params !== void 0 && params.contactId ? new Contact(params.contactId).getAttributes() : undefined; return new Promise(function (resolve, reject) { client.call(connect.ApiProxyClientMethods.QR_SEARCH_QUICK_RESPONSES, _objectSpread(_objectSpread({}, params), {}, { attributes: attributes }), { success: function success(data) { connect.getLog().info("searchQuickResponses succeeded").withObject(data).sendInternalLogToServer(); resolve(data); }, failure: function failure(err) { connect.getLog().error("searchQuickResponses failed").withException(err).sendInternalLogToServer(); reject(err); } }); }); }); ; /*---------------------------------------------------------------- * class Agent */ var Agent = function Agent() { if (!connect.agent.initialized) { throw new connect.StateError("The agent is not yet initialized!"); } }; Agent.prototype._getData = function () { return connect.core.getAgentDataProvider().getAgentData(); }; Agent.prototype._createContactAPI = function (contactData) { return new connect.Contact(contactData.contactId); }; Agent.prototype.onRefresh = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.REFRESH, f); }; Agent.prototype.onRoutable = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.ROUTABLE, f); }; Agent.prototype.onNotRoutable = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.NOT_ROUTABLE, f); }; Agent.prototype.onOffline = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.OFFLINE, f); }; Agent.prototype.onError = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.ERROR, f); }; Agent.prototype.onSoftphoneError = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.SOFTPHONE_ERROR, f); }; Agent.prototype.onWebSocketConnectionLost = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, f); }; Agent.prototype.onWebSocketConnectionGained = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED, f); }; Agent.prototype.onAfterCallWork = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.ACW, f); }; Agent.prototype.onStateChange = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.STATE_CHANGE, f); }; Agent.prototype.onMuteToggle = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.MUTE_TOGGLE, f); }; Agent.prototype.onLocalMediaStreamCreated = function (f) { return connect.core.getEventBus().subscribe(connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, f); }; Agent.prototype.onSpeakerDeviceChanged = function (f) { return connect.core.getEventBus().subscribe(connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, f); }; Agent.prototype.onMicrophoneDeviceChanged = function (f) { return connect.core.getEventBus().subscribe(connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, f); }; Agent.prototype.onRingerDeviceChanged = function (f) { return connect.core.getEventBus().subscribe(connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, f); }; Agent.prototype.onCameraDeviceChanged = function (f) { return connect.core.getEventBus().subscribe(connect.ConfigurationEvents.CAMERA_DEVICE_CHANGED, f); }; Agent.prototype.onBackgroundBlurChanged = function (f) { return connect.core.getEventBus().subscribe(connect.ConfigurationEvents.BACKGROUND_BLUR_CHANGED, f); }; Agent.prototype.mute = function () { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.MUTE, data: { mute: true } }); }; Agent.prototype.unmute = function () { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.MUTE, data: { mute: false } }); }; Agent.prototype.setSpeakerDevice = function (deviceId) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.SET_SPEAKER_DEVICE, data: { deviceId: deviceId } }); }; Agent.prototype.setMicrophoneDevice = function (deviceId) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, data: { deviceId: deviceId } }); }; Agent.prototype.setRingerDevice = function (deviceId) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.SET_RINGER_DEVICE, data: { deviceId: deviceId } }); }; // Only send event CAMERA_DEVICE_CHANGED because we do not handle video streams in StreamJS Agent.prototype.setCameraDevice = function (deviceId) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.CAMERA_DEVICE_CHANGED, data: { deviceId: deviceId } }); }; Agent.prototype.setBackgroundBlur = function (isBackgroundBlurEnabled) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.BACKGROUND_BLUR_CHANGED, data: { isBackgroundBlurEnabled: isBackgroundBlurEnabled } }); }; /** * @deprecated * use agent.getAvailabilityState */ Agent.prototype.getState = function () { return this._getData().snapshot.state; }; Agent.prototype.getNextState = function () { return this._getData().snapshot.nextState; }; Agent.prototype.getAvailabilityState = function () { return this._getData().snapshot.agentAvailabilityState; }; /** * @deprecated * use agent.getAvailabilityState */ Agent.prototype.getStatus = Agent.prototype.getState; Agent.prototype.getStateDuration = function () { return connect.now() - this._getData().snapshot.state.startTimestamp.getTime() + connect.core.getSkew(); }; Agent.prototype.getStatusDuration = Agent.prototype.getStateDuration; Agent.prototype.getPermissions = function () { return this.getConfiguration().permissions; }; Agent.prototype.getContacts = function (contactTypeFilter) { var self = this; return this._getData().snapshot.contacts.map(function (contactData) { return self._createContactAPI(contactData); }).filter(function (contact) { return !contactTypeFilter || contact.getType() === contactTypeFilter; }); }; Agent.prototype.getConfiguration = function () { return this._getData().configuration; }; Agent.prototype.getAgentStates = function () { return this.getConfiguration().agentStates; }; Agent.prototype.getRoutingProfile = function () { return this.getConfiguration().routingProfile; }; Agent.prototype.getChannelConcurrency = function (channel) { var channelConcurrencyMap = this.getRoutingProfile().channelConcurrencyMap; if (!channelConcurrencyMap) { channelConcurrencyMap = Object.keys(connect.ChannelType).reduce(function (acc, key) { // Exclude TASK from default concurrency. if (key !== 'TASK') { acc[connect.ChannelType[key]] = 1; } return acc; }, {}); } return channel ? channelConcurrencyMap[channel] || 0 : channelConcurrencyMap; }; Agent.prototype.getName = function () { return this.getConfiguration().name; }; Agent.prototype.getAgentARN = function () { return this.getConfiguration().agentARN; }; Agent.prototype.getExtension = function () { return this.getConfiguration().extension; }; Agent.prototype.getDialableCountries = function () { return this.getConfiguration().dialableCountries; }; Agent.prototype.isSoftphoneEnabled = function () { return this.getConfiguration().softphoneEnabled; }; Agent.prototype.setConfiguration = function (configuration, callbacks) { var client = connect.core.getClient(); if (configuration && configuration.agentPreferences && configuration.agentPreferences.LANGUAGE && !configuration.agentPreferences.locale) { // workaround for the inconsistency issue that getAgentConfiguration returns agentPreferences.LANGUAGE but updateAgentConfiguration expects agentPreferences.locale to be set. configuration.agentPreferences.locale = configuration.agentPreferences.LANGUAGE; } if (configuration && configuration.agentPreferences && !connect.isValidLocale(configuration.agentPreferences.locale)) { if (callbacks && callbacks.failure) { callbacks.failure(connect.AgentErrorStates.INVALID_LOCALE); } } else { client.call(connect.ClientMethods.UPDATE_AGENT_CONFIGURATION, { configuration: connect.assertNotNull(configuration, 'configuration') }, { success: function success(data) { // We need to ask the shared worker to reload agent config // once we change it so every tab has accurate config. var conduit = connect.core.getUpstream(); conduit.sendUpstream(connect.EventType.RELOAD_AGENT_CONFIGURATION); if (callbacks.success) { callbacks.success(data); } }, failure: callbacks && callbacks.failure }); } }; Agent.prototype.setState = function (state, callbacks, options) { var client = connect.core.getClient(); client.call(connect.ClientMethods.PUT_AGENT_STATE, { state: connect.assertNotNull(state, 'state'), enqueueNextState: options && !!options.enqueueNextState }, callbacks); }; Agent.prototype.onEnqueuedNextState = function (f) { var bus = connect.core.getEventBus(); return bus.subscribe(connect.AgentEvents.ENQUEUED_NEXT_STATE, f); }; Agent.prototype.setStatus = Agent.prototype.setState; Agent.prototype.connect = function (endpointIn, params) { var client = connect.core.getClient(); var endpoint = new connect.Endpoint(endpointIn); // Have to remove the endpointId field or AWS JS SDK gets mad. delete endpoint.endpointId; var callParams = { endpoint: connect.assertNotNull(endpoint, 'endpoint'), queueARN: params && (params.queueARN || params.queueId) || this.getRoutingProfile().defaultOutboundQueue.queueARN }; if (params && params.relatedContactId && params.relatedContactId !== null) { callParams.relatedContactId = params.relatedContactId; if (params.previousContactId) { delete callParams.previousContactId; } } client.call(connect.ClientMethods.CREATE_OUTBOUND_CONTACT, callParams, params && { success: params.success, failure: params.failure }); }; Agent.prototype.getAllQueueARNs = function () { return this.getConfiguration().routingProfile.queues.map(function (queue) { return queue.queueARN; }); }; Agent.prototype.getEndpoints = function (queueARNs, callbacks, pageInfoIn) { var self = this; var client = connect.core.getClient(); connect.assertNotNull(callbacks, "callbacks"); connect.assertNotNull(callbacks.success, "callbacks.success"); var pageInfo = pageInfoIn || {}; pageInfo.endpoints = pageInfo.endpoints || []; pageInfo.maxResults = pageInfo.maxResults || connect.DEFAULT_BATCH_SIZE; // Backwards compatibility allowing a single queueARN to be specified // instead of an array. if (!connect.isArray(queueARNs)) { queueARNs = [queueARNs]; } client.call(connect.ClientMethods.GET_ENDPOINTS, { queueARNs: queueARNs, nextToken: pageInfo.nextToken || null, maxResults: pageInfo.maxResults }, { success: function success(data) { if (data.nextToken) { self.getEndpoints(queueARNs, callbacks, { nextToken: data.nextToken, maxResults: pageInfo.maxResults, endpoints: pageInfo.endpoints.concat(data.endpoints) }); } else { pageInfo.endpoints = pageInfo.endpoints.concat(data.endpoints); var endpoints = pageInfo.endpoints.map(function (endpoint) { return new connect.Endpoint(endpoint); }); callbacks.success({ endpoints: endpoints, addresses: endpoints }); } }, failure: callbacks.failure }); }; Agent.prototype.getAddresses = Agent.prototype.getEndpoints; //Internal identifier. Agent.prototype._getResourceId = function () { var queueArns = this.getAllQueueARNs(); var _iterator = _createForOfIteratorHelper(queueArns), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var queueArn = _step.value; var agentIdMatch = queueArn.match(/\/agent\/([^/]+)/); if (agentIdMatch) { return agentIdMatch[1]; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ", queueArns); }; Agent.prototype.toSnapshot = function () { return new connect.AgentSnapshot(this._getData()); }; /*---------------------------------------------------------------- * class AgentSnapshot */ var AgentSnapshot = function AgentSnapshot(agentData) { connect.Agent.call(this); this.agentData = agentData; }; AgentSnapshot.prototype = Object.create(Agent.prototype); AgentSnapshot.prototype.constructor = AgentSnapshot; AgentSnapshot.prototype._getData = function () { return this.agentData; }; AgentSnapshot.prototype._createContactAPI = function (contactData) { return new connect.ContactSnapshot(contactData); }; /*---------------------------------------------------------------- * class Contact */ var Contact = function Contact(contactId) { this.contactId = contactId; }; Contact.prototype._getSDKClient = function () { if (this.contactClient) { return this.contactClient; } try { var _connect$core, _connect$core2, _connect$core3; var providerData = { providerId: (_connect$core = connect.core) === null || _connect$core === void 0 || (_connect$core = _connect$core._amazonConnectProviderData) === null || _connect$core === void 0 || (_connect$core = _connect$core.provider) === null || _connect$core === void 0 ? void 0 : _connect$core.id, config: (_connect$core2 = connect.core) === null || _connect$core2 === void 0 || (_connect$core2 = _connect$core2._amazonConnectProviderData) === null || _connect$core2 === void 0 || (_connect$core2 = _connect$core2.provider) === null || _connect$core2 === void 0 ? void 0 : _connect$core2.config, isStreamsProvider: (_connect$core3 = connect.core) === null || _connect$core3 === void 0 || (_connect$core3 = _connect$core3._amazonConnectProviderData) === null || _connect$core3 === void 0 ? void 0 : _connect$core3.isStreamsProvider }; connect.getLog().info('Initializing Contact SDK Clients').withObject(providerData).sendInternalLogToServer(); this.contactClient = new ContactClient(connect.core.getSDKClientConfig()); return this.contactClient; } catch (e) { var _connect$core4, _connect$core5, _connect$core6; var errorData = { providerId: (_connect$core4 = connect.core) === null || _connect$core4 === void 0 || (_connect$core4 = _connect$core4._amazonConnectProviderData) === null || _connect$core4 === void 0 || (_connect$core4 = _connect$core4.provider) === null || _connect$core4 === void 0 ? void 0 : _connect$core4.id, config: (_connect$core5 = connect.core) === null || _connect$core5 === void 0 || (_connect$core5 = _connect$core5._amazonConnectProviderData) === null || _connect$core5 === void 0 || (_connect$core5 = _connect$core5.provider) === null || _connect$core5 === void 0 ? void 0 : _connect$core5.config, isStreamsProvider: (_connect$core6 = connect.core) === null || _connect$core6 === void 0 || (_connect$core6 = _connect$core6._amazonConnectProviderData) === null || _connect$core6 === void 0 ? void 0 : _connect$core6.isStreamsProvider, error: e }; connect.getLog().error('Failed to initialize Contact SDK Clients').withObject(errorData).sendInternalLogToServer(); } }; Contact.prototype._getData = function () { return connect.core.getAgentDataProvider().getContactData(this.getContactId()); }; Contact.prototype._createConnectionAPI = function (connectionData) { if (this.getType() === connect.ContactType.CHAT) { return new connect.ChatConnection(this.contactId, connectionData.connectionId); } else if (this.getType() === connect.ContactType.TASK) { return new connect.TaskConnection(this.contactId, connectionData.connectionId); } else if (this.getType() === connect.ContactType.EMAIL) { return new connect.EmailConnection(this.contactId, connectionData.connectionId); } else { return new connect.VoiceConnection(this.contactId, connectionData.connectionId); } }; Contact.prototype.getEventName = function (eventName) { return connect.core.getContactEventName(eventName, this.getContactId()); }; Contact.prototype.onRefresh = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.REFRESH), f); }; Contact.prototype.onIncoming = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.INCOMING), f); }; Contact.prototype.onConnecting = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.CONNECTING), f); }; Contact.prototype.onPending = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.PENDING), f); }; Contact.prototype.onAccepted = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.ACCEPTED), f); }; Contact.prototype.onMissed = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.MISSED), f); }; Contact.prototype.onEnded = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.ENDED), f); }; Contact.prototype.onDestroy = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.DESTROYED), f); }; Contact.prototype.onACW = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.ACW), f); }; Contact.prototype.onConnected = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.CONNECTED), f); }; Contact.prototype.onError = function (f) { return connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.ERROR), f); }; Contact.prototype.getContactId = function () { return this.contactId; }; Contact.prototype.getOriginalContactId = function () { return this._getData().initialContactId; }; Contact.prototype.getInitialContactId = Contact.prototype.getOriginalContactId; Contact.prototype.getType = function () { return this._getData().type; }; Contact.prototype.getContactDuration = function () { return this._getData().contactDuration; }; Contact.prototype.engagePreviewContact = function () { var contactClient = this._getSDKClient(); var contactId = this.getContactId(); return contactClient.engagePreviewContact(contactId); }; Contact.prototype.getPreviewConfiguration = function () { var contactClient = this._getSDKClient(); var contactId = this.getContactId(); return contactClient.getPreviewConfiguration(contactId); }; Contact.prototype.isPreviewMode = function () { var contactClient = this._getSDKClient(); var contactId = this.getContactId(); return contactClient.isPreviewMode(contactId); }; Contact.prototype.getState = function () { return this._getData().state; }; Contact.prototype.getStatus = Contact.prototype.getState; Contact.prototype.getStateDuration = function () { return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew(); }; Contact.prototype.getStatusDuration = Contact.prototype.getStateDuration; Contact.prototype.getQueue = function () { return this._getData().queue; }; Contact.prototype.getQueueTimestamp = function () { return this._getData().queueTimestamp; }; Contact.prototype.getConnections = function () { var self = this; return this._getData().connections.map(function (connData) { if (self.getType() === connect.ContactType.CHAT) { return new connect.ChatConnection(self.contactId, connData.connectionId); } else if (self.getType() === connect.ContactType.TASK) { return new connect.TaskConnection(self.contactId, connData.connectionId); } else if (self.getType() === connect.ContactType.EMAIL) { return new connect.EmailConnection(self.contactId, connData.connectionId); } else { return new connect.VoiceConnection(self.contactId, connData.connectionId); } }); }; Contact.prototype.getInitialConnection = function () { return connect.find(this.getConnections(), function (conn) { return conn.isInitialConnection(); }) || null; }; Contact.prototype.getActiveInitialConnection = function () { var initialConn = this.getInitialConnection(); if (initialConn != null && initialConn.isActive()) { return initialConn; } else { return null; } }; Contact.prototype.getThirdPartyConnections = function () { return this.getConnections().filter(function (conn) { return !conn.isInitialConnection() && conn.getType() !== connect.ConnectionType.AGENT; }); }; Contact.prototype.getSingleActiveThirdPartyConnection = function () { return this.getThirdPartyConnections().filter(function (conn) { return conn.isActive(); })[0] || null; }; Contact.prototype.getAgentConnection = function () { return connect.find(this.getConnections(), function (conn) { var connType = conn.getType(); return connType === connect.ConnectionType.AGENT || connType === connect.ConnectionType.MONITORING; }); }; Contact.prototype.getActiveConnections = function () { return this.getConnections().filter(function (conn) { return conn.isActive(); }); }; Contact.prototype.hasTwoActiveParticipants = function () { return this.getActiveConnections().length === 2; }; Contact.prototype.getName = function () { return this._getData().name; }; Contact.prototype.getInitiationMethod = function () { return this._getData().initiationMethod; }; Contact.prototype.getContactMetadata = function () { return this._getData().contactMetadata; }; Contact.prototype.getDescription = function () { return this._getData().description; }; Contact.prototype.getRelatedContactId = function () { return this._getData().relatedContactId; }; Contact.prototype.getContactAssociationId = function () { return this._getData().contactAssociationId; }; Contact.prototype.getCustomerEndpoint = function () { return this._getData().customerEndpoint; }; Contact.prototype.getConnectSystemEndpoint = function () { return this._getData().connectSystemEndpoint; }; Contact.prototype.getReferences = function () { return this._getData().references; }; Contact.prototype.getAttributes = function () { return this._getData().attributes; }; Contact.prototype.getContactFeatures = function () { return this._getData().contactFeatures; }; Contact.prototype.getChannelContext = function () { return this._getData().channelContext; }; Contact.prototype.getSegmentAttributes = function () { return this._getData().segmentAttributes; }; Contact.prototype.getContactSubtype = function () { var segmentAttributes = this.getSegmentAttributes(); return segmentAttributes && segmentAttributes["connect:Subtype"] ? segmentAttributes["connect:Subtype"].ValueString : null; }; Contact.prototype.isSoftphoneCall = function () { if (this.getType() !== connect.ContactType.VOICE && this.getType() !== connect.ContactType.QUEUE_CALLBACK) { return false; } return Boolean(this.getConnections().find(function (conn) { return conn.getSoftphoneMediaInfo(); })); }; Contact.prototype.hasVideoRTCCapabilities = function () { return connect.find(this.getConnections(), function (conn) { return conn.canSendVideo && conn.canSendVideo(); }) !== null; }; Contact.prototype.canAgentSendVideo = function () { var agentConnection = this.getAgentConnection(); return agentConnection.canSendVideo && agentConnection.canSendVideo(); }; Contact.prototype.canAgentReceiveVideo = function () { var initialConn = this.getInitialConnection(); // If customer has SEND capability, then agent can receive video if (initialConn.canSendVideo && initialConn.canSendVideo()) { return true; } // If customer does not have SEND capability, right now we do not populate SEND capability in third party connection // so if customer does not have SEND capability then use agent SEND capability to determine that agent can // receive videos from other parties (other agents, superiors). var thirdPartyConns = this.getThirdPartyConnections(); return thirdPartyConns && thirdPartyConns.length > 0 && this.canAgentSendVideo(); }; Contact.prototype.hasScreenShareCapability = function () { return connect.find(this.getConnections(), function (conn) { return conn.canSendScreenShare && conn.canSendScreenShare(); }) !== null; }; Contact.prototype.canAgentSendScreenShare = function () { var agentConnection = this.getAgentConnection(); return agentConnection.canSendScreenShare && agentConnection.canSendScreenShare(); }; Contact.prototype.canCustomerSendScreenShare = function () { var initialConn = this.getInitialConnection(); return initialConn.canSendScreenShare && initialConn.canSendScreenShare(); }; Contact.prototype.startScreenSharing = /*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(skipSessionInitiation) { var contactId, client, body; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: contactId = this.getContactId(); if (!(this.getContactSubtype() !== "connect:WebRTC")) { _context.next = 3; break; } throw new Error("Screen sharing is only supported for WebRTC contacts."); case 3: if (this.isConnected()) { _context.next = 5; break; } throw new connect.StateError('Contact %s is not connected.', contactId); case 5: if (skipSessionInitiation) { _context.next = 11; break; } client = connect.isCRM() ? connect.core.getClient() : connect.core.getApiProxyClient(); body = { "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), "ContactId": contactId, "ParticipantId": this.getAgentConnection().getConnectionId() }; return _context.abrupt("return", new Promise(function (resolve, reject) { client.call(connect.ApiProxyClientMethods.START_SCREEN_SHARING, body, { success: function success(data) { connect.getLog().info("startScreenSharing succeeded").withObject(data).sendInternalLogToServer(); connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ContactEvents.SCREEN_SHARING_STARTED, data: { contactId: contactId } }); resolve(data); }, failure: function failure(err) { connect.getLog().error("startScreenSharing failed").withException(err).sendInternalLogToServer(); connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ContactEvents.SCREEN_SHARING_ERROR, data: { contactId: contactId } }); reject(err); } }); })); case 11: connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ContactEvents.SCREEN_SHARING_STARTED, data: { contactId: contactId } }); case 12: case "end": return _context.stop(); } }, _callee, this); })); return function (_x) { return _ref.apply(this, arguments); }; }(); Contact.prototype.onScreenSharingStarted = function (f) { return connect.core.getEventBus().subscribe(connect.ContactEvents.SCREEN_SHARING_STARTED, f); }; Contact.prototype.stopScreenSharing = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { var contactId; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: contactId = this.getContactId(); if (!(this.getContactSubtype() !== "connect:WebRTC")) { _context2.next = 3; break; } throw new Error("Screen sharing is only supported for WebRTC contacts."); case 3: if (this.isConnected()) { _context2.next = 5; break; } throw new connect.StateError('Contact %s is not connected.', contactId); case 5: connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ContactEvents.SCREEN_SHARING_STOPPED, data: { contactId: contactId } }); case 6: case "end": return _context2.stop(); } }, _callee2, this); })); Contact.prototype.onScreenSharingStopped = function (f) { return connect.core.getEventBus().subscribe(connect.ContactEvents.SCREEN_SHARING_STOPPED, f); }; Contact.prototype.onScreenSharingError = function (f) { return connect.core.getEventBus().subscribe(connect.ContactEvents.SCREEN_SHARING_ERROR, f); }; Contact.prototype._isInbound = function () { var initiationMethod = this._getData().initiationMethod; return initiationMethod === connect.ContactInitiationMethod.OUTBOUND ? false : true; }; Contact.prototype.isInbound = function () { var conn = this.getInitialConnection(); // We will gradually change checking inbound by relying on contact initiationMethod if ([connect.MediaType.TASK, connect.MediaType.EMAIL].includes(conn.getMediaType())) { return this._isInbound(); } return conn ? conn.getType() === connect.ConnectionType.INBOUND : false; }; Contact.prototype.isConnected = function () { return this.getStatus().type === connect.ContactStateType.CONNECTED; }; Contact.prototype.accept = function (callbacks) { var client = connect.core.getClient(); var self = this; var contactId = this.getContactId(); connect.publishClickStreamData({ contactId: this.getContactId(), clickType: connect.ClickType.ACCEPT, clickTime: new Date().toISOString() }); client.call(connect.ClientMethods.ACCEPT_CONTACT, { contactId: contactId }, { success: function success(data) { var conduit = connect.core.getUpstream(); conduit.sendUpstream(connect.EventType.BROADCAST, { event: connect.ContactEvents.ACCEPTED, data: new connect.Contact(contactId) }); conduit.sendUpstream(connect.EventType.BROADCAST, { event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, self.getContactId()), data: new connect.Contact(contactId) }); // In Firefox, there's a browser restriction that an unfocused browser tab is not allowed to access the user's microphone. // The problem is that the restriction could cause a webrtc session creation timeout error when you get an incoming call while you are not on the primary tab. // It was hard to workaround the issue especially when you have multiple tabs open because you needed to find the right tab and accept the contact before the timeout. // To avoid the error, when multiple tabs are open in Firefox, a webrtc session is not immediately created as an incoming softphone contact is detected. // Instead, it waits until contact.accept() is called on a tab and lets the tab become the new primary tab and start the web rtc session there // because the tab should be focused at the moment and have access to the user's microphone. var contact = new connect.Contact(contactId); if (connect.isFirefoxBrowser() && contact.isSoftphoneCall()) { connect.core.triggerReadyToStartSessionEvent(); } if (callbacks && callbacks.success) { callbacks.success(data); } }, failure: function failure(err, data) { connect.getLog().error("Accept Contact failed").sendInternalLogToServer().withException(err).withObject({ data: data }); connect.publishMetric({ name: "ContactAcceptFailure", data: { count: 1 } }); if (callbacks && callbacks.failure) { callbacks.failure(connect.ContactStateType.ERROR); } } }); }; Contact.prototype.destroy = function () { connect.getLog().warn("contact.destroy() has been deprecated."); }; Contact.prototype.reject = function (callbacks) { var client = connect.core.getClient(); connect.publishClickStreamData({ contactId: this.getContactId(), clickType: connect.ClickType.REJECT, clickTime: new Date().toISOString() }); client.call(connect.ClientMethods.REJECT_CONTACT, { contactId: this.getContactId() }, callbacks); }; Contact.prototype.complete = function (callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.COMPLETE_CONTACT, { contactId: this.getContactId() }, callbacks); }; Contact.prototype.clear = function (callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.CLEAR_CONTACT, { contactId: this.getContactId() }, callbacks); }; Contact.prototype.notifyIssue = function (issueCode, description, callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.NOTIFY_CONTACT_ISSUE, { contactId: this.getContactId(), issueCode: issueCode, description: description }, callbacks); }; Contact.prototype.addConnection = function (endpointIn, callbacks) { var client = connect.core.getClient(); var endpoint = new connect.Endpoint(endpointIn); // Have to remove the endpointId field or AWS JS SDK gets mad. delete endpoint.endpointId; client.call(connect.ClientMethods.CREATE_ADDITIONAL_CONNECTION, { contactId: this.getContactId(), endpoint: endpoint }, callbacks); }; Contact.prototype.toggleActiveConnections = function (callbacks) { var client = connect.core.getClient(); var connectionId = null; var holdingConn = connect.find(this.getConnections(), function (conn) { return conn.getStatus().type === connect.ConnectionStateType.HOLD; }); if (holdingConn != null) { connectionId = holdingConn.getConnectionId(); } else { var activeConns = this.getConnections().filter(function (conn) { return conn.isActive(); }); if (activeConns.length > 0) { connectionId = activeConns[0].getConnectionId(); } } client.call(connect.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS, { contactId: this.getContactId(), connectionId: connectionId }, callbacks); }; Contact.prototype.sendSoftphoneMetrics = function (softphoneStreamStatistics, callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS, { contactId: this.getContactId(), ccpVersion: global.ccpVersion, softphoneStreamStatistics: softphoneStreamStatistics }, callbacks); connect.publishSoftphoneStats({ contactId: this.getContactId(), ccpVersion: global.ccpVersion, stats: softphoneStreamStatistics }); }; Contact.prototype.sendSoftphoneReport = function (report, callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT, { contactId: this.getContactId(), ccpVersion: global.ccpVersion, report: report }, callbacks); }; Contact.prototype.conferenceConnections = function (callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.CONFERENCE_CONNECTIONS, { contactId: this.getContactId() }, callbacks); }; Contact.prototype.toSnapshot = function () { return new connect.ContactSnapshot(this._getData()); }; Contact.prototype.isMultiPartyConferenceEnabled = function () { var contactFeatures = this.getContactFeatures(); return !!(contactFeatures && contactFeatures.multiPartyConferenceEnabled); }; Contact.prototype.updateMonitorParticipantState = function (targetState, callbacks) { if (!targetState || !Object.values(connect.MonitoringMode).includes(targetState.toUpperCase())) { connect.getLog().error("Invalid target state was provided: ".concat(targetState)).sendInternalLogToServer(); if (callbacks && callbacks.failure) { callbacks.failure(connect.MonitoringErrorTypes.INVALID_TARGET_STATE); } } else { var client = connect.core.getClient(); client.call(connect.ClientMethods.UPDATE_MONITOR_PARTICIPANT_STATE, { contactId: this.getContactId(), targetMonitorMode: targetState.toUpperCase() }, callbacks); } }; Contact.prototype.isUnderSupervision = function () { var nonAgentConnections = this.getConnections().filter(function (conn) { return conn.getType() !== connect.ConnectionType.AGENT; }); var supervisorConnection = nonAgentConnections && nonAgentConnections.find(function (conn) { return conn.isBarge() && conn.isActive(); }); return supervisorConnection !== undefined; }; Contact.prototype.silentMonitor = function (callbacks) { return this.updateMonitorParticipantState(connect.MonitoringMode.SILENT_MONITOR, callbacks); }; Contact.prototype.bargeIn = function (callbacks) { return this.updateMonitorParticipantState(connect.MonitoringMode.BARGE, callbacks); }; Contact.prototype.pause = function (callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.PAUSE_CONTACT, { contactId: this.getContactId() }, callbacks); }; Contact.prototype.resume = function (callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.RESUME_CONTACT, { contactId: this.getContactId() }, callbacks); }; Contact.prototype.addParticipant = function (endpointIn, options) { var client = connect.core.getClient(); var endpoint = new connect.Endpoint(endpointIn); // endpointId is not defined in the API model, adding it will cause the API to reject delete endpoint.endpointId; client.call(connect.ClientMethods.ADD_NEW_CONNECTION, { contactId: this.getContactId(), endpoint: endpoint }, options); }; Contact.prototype.transfer = function (endpointIn, options) { var client = connect.core.getClient(); var endpoint = new connect.Endpoint(endpointIn); // endpointId is not defined in the API model, adding it will cause the API to reject delete endpoint.endpointId; client.call(connect.ClientMethods.TRANSFER_CONTACT, { contactId: this.getContactId(), endpoint: endpoint }, options); }; /*---------------------------------------------------------------- * class ContactSnapshot */ var ContactSnapshot = function ContactSnapshot(contactData) { connect.Contact.call(this, contactData.contactId); this.contactData = contactData; }; ContactSnapshot.prototype = Object.create(Contact.prototype); ContactSnapshot.prototype.constructor = ContactSnapshot; ContactSnapshot.prototype._getData = function () { return this.contactData; }; ContactSnapshot.prototype._createConnectionAPI = function (connectionData) { return new connect.ConnectionSnapshot(connectionData); }; /*---------------------------------------------------------------- * class Connection */ var Connection = function Connection(contactId, connectionId) { this.contactId = contactId; this.connectionId = connectionId; this._initMediaController(); }; Connection.prototype._getData = function () { return connect.core.getAgentDataProvider().getConnectionData(this.getContactId(), this.getConnectionId()); }; Connection.prototype.getContactId = function () { return this.contactId; }; Connection.prototype.getConnectionId = function () { return this.connectionId; }; Connection.prototype.getEndpoint = function () { return new connect.Endpoint(this._getData().endpoint); }; Connection.prototype.getAddress = Connection.prototype.getEndpoint; Connection.prototype.getState = function () { return this._getData().state; }; Connection.prototype.getStatus = Connection.prototype.getState; Connection.prototype.getStateDuration = function () { return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew(); }; Connection.prototype.getStatusDuration = Connection.prototype.getStateDuration; Connection.prototype.getType = function () { return this._getData().type; }; Connection.prototype.isInitialConnection = function () { return this._getData().initial; }; Connection.prototype.isActive = function () { return connect.contains(connect.CONNECTION_ACTIVE_STATES, this.getStatus().type); }; Connection.prototype.isConnected = function () { return connect.contains(connect.CONNECTION_CONNECTED_STATES, this.getStatus().type); }; Connection.prototype.isConnecting = function () { return this.getStatus().type === connect.ConnectionStateType.CONNECTING; }; Connection.prototype.isOnHold = function () { return this.getStatus().type === connect.ConnectionStateType.HOLD; }; Connection.prototype.getSoftphoneMediaInfo = function () { return this._getData().softphoneMediaInfo; }; /** * Gets the currently monitored contact info, Returns null if does not exists. * @return {{agentName:string, customerName:string, joinTime:Date}} */ Connection.prototype.getMonitorInfo = function () { return this._getData().monitoringInfo; }; Connection.prototype.destroy = function (callbacks) { connect.publishClickStreamData({ contactId: this.getContactId(), clickType: connect.ClickType.HANGUP, clickTime: new Date().toISOString() }); var client = connect.core.getClient(); client.call(connect.ClientMethods.DESTROY_CONNECTION, { contactId: this.getContactId(), connectionId: this.getConnectionId() }, callbacks); }; Connection.prototype.sendDigits = function (digits, callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.SEND_DIGITS, { contactId: this.getContactId(), connectionId: this.getConnectionId(), digits: digits }, callbacks); }; Connection.prototype.hold = function (callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.HOLD_CONNECTION, { contactId: this.getContactId(), connectionId: this.getConnectionId() }, callbacks); }; Connection.prototype.resume = function (callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.RESUME_CONNECTION, { contactId: this.getContactId(), connectionId: this.getConnectionId() }, callbacks); }; Connection.prototype.toSnapshot = function () { return new connect.ConnectionSnapshot(this._getData()); }; Connection.prototype._initMediaController = function () { if (this.getMediaInfo()) { connect.core.mediaFactory.get(this)["catch"](function () {}); } }; // Method for checking whether this connection is an agent-side connection // (type AGENT or MONITORING) Connection.prototype._isAgentConnectionType = function () { var connectionType = this.getType(); return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; }; /** * Utility method for checking whether this connection is an agent-side connection * (type AGENT or MONITORING) * @return {boolean} True if this connection is an agent-side connection. False otherwise. */ Connection.prototype._isAgentConnectionType = function () { var connectionType = this.getType(); return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; }; /*---------------------------------------------------------------- * Voice authenticator VoiceId */ var VoiceId = function VoiceId(contactId) { this.contactId = contactId; }; VoiceId.prototype.getSpeakerId = function () { var self = this; self.checkConferenceCall(); var client = connect.core.getClient(); return new Promise(function (resolve, reject) { var params = { "contactId": self.contactId, "instanceId": connect.core.getAgentDataProvider().getInstanceId(), "awsAccountId": connect.core.getAgentDataProvider().getAWSAccountId() }; connect.getLog().info("getSpeakerId called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.GET_CONTACT, params, { success: function success(data) { if (data.contactData.customerId) { var obj = { speakerId: data.contactData.customerId }; connect.getLog().info("getSpeakerId succeeded").withObject(data).sendInternalLogToServer(); resolve(obj); } else { var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND, "No speakerId assotiated with this call"); reject(error); } }, failure: function failure(err) { connect.getLog().error("Get SpeakerId failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED, "Get SpeakerId failed", err); reject(error); } }); }); }; VoiceId.prototype.getSpeakerStatus = function () { var self = this; self.checkConferenceCall(); var client = connect.core.getClient(); return new Promise(function (resolve, reject) { self.getSpeakerId().then(function (data) { self.getDomainId().then(function (domainId) { var params = { "SpeakerId": connect.assertNotNull(data.speakerId, 'speakerId'), "DomainId": domainId }; connect.getLog().info("getSpeakerStatus called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.DESCRIBE_SPEAKER, params, { success: function success(data) { connect.getLog().info("getSpeakerStatus succeeded").withObject(data).sendInternalLogToServer(); resolve(data); }, failure: function failure(err) { var error; var parsedErr = JSON.parse(err); switch (parsedErr.status) { case 400: case 404: var data = parsedErr; data.type = data.type ? data.type : connect.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED; connect.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(); resolve(data); break; default: connect.getLog().error("getSpeakerStatus failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED, "Get SpeakerStatus failed", err); reject(error); } } }); })["catch"](function (err) { reject(err); }); })["catch"](function (err) { reject(err); }); }); }; // internal only VoiceId.prototype._optOutSpeakerInLcms = function (speakerId, generatedSpeakerId) { var self = this; var client = connect.core.getClient(); return new Promise(function (resolve, reject) { var params = { "ContactId": self.contactId, "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), "VoiceIdResult": { "SpeakerOptedOut": true, "generatedSpeakerId": generatedSpeakerId } }; connect.getLog().info("_optOutSpeakerInLcms called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, params, { success: function success(data) { connect.getLog().info("optOutSpeakerInLcms succeeded").withObject(data).sendInternalLogToServer(); resolve(data); }, failure: function failure(err) { connect.getLog().error("optOutSpeakerInLcms failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED, "optOutSpeakerInLcms failed", err); reject(error); } }); }); }; VoiceId.prototype.optOutSpeaker = function () { var self = this; self.checkConferenceCall(); var client = connect.core.getClient(); return new Promise(function (resolve, reject) { self.getSpeakerId().then(function (data) { self.getDomainId().then(function (domainId) { var speakerId = data.speakerId; var params = { "SpeakerId": connect.assertNotNull(speakerId, 'speakerId'), "DomainId": domainId }; connect.getLog().info("optOutSpeaker called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.OPT_OUT_SPEAKER, params, { success: function success(data) { self._optOutSpeakerInLcms(speakerId, data.generatedSpeakerId)["catch"](function () {}); connect.getLog().info("optOutSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); }, failure: function failure(err) { connect.getLog().error("optOutSpeaker failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED, "optOutSpeaker failed.", err); reject(error); } }); })["catch"](function (err) { reject(err); }); })["catch"](function (err) { reject(err); }); }); }; VoiceId.prototype.deleteSpeaker = function () { var self = this; self.checkConferenceCall(); var client = connect.core.getClient(); return new Promise(function (resolve, reject) { self.getSpeakerId().then(function (data) { self.getDomainId().then(function (domainId) { var params = { "SpeakerId": connect.assertNotNull(data.speakerId, 'speakerId'), "DomainId": domainId }; connect.getLog().info("deleteSpeaker called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.DELETE_SPEAKER, params, { success: function success(data) { connect.getLog().info("deleteSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); }, failure: function failure(err) { connect.getLog().error("deleteSpeaker failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED, "deleteSpeaker failed.", err); reject(error); } }); })["catch"](function (err) { reject(err); }); })["catch"](function (err) { reject(err); }); }); }; VoiceId.prototype.startSession = function () { var self = this; self.checkConferenceCall(); var client = connect.core.getClient(); return new Promise(function (resolve, reject) { self.getDomainId().then(function (domainId) { var params = { "contactId": self.contactId, "instanceId": connect.core.getAgentDataProvider().getInstanceId(), "customerAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), "clientToken": AWS.util.uuid.v4(), "domainId": domainId }; connect.getLog().info("startSession called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.START_VOICE_ID_SESSION, params, { success: function success(data) { if (data.sessionId) { resolve(data); } else { connect.getLog().error("startVoiceIdSession failed, no session id returned").withObject({ data: data }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "No session id returned from start session api"); reject(error); } }, failure: function failure(err) { connect.getLog().error("startVoiceIdSession failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "startVoiceIdSession failed", err); reject(error); } }); })["catch"](function (err) { reject(err); }); }); }; VoiceId.prototype.evaluateSpeaker = function (startNew) { var self = this; self.checkConferenceCall(); var client = connect.core.getClient(); var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); var pollTimes = 0; return new Promise(function (resolve, reject) { function evaluate() { self.getDomainId().then(function (domainId) { var params = { "SessionNameOrId": contactData.initialContactId || this.contactId, "DomainId": domainId }; connect.getLog().info("evaluateSpeaker called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.EVALUATE_SESSION, params, { success: function success(data) { if (++pollTimes < connect.VoiceIdConstants.EVALUATION_MAX_POLL_TIMES) { if (data.StreamingStatus === connect.VoiceIdStreamingStatus.PENDING_CONFIGURATION) { setTimeout(evaluate, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); } else { if (!data.AuthenticationResult) { data.AuthenticationResult = {}; data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENABLED; } if (!data.FraudDetectionResult) { data.FraudDetectionResult = {}; data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.NOT_ENABLED; } // Resolve if both authentication and fraud detection are not enabled. if (!self.isAuthEnabled(data.AuthenticationResult.Decision) && !self.isFraudEnabled(data.FraudDetectionResult.Decision)) { connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); return; } if (data.StreamingStatus === connect.VoiceIdStreamingStatus.ENDED) { if (self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision)) { data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.INCONCLUSIVE; } if (self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision)) { data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE; } } // Voice print is not long enough for both authentication and fraud detection if (self.isAuthResultInconclusive(data.AuthenticationResult.Decision) && self.isFraudResultInconclusive(data.FraudDetectionResult.Decision)) { connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); return; } if (!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && self.isAuthEnabled(data.AuthenticationResult.Decision)) { switch (data.AuthenticationResult.Decision) { case connect.VoiceIdAuthenticationDecision.ACCEPT: data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.AUTHENTICATED; break; case connect.VoiceIdAuthenticationDecision.REJECT: data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_AUTHENTICATED; break; case connect.VoiceIdAuthenticationDecision.SPEAKER_OPTED_OUT: data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.OPTED_OUT; break; case connect.VoiceIdAuthenticationDecision.SPEAKER_NOT_ENROLLED: data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENROLLED; break; default: data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.ERROR; } } if (!self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision) && self.isFraudEnabled(data.FraudDetectionResult.Decision)) { switch (data.FraudDetectionResult.Decision) { case connect.VoiceIdFraudDetectionDecision.HIGH_RISK: data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.HIGH_RISK; break; case connect.VoiceIdFraudDetectionDecision.LOW_RISK: data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.LOW_RISK; break; default: data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.ERROR; } } if (!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && !self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision)) { // Resolve only when both authentication and fraud detection have results. Otherwise, keep polling. connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); return; } else { setTimeout(evaluate, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); } } } else { connect.getLog().error("evaluateSpeaker timeout").sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_TIMEOUT, "evaluateSpeaker timeout"); reject(error); } }, failure: function failure(err) { var error; var parsedErr = JSON.parse(err); switch (parsedErr.status) { case 400: case 404: error = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "evaluateSpeaker failed, session not exists", err); connect.getLog().error("evaluateSpeaker failed, session not exists").withObject({ err: err }).sendInternalLogToServer(); break; default: error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_FAILED, "evaluateSpeaker failed", err); connect.getLog().error("evaluateSpeaker failed").withObject({ err: err }).sendInternalLogToServer(); } reject(error); } }); })["catch"](function (err) { reject(err); }); } if (!startNew) { self.syncSpeakerId().then(function () { evaluate(); })["catch"](function (err) { connect.getLog().error("syncSpeakerId failed when session startNew=false").withObject({ err: err }).sendInternalLogToServer(); reject(err); }); } else { self.startSession().then(function (data) { self.syncSpeakerId().then(function (data) { setTimeout(evaluate, connect.VoiceIdConstants.EVALUATE_SESSION_DELAY); })["catch"](function (err) { connect.getLog().error("syncSpeakerId failed when session startNew=true").withObject({ err: err }).sendInternalLogToServer(); reject(err); }); })["catch"](function (err) { connect.getLog().error("startSession failed when session startNew=true").withObject({ err: err }).sendInternalLogToServer(); reject(err); }); } }); }; VoiceId.prototype.describeSession = function () { var self = this; var client = connect.core.getClient(); var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); return new Promise(function (resolve, reject) { self.getDomainId().then(function (domainId) { var params = { "SessionNameOrId": contactData.initialContactId || this.contactId, "DomainId": domainId }; connect.getLog().info("describeSession called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.DESCRIBE_SESSION, params, { success: function success(data) { resolve(data); }, failure: function failure(err) { connect.getLog().error("describeSession failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.DESCRIBE_SESSION_FAILED, "describeSession failed", err); reject(error); } }); })["catch"](function (err) { reject(err); }); }); }; VoiceId.prototype.checkEnrollmentStatus = function (callbackOnAudioCollectionComplete) { connect.getLog().info("checkEnrollmentStatus called").sendInternalLogToServer(); var self = this; var pollingTimes = 0; var callbackOnAudioCollectionCompleteHasBeenInvoked = false; return new Promise(function (resolve, reject) { function describe() { if (++pollingTimes < connect.VoiceIdConstants.ENROLLMENT_MAX_POLL_TIMES) { self.describeSession().then(function (data) { switch (data.Session.EnrollmentRequestDetails.Status) { case connect.VoiceIdEnrollmentRequestStatus.COMPLETED: resolve(data); break; case connect.VoiceIdEnrollmentRequestStatus.IN_PROGRESS: if (!callbackOnAudioCollectionCompleteHasBeenInvoked && typeof callbackOnAudioCollectionComplete === 'function') { callbackOnAudioCollectionComplete(data); callbackOnAudioCollectionCompleteHasBeenInvoked = true; } setTimeout(describe, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); break; case connect.VoiceIdEnrollmentRequestStatus.NOT_ENOUGH_SPEECH: if (data.Session.StreamingStatus !== connect.VoiceIdStreamingStatus.ENDED) { setTimeout(describe, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); } else { setTimeout(function () { self.startSession().then(function (data) { describe(); })["catch"](function (err, data) { reject(err); }); }, connect.VoiceIdConstants.START_SESSION_DELAY); } break; default: var message = data.Session.EnrollmentRequestDetails.Message ? data.Session.EnrollmentRequestDetails.Message : "enrollSpeaker failed. Unknown enrollment status has been received"; connect.getLog().error(message).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, message, data.Session.EnrollmentRequestDetails.Status); reject(error); } }); } else { connect.getLog().error("enrollSpeaker timeout").sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_TIMEOUT, "enrollSpeaker timeout"); reject(error); } } describe(); }); }; VoiceId.prototype.enrollSpeaker = function (callbackOnAudioCollectionComplete) { connect.getLog().info("enrollSpeaker called").sendInternalLogToServer(); var self = this; self.checkConferenceCall(); return new Promise(function (resolve, reject) { self.syncSpeakerId().then(function () { self.getSpeakerStatus().then(function (data) { if (data.Speaker && data.Speaker.Status == connect.VoiceIdSpeakerStatus.OPTED_OUT) { self.deleteSpeaker().then(function () { self.enrollSpeakerHelper(resolve, reject, callbackOnAudioCollectionComplete); })["catch"](function (err) { reject(err); }); } else { self.enrollSpeakerHelper(resolve, reject, callbackOnAudioCollectionComplete); } })["catch"](function (err) { reject(err); }); })["catch"](function (err) { reject(err); }); }); }; VoiceId.prototype.enrollSpeakerHelper = function (resolve, reject, callbackOnAudioCollectionComplete) { var self = this; var client = connect.core.getClient(); var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); self.getDomainId().then(function (domainId) { var params = { "SessionNameOrId": contactData.initialContactId || this.contactId, "DomainId": domainId }; connect.getLog().info("enrollSpeakerHelper called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.ENROLL_BY_SESSION, params, { success: function success(data) { if (data.Status === connect.VoiceIdEnrollmentRequestStatus.COMPLETED) { connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); } else { self.checkEnrollmentStatus(callbackOnAudioCollectionComplete).then(function (data) { connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); resolve(data); })["catch"](function (err) { reject(err); }); } }, failure: function failure(err) { connect.getLog().error("enrollSpeaker failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, "enrollSpeaker failed", err); reject(error); } }); })["catch"](function (err) { reject(err); }); }; // internal only VoiceId.prototype._updateSpeakerIdInLcms = function (speakerId, generatedSpeakerId) { var self = this; var client = connect.core.getClient(); return new Promise(function (resolve, reject) { var params = { "ContactId": self.contactId, "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), "VoiceIdResult": { "generatedSpeakerId": generatedSpeakerId } }; connect.getLog().info("_updateSpeakerIdInLcms called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, params, { success: function success(data) { connect.getLog().info("updateSpeakerIdInLcms succeeded").withObject(data).sendInternalLogToServer(); resolve(data); }, failure: function failure(err) { connect.getLog().error("updateSpeakerIdInLcms failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_IN_LCMS_FAILED, "updateSpeakerIdInLcms failed", err); reject(error); } }); }); }; VoiceId.prototype.updateSpeakerIdInVoiceId = function (speakerId) { var self = this; self.checkConferenceCall(); var client = connect.core.getClient(); var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); return new Promise(function (resolve, reject) { self.getDomainId().then(function (domainId) { var params = { "SessionNameOrId": contactData.initialContactId || this.contactId, "SpeakerId": connect.assertNotNull(speakerId, 'speakerId'), "DomainId": domainId }; connect.getLog().info("updateSpeakerIdInVoiceId called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.UPDATE_SESSION, params, { success: function success(data) { connect.getLog().info("updateSpeakerIdInVoiceId succeeded").withObject(data).sendInternalLogToServer(); var generatedSpeakerId = data && data.Session && data.Session.GeneratedSpeakerId; self._updateSpeakerIdInLcms(speakerId, generatedSpeakerId).then(function () { resolve(data); })["catch"](function (err) { reject(err); }); }, failure: function failure(err) { var error; var parsedErr = JSON.parse(err); switch (parsedErr.status) { case 400: case 404: error = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "updateSpeakerIdInVoiceId failed, session not exists", err); connect.getLog().error("updateSpeakerIdInVoiceId failed, session not exists").withObject({ err: err }).sendInternalLogToServer(); break; default: error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_FAILED, "updateSpeakerIdInVoiceId failed", err); connect.getLog().error("updateSpeakerIdInVoiceId failed").withObject({ err: err }).sendInternalLogToServer(); } reject(error); } }); })["catch"](function (err) { reject(err); }); }); }; VoiceId.prototype.syncSpeakerId = function () { connect.getLog().info("syncSpeakerId called").sendInternalLogToServer(); var self = this; return new Promise(function (resolve, reject) { self.getSpeakerId().then(function (data) { self.updateSpeakerIdInVoiceId(data.speakerId).then(function (data) { resolve(data); })["catch"](function (err) { reject(err); }); })["catch"](function (err) { reject(err); }); }); }; VoiceId.prototype.getDomainId = function () { return new Promise(function (resolve, reject) { var agent = new connect.Agent(); if (!agent.getPermissions().includes(connect.AgentPermissions.VOICE_ID)) { reject(new Error("Agent doesn't have the permission for Voice ID")); } else if (connect.core.voiceIdDomainId) { resolve(connect.core.voiceIdDomainId); } else { var client = connect.core.getClient(); var params = { "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), "IntegrationType": "VOICE_ID" }; connect.getLog().info("getDomainId called").withObject(params).sendInternalLogToServer(); client.call(connect.AgentAppClientMethods.LIST_INTEGRATION_ASSOCIATIONS, params, { success: function success(data) { try { var domainId; if (data.IntegrationAssociationSummaryList.length >= 1) { var integrationArn = data.IntegrationAssociationSummaryList[0].IntegrationArn; domainId = integrationArn.replace(/^.*domain\//i, ''); } if (!domainId) { connect.getLog().info("getDomainId: no domainId found").sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND); reject(error); return; } connect.getLog().info("getDomainId succeeded").withObject(data).sendInternalLogToServer(); connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.VoiceIdEvents.UPDATE_DOMAIN_ID, data: { domainId: domainId } }); resolve(domainId); } catch (err) { connect.getLog().error("getDomainId failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", err); reject(error); } }, failure: function failure(err) { connect.getLog().error("getDomainId failed").withObject({ err: err }).sendInternalLogToServer(); var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", err); reject(error); } }); } }); }; VoiceId.prototype.checkConferenceCall = function () { var self = this; var isConferenceCall = connect.core.getAgentDataProvider().getContactData(self.contactId).connections.filter(function (conn) { return connect.contains(connect.CONNECTION_ACTIVE_STATES, conn.state.type); }).length > 2; if (isConferenceCall) { throw new connect.NotImplementedError("VoiceId is not supported for conference calls"); } }; VoiceId.prototype.isAuthEnabled = function (authResult) { return authResult !== connect.ContactFlowAuthenticationDecision.NOT_ENABLED; }; VoiceId.prototype.isAuthResultNotEnoughSpeech = function (authResult) { return authResult === connect.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH; }; VoiceId.prototype.isAuthResultInconclusive = function (authResult) { return authResult === connect.ContactFlowAuthenticationDecision.INCONCLUSIVE; }; VoiceId.prototype.isFraudEnabled = function (fraudResult) { return fraudResult !== connect.ContactFlowFraudDetectionDecision.NOT_ENABLED; }; VoiceId.prototype.isFraudResultNotEnoughSpeech = function (fraudResult) { return fraudResult === connect.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH; }; VoiceId.prototype.isFraudResultInconclusive = function (fraudResult) { return fraudResult === connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE; }; /** * @class VoiceConnection * @param {number} contactId * @param {number} connectionId * @description - Provides voice media specific operations */ var VoiceConnection = function VoiceConnection(contactId, connectionId) { this._speakerAuthenticator = new VoiceId(contactId); Connection.call(this, contactId, connectionId); }; VoiceConnection.prototype = Object.create(Connection.prototype); VoiceConnection.prototype.constructor = VoiceConnection; /** * @deprecated * Please use getMediaInfo */ VoiceConnection.prototype.getSoftphoneMediaInfo = function () { return this._getData().softphoneMediaInfo; }; VoiceConnection.prototype.getMediaInfo = function () { return this._getData().softphoneMediaInfo; }; VoiceConnection.prototype.getMediaType = function () { return connect.MediaType.SOFTPHONE; }; VoiceConnection.prototype.getMediaController = function () { return connect.core.mediaFactory.get(this); }; VoiceConnection.prototype.getVoiceIdSpeakerId = function () { return this._speakerAuthenticator.getSpeakerId(); }; VoiceConnection.prototype.getVoiceIdSpeakerStatus = function () { return this._speakerAuthenticator.getSpeakerStatus(); }; VoiceConnection.prototype.optOutVoiceIdSpeaker = function () { return this._speakerAuthenticator.optOutSpeaker(); }; VoiceConnection.prototype.deleteVoiceIdSpeaker = function () { return this._speakerAuthenticator.deleteSpeaker(); }; VoiceConnection.prototype.evaluateSpeakerWithVoiceId = function (startNew) { return this._speakerAuthenticator.evaluateSpeaker(startNew); }; VoiceConnection.prototype.enrollSpeakerInVoiceId = function (callbackOnAudioCollectionComplete) { return this._speakerAuthenticator.enrollSpeaker(callbackOnAudioCollectionComplete); }; VoiceConnection.prototype.updateVoiceIdSpeakerId = function (speakerId) { return this._speakerAuthenticator.updateSpeakerIdInVoiceId(speakerId); }; VoiceConnection.prototype.getQuickConnectName = function () { return this._getData().quickConnectName; }; VoiceConnection.prototype.isSilentMonitor = function () { return this.getMonitorStatus() === connect.MonitoringMode.SILENT_MONITOR; }; VoiceConnection.prototype.isBarge = function () { return this.getMonitorStatus() === connect.MonitoringMode.BARGE; }; VoiceConnection.prototype.isBargeEnabled = function () { var monitoringCapabilities = this.getMonitorCapabilities(); return monitoringCapabilities && monitoringCapabilities.includes(connect.MonitoringMode.BARGE); }; VoiceConnection.prototype.isSilentMonitorEnabled = function () { var monitoringCapabilities = this.getMonitorCapabilities(); return monitoringCapabilities && monitoringCapabilities.includes(connect.MonitoringMode.SILENT_MONITOR); }; VoiceConnection.prototype.getMonitorCapabilities = function () { return this._getData().monitorCapabilities; }; VoiceConnection.prototype.getMonitorStatus = function () { return this._getData().monitorStatus; }; VoiceConnection.prototype.isMute = function () { return this._getData().mute; }; VoiceConnection.prototype.isForcedMute = function () { return this._getData().forcedMute; }; VoiceConnection.prototype.muteParticipant = function (callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.MUTE_PARTICIPANT, { contactId: this.getContactId(), connectionId: this.getConnectionId() }, callbacks); }; VoiceConnection.prototype.unmuteParticipant = function (callbacks) { var client = connect.core.getClient(); client.call(connect.ClientMethods.UNMUTE_PARTICIPANT, { contactId: this.getContactId(), connectionId: this.getConnectionId() }, callbacks); }; VoiceConnection.prototype.canSendVideo = function () { var capabilities = this.getCapabilities(); return capabilities && capabilities.Video === connect.VideoCapability.SEND; }; VoiceConnection.prototype.canSendScreenShare = function () { var capabilities = this.getCapabilities(); return capabilities && capabilities.ScreenShare === connect.ScreenShareCapability.SEND; }; VoiceConnection.prototype.getCapabilities = function () { return this._getData().capabilities; }; VoiceConnection.prototype.getVideoConnectionInfo = function () { var client = connect.core.getClient(); var transportDetails = { transportType: connect.TRANSPORT_TYPES.WEB_RTC, contactId: this.contactId }; return new Promise(function (resolve, reject) { client.call(connect.ClientMethods.CREATE_TRANSPORT, transportDetails, { success: function success(data) { connect.getLog().info("getVideoConnectionInfo succeeded").sendInternalLogToServer(); resolve(data.webRTCTransport); }, failure: function failure(err, data) { connect.getLog().error("getVideoConnectionInfo failed").sendInternalLogToServer().withObject({ err: err, data: data }); reject(Error("getVideoConnectionInfo failed")); } }); }); }; /** * @class ChatConnection * @param {*} contactId * @param {*} connectionId * @description adds the chat media specific functionality */ var ChatConnection = function ChatConnection(contactId, connectionId) { Connection.call(this, contactId, connectionId); }; ChatConnection.prototype = Object.create(Connection.prototype); ChatConnection.prototype.constructor = ChatConnection; ChatConnection.prototype.getMediaInfo = function () { var data = this._getData().chatMediaInfo; if (!data) { return null; } else { var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); var mediaObject = { contactId: this.contactId, initialContactId: contactData.initialContactId || this.contactId, participantId: this.connectionId, getConnectionToken: connect.hitch(this, this.getConnectionToken) }; if (data.connectionData) { try { mediaObject.participantToken = JSON.parse(data.connectionData).ConnectionAuthenticationToken; } catch (e) { connect.getLog().error(connect.LogComponent.CHAT, "Connection data is invalid").withObject(data).withException(e).sendInternalLogToServer(); mediaObject.participantToken = null; } } mediaObject.participantToken = mediaObject.participantToken || null; /** Just to keep the data accessible */ mediaObject.originalInfo = this._getData().chatMediaInfo; return mediaObject; } }; /** * Provides the chat connectionToken through the create_transport API for a specific contact and participant Id. * @returns a promise which, upon success, returns the response from the createTransport API. * Usage: * connection.getConnectionToken() * .then(response => {}) * .catch(error => {}) */ ChatConnection.prototype.getConnectionToken = function () { var client = connect.core.getClient(); var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); var transportDetails = { transportType: connect.TRANSPORT_TYPES.CHAT_TOKEN, participantId: this.connectionId, contactId: this.contactId }; return new Promise(function (resolve, reject) { client.call(connect.ClientMethods.CREATE_TRANSPORT, transportDetails, { success: function success(data) { connect.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(); resolve(data); }, failure: function failure(err, data) { connect.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({ err: err, data: data }); reject(Error("getConnectionToken failed")); } }); }); }; ChatConnection.prototype.getMediaType = function () { return connect.MediaType.CHAT; }; ChatConnection.prototype.getMediaController = function () { return connect.core.mediaFactory.get(this); }; ChatConnection.prototype._initMediaController = function () { // Note that a chat media controller only needs to be produced for agent type connections. if (this._isAgentConnectionType()) { connect.core.mediaFactory.get(this)["catch"](function () {}); } }; ChatConnection.prototype.isBargeEnabled = function () { var monitoringCapabilities = this.getMonitorCapabilities(); return monitoringCapabilities && monitoringCapabilities.includes(connect.MonitoringMode.BARGE); }; ChatConnection.prototype.isSilentMonitorEnabled = function () { var monitoringCapabilities = this.getMonitorCapabilities(); return monitoringCapabilities && monitoringCapabilities.includes(connect.MonitoringMode.SILENT_MONITOR); }; ChatConnection.prototype.getMonitorCapabilities = function () { return this._getData().monitorCapabilities; }; ChatConnection.prototype.isBarge = function () { return this.getMonitorStatus() === connect.MonitoringMode.BARGE; }; ChatConnection.prototype.isSilentMonitor = function () { return this.getMonitorStatus() === connect.MonitoringMode.SILENT_MONITOR; }; ChatConnection.prototype.getMonitorStatus = function () { return this._getData().monitorStatus; }; ChatConnection.prototype.getAuthenticationDetails = function () { var _contactData$segmentA; if (this._isAgentConnectionType()) { //only to be used for ChatConnection throw new Error("Authentication details are available only for customer connection"); } var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); if (contactData !== null && contactData !== void 0 && (_contactData$segmentA = contactData.segmentAttributes) !== null && _contactData$segmentA !== void 0 && (_contactData$segmentA = _contactData$segmentA["connect:CustomerAuthentication"]) !== null && _contactData$segmentA !== void 0 && _contactData$segmentA.ValueMap) { var attributesMap = contactData.segmentAttributes["connect:CustomerAuthentication"].ValueMap; if (_typeof(attributesMap) === 'object' && attributesMap !== null) { var returnVal = {}; for (var _i = 0, _Object$entries = Object.entries(attributesMap); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), key = _Object$entries$_i[0], value = _Object$entries$_i[1]; if ((value === null || value === void 0 ? void 0 : value.ValueString) !== null) { returnVal[key] = value.ValueString; } } return returnVal; } } return null; }; ChatConnection.prototype.isAuthenticated = function () { var authenticationDetails = this.getAuthenticationDetails(); return (authenticationDetails === null || authenticationDetails === void 0 ? void 0 : authenticationDetails.Status) === connect.CustomerAuthenticationStatus.AUTHENTICATED; }; /** * Returns the name associated with the connection * @returns */ ChatConnection.prototype.getParticipantName = function () { if (this._isAgentConnectionType()) { return new connect.Agent().getConfiguration().name; } else if (this.isInitialConnection()) { return this._getData().chatMediaInfo.customerName; } return this._getData().chatMediaInfo.agentName; }; /** * @class TaskConnection * @param {*} contactId * @param {*} connectionId * @description adds the task media specific functionality */ var TaskConnection = function TaskConnection(contactId, connectionId) { Connection.call(this, contactId, connectionId); }; TaskConnection.prototype = Object.create(Connection.prototype); TaskConnection.prototype.constructor = TaskConnection; TaskConnection.prototype.getMediaType = function () { return connect.MediaType.TASK; }; TaskConnection.prototype.getMediaInfo = function () { var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); var mediaObject = { contactId: this.contactId, initialContactId: contactData.initialContactId || this.contactId }; return mediaObject; }; TaskConnection.prototype.getMediaController = function () { return connect.core.mediaFactory.get(this); }; /** * @class EmailConnection * @param {*} contactId * @param {*} connectionId * @description adds Email specific functionality */ var EmailConnection = function EmailConnection(contactId, connectionId) { Connection.call(this, contactId, connectionId); }; EmailConnection.prototype = Object.create(Connection.prototype); EmailConnection.prototype.constructor = EmailConnection; EmailConnection.prototype.getMediaType = function () { return connect.MediaType.EMAIL; }; EmailConnection.prototype._initMediaController = function () {}; /*---------------------------------------------------------------- * class ConnectionSnapshot */ var ConnectionSnapshot = function ConnectionSnapshot(connectionData) { connect.Connection.call(this, connectionData.contactId, connectionData.connectionId); this.connectionData = connectionData; }; ConnectionSnapshot.prototype = Object.create(Connection.prototype); ConnectionSnapshot.prototype.constructor = ConnectionSnapshot; ConnectionSnapshot.prototype._getData = function () { return this.connectionData; }; ConnectionSnapshot.prototype._initMediaController = function () {}; var Endpoint = function Endpoint(paramsIn) { var params = paramsIn || {}; this.endpointARN = params.endpointId || params.endpointARN || null; this.endpointId = this.endpointARN; this.type = params.type || null; this.name = params.name || null; this.phoneNumber = params.phoneNumber || null; this.agentLogin = params.agentLogin || null; this.queue = params.queue || null; }; /** * Strip the SIP endpoint components from the phoneNumber field. */ Endpoint.prototype.stripPhoneNumber = function () { return this.phoneNumber ? this.phoneNumber.replace(/sip:([^@]*)@.*/, "$1") : ""; }; /** * Create an Endpoint object from the given phone number and name. */ Endpoint.byPhoneNumber = function (number, name) { return new Endpoint({ type: connect.EndpointType.PHONE_NUMBER, phoneNumber: number, name: name || null }); }; /** * Session Expiration Warning Manager */ var SessionExpirationWarningManager = /*#__PURE__*/function () { function SessionExpirationWarningManager() { _classCallCheck(this, SessionExpirationWarningManager); this.sessionExpirationWarningClient = new SessionExpirationWarningClient(connect.core.getSDKClientConfig()); } return _createClass(SessionExpirationWarningManager, [{ key: "_getSDKClient", value: function _getSDKClient() { if (this.sessionExpirationWarningClient) return this.sessionExpirationWarningClient;else { this.sessionExpirationWarningClient = new SessionExpirationWarningClient(connect.core.getSDKClientConfig()); return this.sessionExpirationWarningClient; } } // Triggered when the agent's session is about to expire due to inactivity }, { key: "onExpirationWarning", value: function onExpirationWarning(f) { var _this = this; var handler = function handler(e) { f(e); return Promise.resolve(); }; this._getSDKClient().onExpirationWarning(handler); return { unsubscribe: function unsubscribe() { return _this._getSDKClient().offExpirationWarning(handler); } }; } // Triggered when the warning has been cleared }, { key: "onExpirationWarningCleared", value: function onExpirationWarningCleared(f) { var _this2 = this; var handler = function handler(e) { f(e); return Promise.resolve(); }; this._getSDKClient().onExpirationWarningCleared(handler); return { unsubscribe: function unsubscribe() { return _this2._getSDKClient().offExpirationWarningCleared(handler); } }; } /** * Triggered when there is an error with updating the * agent's activity */ }, { key: "onSessionExtensionError", value: function onSessionExtensionError(f) { var _this3 = this; var handler = function handler(e) { f(e); return Promise.resolve(); }; this._getSDKClient().onSessionExtensionError(handler); return { unsubscribe: function unsubscribe() { return _this3._getSDKClient().offExpirationWarningCleared(handler); } }; } }]); }(); // Sends activity signals indicating that the agent is active connect.sendActivity = function () { return sendActivity(connect.core.getSDKClientConfig().provider); }; /*---------------------------------------------------------------- * class SoftphoneError */ var SoftphoneError = function SoftphoneError(errorType, errorMessage, endPointUrl) { this.errorType = errorType; this.errorMessage = errorMessage; this.endPointUrl = endPointUrl; }; SoftphoneError.prototype.getErrorType = function () { return this.errorType; }; SoftphoneError.prototype.getErrorMessage = function () { return this.errorMessage; }; SoftphoneError.prototype.getEndPointUrl = function () { return this.endPointUrl; }; /*---------------------------------------------------------------- * Root Subscription APIs. */ connect.agent = function (f) { var bus = connect.core.getEventBus(); var sub = bus.subscribe(connect.AgentEvents.INIT, f); if (connect.agent.initialized) { f(new connect.Agent()); } return sub; }; connect.agent.initialized = false; connect.contact = function (f) { var bus = connect.core.getEventBus(); return bus.subscribe(connect.ContactEvents.INIT, f); }; connect.onWebsocketInitFailure = function (f) { var bus = connect.core.getEventBus(); var sub = bus.subscribe(connect.WebSocketEvents.INIT_FAILURE, f); if (connect.webSocketInitFailed) { f(); } return sub; }; /** * Starts the given function asynchronously only if the shared worker * says we are the master for the given topic. If there is no master for * the given topic, we become the master and start the function unless * shouldNotBecomeMasterIfNone is true. * * @param topic The master topic we are concerned about. * @param f_true The callback to be invoked if we are the master. * @param f_else [optional] A callback to be invoked if we are not the master. * @param shouldNotBecomeMasterIfNone [optional] if true, this tab won't become master. */ connect.ifMaster = function (topic, f_true, f_else, shouldNotBecomeMasterIfNone) { connect.assertNotNull(topic, "A topic must be provided."); connect.assertNotNull(f_true, "A true callback must be provided."); if (!connect.core.masterClient) { // We can't be the master because there is no master client! connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", topic).sendInternalLogToServer(); if (f_else) { f_else(); } return; } var masterClient = connect.core.getMasterClient(); masterClient.call(connect.MasterMethods.CHECK_MASTER, { topic: topic, shouldNotBecomeMasterIfNone: shouldNotBecomeMasterIfNone }, { success: function success(data) { if (data.isMaster) { f_true(); } else if (f_else) { f_else(); } } }); }; /** * Notify the shared worker and other CCP tabs that we are now the master for the given topic. */ connect.becomeMaster = function (topic, successCallback, failureCallback) { connect.assertNotNull(topic, "A topic must be provided."); if (!connect.core.masterClient) { // We can't be the master because there is no master client! connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", topic); if (failureCallback) { failureCallback(); } } else { var masterClient = connect.core.getMasterClient(); masterClient.call(connect.MasterMethods.BECOME_MASTER, { topic: topic }, { success: function success() { if (successCallback) { successCallback(); } } }); } }; connect.Agent = Agent; connect.AgentSnapshot = AgentSnapshot; connect.Contact = Contact; connect.ContactSnapshot = ContactSnapshot; /** Default will get the Voice connection */ connect.Connection = VoiceConnection; connect.BaseConnection = Connection; connect.VoiceConnection = VoiceConnection; connect.ChatConnection = ChatConnection; connect.TaskConnection = TaskConnection; connect.EmailConnection = EmailConnection; connect.ConnectionSnapshot = ConnectionSnapshot; connect.Endpoint = Endpoint; connect.Address = Endpoint; connect.SoftphoneError = SoftphoneError; connect.VoiceId = VoiceId; connect.QuickResponses = QuickResponses; connect.SessionExpirationWarningManager = SessionExpirationWarningManager; })(); /***/ }), /***/ 167: /***/ ((module, exports, __webpack_require__) => { var __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o;}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o;},_typeof(o);}// AWS SDK for JavaScript v2.1455.0 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // License at https://sdk.amazonaws.com/js/BUNDLE_LICENSE.txt (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=undefined;if(!f&&c)return require(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a;}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r);},p,p.exports,r,e,n,t);}return n[i].exports;}for(var u=undefined,i=0;i-1;};}/** * @api private */var viewStrings=['[object Int8Array]','[object Uint8Array]','[object Uint8ClampedArray]','[object Int16Array]','[object Uint16Array]','[object Int32Array]','[object Uint32Array]','[object Float32Array]','[object Float64Array]','[object DataView]'];/** * @api private */function isEmptyData(data){if(typeof data==='string'){return data.length===0;}return data.byteLength===0;}/** * @api private */function convertToBuffer(data){if(typeof data==='string'){data=new Buffer(data,'utf8');}if(ArrayBuffer.isView(data)){return new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT);}return new Uint8Array(data);}/** * @api private */module.exports=exports={isEmptyData:isEmptyData,convertToBuffer:convertToBuffer};},{"buffer/":86}],12:[function(require,module,exports){var hashUtils=require('./browserHashUtils');/** * @api private */function Hmac(hashCtor,secret){this.hash=new hashCtor();this.outer=new hashCtor();var inner=bufferFromSecret(hashCtor,secret);var outer=new Uint8Array(hashCtor.BLOCK_SIZE);outer.set(inner);for(var i=0;ihashCtor.BLOCK_SIZE){var bufferHash=new hashCtor();bufferHash.update(input);input=bufferHash.digest();}var buffer=new Uint8Array(hashCtor.BLOCK_SIZE);buffer.set(input);return buffer;}},{"./browserHashUtils":11}],13:[function(require,module,exports){var hashUtils=require('./browserHashUtils');var Buffer=require('buffer/').Buffer;var BLOCK_SIZE=64;var DIGEST_LENGTH=16;var INIT=[0x67452301,0xefcdab89,0x98badcfe,0x10325476];/** * @api private */function Md5(){this.state=[0x67452301,0xefcdab89,0x98badcfe,0x10325476];this.buffer=new DataView(new ArrayBuffer(BLOCK_SIZE));this.bufferLength=0;this.bytesHashed=0;this.finished=false;}/** * @api private */module.exports=exports=Md5;Md5.BLOCK_SIZE=BLOCK_SIZE;Md5.prototype.update=function(sourceData){if(hashUtils.isEmptyData(sourceData)){return this;}else if(this.finished){throw new Error('Attempted to update an already finished hash.');}var data=hashUtils.convertToBuffer(sourceData);var position=0;var byteLength=data.byteLength;this.bytesHashed+=byteLength;while(byteLength>0){this.buffer.setUint8(this.bufferLength++,data[position++]);byteLength--;if(this.bufferLength===BLOCK_SIZE){this.hashBuffer();this.bufferLength=0;}}return this;};Md5.prototype.digest=function(encoding){if(!this.finished){var _a=this,buffer=_a.buffer,undecoratedLength=_a.bufferLength,bytesHashed=_a.bytesHashed;var bitsHashed=bytesHashed*8;buffer.setUint8(this.bufferLength++,128);// Ensure the final block has enough room for the hashed length if(undecoratedLength%BLOCK_SIZE>=BLOCK_SIZE-8){for(var i=this.bufferLength;i>>0,true);buffer.setUint32(BLOCK_SIZE-4,Math.floor(bitsHashed/0x100000000),true);this.hashBuffer();this.finished=true;}var out=new DataView(new ArrayBuffer(DIGEST_LENGTH));for(var i=0;i<4;i++){out.setUint32(i*4,this.state[i],true);}var buff=new Buffer(out.buffer,out.byteOffset,out.byteLength);return encoding?buff.toString(encoding):buff;};Md5.prototype.hashBuffer=function(){var _a=this,buffer=_a.buffer,state=_a.state;var a=state[0],b=state[1],c=state[2],d=state[3];a=ff(a,b,c,d,buffer.getUint32(0,true),7,0xd76aa478);d=ff(d,a,b,c,buffer.getUint32(4,true),12,0xe8c7b756);c=ff(c,d,a,b,buffer.getUint32(8,true),17,0x242070db);b=ff(b,c,d,a,buffer.getUint32(12,true),22,0xc1bdceee);a=ff(a,b,c,d,buffer.getUint32(16,true),7,0xf57c0faf);d=ff(d,a,b,c,buffer.getUint32(20,true),12,0x4787c62a);c=ff(c,d,a,b,buffer.getUint32(24,true),17,0xa8304613);b=ff(b,c,d,a,buffer.getUint32(28,true),22,0xfd469501);a=ff(a,b,c,d,buffer.getUint32(32,true),7,0x698098d8);d=ff(d,a,b,c,buffer.getUint32(36,true),12,0x8b44f7af);c=ff(c,d,a,b,buffer.getUint32(40,true),17,0xffff5bb1);b=ff(b,c,d,a,buffer.getUint32(44,true),22,0x895cd7be);a=ff(a,b,c,d,buffer.getUint32(48,true),7,0x6b901122);d=ff(d,a,b,c,buffer.getUint32(52,true),12,0xfd987193);c=ff(c,d,a,b,buffer.getUint32(56,true),17,0xa679438e);b=ff(b,c,d,a,buffer.getUint32(60,true),22,0x49b40821);a=gg(a,b,c,d,buffer.getUint32(4,true),5,0xf61e2562);d=gg(d,a,b,c,buffer.getUint32(24,true),9,0xc040b340);c=gg(c,d,a,b,buffer.getUint32(44,true),14,0x265e5a51);b=gg(b,c,d,a,buffer.getUint32(0,true),20,0xe9b6c7aa);a=gg(a,b,c,d,buffer.getUint32(20,true),5,0xd62f105d);d=gg(d,a,b,c,buffer.getUint32(40,true),9,0x02441453);c=gg(c,d,a,b,buffer.getUint32(60,true),14,0xd8a1e681);b=gg(b,c,d,a,buffer.getUint32(16,true),20,0xe7d3fbc8);a=gg(a,b,c,d,buffer.getUint32(36,true),5,0x21e1cde6);d=gg(d,a,b,c,buffer.getUint32(56,true),9,0xc33707d6);c=gg(c,d,a,b,buffer.getUint32(12,true),14,0xf4d50d87);b=gg(b,c,d,a,buffer.getUint32(32,true),20,0x455a14ed);a=gg(a,b,c,d,buffer.getUint32(52,true),5,0xa9e3e905);d=gg(d,a,b,c,buffer.getUint32(8,true),9,0xfcefa3f8);c=gg(c,d,a,b,buffer.getUint32(28,true),14,0x676f02d9);b=gg(b,c,d,a,buffer.getUint32(48,true),20,0x8d2a4c8a);a=hh(a,b,c,d,buffer.getUint32(20,true),4,0xfffa3942);d=hh(d,a,b,c,buffer.getUint32(32,true),11,0x8771f681);c=hh(c,d,a,b,buffer.getUint32(44,true),16,0x6d9d6122);b=hh(b,c,d,a,buffer.getUint32(56,true),23,0xfde5380c);a=hh(a,b,c,d,buffer.getUint32(4,true),4,0xa4beea44);d=hh(d,a,b,c,buffer.getUint32(16,true),11,0x4bdecfa9);c=hh(c,d,a,b,buffer.getUint32(28,true),16,0xf6bb4b60);b=hh(b,c,d,a,buffer.getUint32(40,true),23,0xbebfbc70);a=hh(a,b,c,d,buffer.getUint32(52,true),4,0x289b7ec6);d=hh(d,a,b,c,buffer.getUint32(0,true),11,0xeaa127fa);c=hh(c,d,a,b,buffer.getUint32(12,true),16,0xd4ef3085);b=hh(b,c,d,a,buffer.getUint32(24,true),23,0x04881d05);a=hh(a,b,c,d,buffer.getUint32(36,true),4,0xd9d4d039);d=hh(d,a,b,c,buffer.getUint32(48,true),11,0xe6db99e5);c=hh(c,d,a,b,buffer.getUint32(60,true),16,0x1fa27cf8);b=hh(b,c,d,a,buffer.getUint32(8,true),23,0xc4ac5665);a=ii(a,b,c,d,buffer.getUint32(0,true),6,0xf4292244);d=ii(d,a,b,c,buffer.getUint32(28,true),10,0x432aff97);c=ii(c,d,a,b,buffer.getUint32(56,true),15,0xab9423a7);b=ii(b,c,d,a,buffer.getUint32(20,true),21,0xfc93a039);a=ii(a,b,c,d,buffer.getUint32(48,true),6,0x655b59c3);d=ii(d,a,b,c,buffer.getUint32(12,true),10,0x8f0ccc92);c=ii(c,d,a,b,buffer.getUint32(40,true),15,0xffeff47d);b=ii(b,c,d,a,buffer.getUint32(4,true),21,0x85845dd1);a=ii(a,b,c,d,buffer.getUint32(32,true),6,0x6fa87e4f);d=ii(d,a,b,c,buffer.getUint32(60,true),10,0xfe2ce6e0);c=ii(c,d,a,b,buffer.getUint32(24,true),15,0xa3014314);b=ii(b,c,d,a,buffer.getUint32(52,true),21,0x4e0811a1);a=ii(a,b,c,d,buffer.getUint32(16,true),6,0xf7537e82);d=ii(d,a,b,c,buffer.getUint32(44,true),10,0xbd3af235);c=ii(c,d,a,b,buffer.getUint32(8,true),15,0x2ad7d2bb);b=ii(b,c,d,a,buffer.getUint32(36,true),21,0xeb86d391);state[0]=a+state[0]&0xFFFFFFFF;state[1]=b+state[1]&0xFFFFFFFF;state[2]=c+state[2]&0xFFFFFFFF;state[3]=d+state[3]&0xFFFFFFFF;};function cmn(q,a,b,x,s,t){a=(a+q&0xFFFFFFFF)+(x+t&0xFFFFFFFF)&0xFFFFFFFF;return(a<>>32-s)+b&0xFFFFFFFF;}function ff(a,b,c,d,x,s,t){return cmn(b&c|~b&d,a,b,x,s,t);}function gg(a,b,c,d,x,s,t){return cmn(b&d|c&~d,a,b,x,s,t);}function hh(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t);}function ii(a,b,c,d,x,s,t){return cmn(c^(b|~d),a,b,x,s,t);}},{"./browserHashUtils":11,"buffer/":86}],14:[function(require,module,exports){var Buffer=require('buffer/').Buffer;var hashUtils=require('./browserHashUtils');var BLOCK_SIZE=64;var DIGEST_LENGTH=20;var KEY=new Uint32Array([0x5a827999,0x6ed9eba1,0x8f1bbcdc|0,0xca62c1d6|0]);var INIT=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];var MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;/** * @api private */function Sha1(){this.h0=0x67452301;this.h1=0xEFCDAB89;this.h2=0x98BADCFE;this.h3=0x10325476;this.h4=0xC3D2E1F0;// The first 64 bytes (16 words) is the data chunk this.block=new Uint32Array(80);this.offset=0;this.shift=24;this.totalLength=0;}/** * @api private */module.exports=exports=Sha1;Sha1.BLOCK_SIZE=BLOCK_SIZE;Sha1.prototype.update=function(data){if(this.finished){throw new Error('Attempted to update an already finished hash.');}if(hashUtils.isEmptyData(data)){return this;}data=hashUtils.convertToBuffer(data);var length=data.length;this.totalLength+=length*8;for(var i=0;i14||this.offset===14&&this.shift<24){this.processBlock();}this.offset=14;this.shift=24;// 64-bit length big-endian this.write(0x00);// numbers this big aren't accurate in javascript anyway this.write(0x00);// ..So just hard-code to zero. this.write(this.totalLength>0xffffffffff?this.totalLength/0x10000000000:0x00);this.write(this.totalLength>0xffffffff?this.totalLength/0x100000000:0x00);for(var s=24;s>=0;s-=8){this.write(this.totalLength>>s);}// The value in state is little-endian rather than big-endian, so flip // each word into a new Uint8Array var out=new Buffer(DIGEST_LENGTH);var outView=new DataView(out.buffer);outView.setUint32(0,this.h0,false);outView.setUint32(4,this.h1,false);outView.setUint32(8,this.h2,false);outView.setUint32(12,this.h3,false);outView.setUint32(16,this.h4,false);return encoding?out.toString(encoding):out;};Sha1.prototype.processBlock=function processBlock(){// Extend the sixteen 32-bit words into eighty 32-bit words: for(var i=16;i<80;i++){var w=this.block[i-3]^this.block[i-8]^this.block[i-14]^this.block[i-16];this.block[i]=w<<1|w>>>31;}// Initialize hash value for this chunk: var a=this.h0;var b=this.h1;var c=this.h2;var d=this.h3;var e=this.h4;var f,k;// Main loop: for(i=0;i<80;i++){if(i<20){f=d^b&(c^d);k=0x5A827999;}else if(i<40){f=b^c^d;k=0x6ED9EBA1;}else if(i<60){f=b&c|d&(b|c);k=0x8F1BBCDC;}else{f=b^c^d;k=0xCA62C1D6;}var temp=(a<<5|a>>>27)+f+e+k+(this.block[i]|0);e=d;d=c;c=b<<30|b>>>2;b=a;a=temp;}// Add this chunk's hash to result so far: this.h0=this.h0+a|0;this.h1=this.h1+b|0;this.h2=this.h2+c|0;this.h3=this.h3+d|0;this.h4=this.h4+e|0;// The block is now reusable. this.offset=0;for(i=0;i<16;i++){this.block[i]=0;}};},{"./browserHashUtils":11,"buffer/":86}],15:[function(require,module,exports){var Buffer=require('buffer/').Buffer;var hashUtils=require('./browserHashUtils');var BLOCK_SIZE=64;var DIGEST_LENGTH=32;var KEY=new Uint32Array([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]);var INIT=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];var MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;/** * @private */function Sha256(){this.state=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];this.temp=new Int32Array(64);this.buffer=new Uint8Array(64);this.bufferLength=0;this.bytesHashed=0;/** * @private */this.finished=false;}/** * @api private */module.exports=exports=Sha256;Sha256.BLOCK_SIZE=BLOCK_SIZE;Sha256.prototype.update=function(data){if(this.finished){throw new Error('Attempted to update an already finished hash.');}if(hashUtils.isEmptyData(data)){return this;}data=hashUtils.convertToBuffer(data);var position=0;var byteLength=data.byteLength;this.bytesHashed+=byteLength;if(this.bytesHashed*8>MAX_HASHABLE_LENGTH){throw new Error('Cannot hash more than 2^53 - 1 bits');}while(byteLength>0){this.buffer[this.bufferLength++]=data[position++];byteLength--;if(this.bufferLength===BLOCK_SIZE){this.hashBuffer();this.bufferLength=0;}}return this;};Sha256.prototype.digest=function(encoding){if(!this.finished){var bitsHashed=this.bytesHashed*8;var bufferView=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength);var undecoratedLength=this.bufferLength;bufferView.setUint8(this.bufferLength++,0x80);// Ensure the final block has enough room for the hashed length if(undecoratedLength%BLOCK_SIZE>=BLOCK_SIZE-8){for(var i=this.bufferLength;i>>24&0xff;out[i*4+1]=this.state[i]>>>16&0xff;out[i*4+2]=this.state[i]>>>8&0xff;out[i*4+3]=this.state[i]>>>0&0xff;}return encoding?out.toString(encoding):out;};Sha256.prototype.hashBuffer=function(){var _a=this,buffer=_a.buffer,state=_a.state;var state0=state[0],state1=state[1],state2=state[2],state3=state[3],state4=state[4],state5=state[5],state6=state[6],state7=state[7];for(var i=0;i>>17|u<<15)^(u>>>19|u<<13)^u>>>10;u=this.temp[i-15];var t2_1=(u>>>7|u<<25)^(u>>>18|u<<14)^u>>>3;this.temp[i]=(t1_1+this.temp[i-7]|0)+(t2_1+this.temp[i-16]|0);}var t1=(((state4>>>6|state4<<26)^(state4>>>11|state4<<21)^(state4>>>25|state4<<7))+(state4&state5^~state4&state6)|0)+(state7+(KEY[i]+this.temp[i]|0)|0)|0;var t2=((state0>>>2|state0<<30)^(state0>>>13|state0<<19)^(state0>>>22|state0<<10))+(state0&state1^state0&state2^state1&state2)|0;state7=state6;state6=state5;state5=state4;state4=state3+t1|0;state3=state2;state2=state1;state1=state0;state0=t1+t2|0;}state[0]+=state0;state[1]+=state1;state[2]+=state2;state[3]+=state3;state[4]+=state4;state[5]+=state5;state[6]+=state6;state[7]+=state7;};},{"./browserHashUtils":11,"buffer/":86}],16:[function(require,module,exports){(function(process){(function(){var util=require('./util');// browser specific modules util.crypto.lib=require('./browserCryptoLib');util.Buffer=require('buffer/').Buffer;util.url=require('url/');util.querystring=require('querystring/');util.realClock=require('./realclock/browserClock');util.environment='js';util.createEventStream=require('./event-stream/buffered-create-event-stream').createEventStream;util.isBrowser=function(){return true;};util.isNode=function(){return false;};var AWS=require('./core');/** * @api private */module.exports=AWS;require('./credentials');require('./credentials/credential_provider_chain');require('./credentials/temporary_credentials');require('./credentials/chainable_temporary_credentials');require('./credentials/web_identity_credentials');require('./credentials/cognito_identity_credentials');require('./credentials/saml_credentials');// Load the DOMParser XML parser AWS.XML.Parser=require('./xml/browser_parser');// Load the XHR HttpClient require('./http/xhr');if(typeof process==='undefined'){var process={browser:true};}}).call(this);}).call(this,require('_process'));},{"./browserCryptoLib":10,"./core":19,"./credentials":20,"./credentials/chainable_temporary_credentials":21,"./credentials/cognito_identity_credentials":22,"./credentials/credential_provider_chain":23,"./credentials/saml_credentials":24,"./credentials/temporary_credentials":25,"./credentials/web_identity_credentials":26,"./event-stream/buffered-create-event-stream":28,"./http/xhr":36,"./realclock/browserClock":54,"./util":74,"./xml/browser_parser":75,"_process":91,"buffer/":86,"querystring/":98,"url/":100}],17:[function(require,module,exports){var AWS=require('./core');require('./credentials');require('./credentials/credential_provider_chain');var PromisesDependency;/** * The main configuration class used by all service objects to set * the region, credentials, and other options for requests. * * By default, credentials and region settings are left unconfigured. * This should be configured by the application before using any * AWS service APIs. * * In order to set global configuration options, properties should * be assigned to the global {AWS.config} object. * * @see AWS.config * * @!group General Configuration Options * * @!attribute credentials * @return [AWS.Credentials] the AWS credentials to sign requests with. * * @!attribute region * @example Set the global region setting to us-west-2 * AWS.config.update({region: 'us-west-2'}); * @return [AWS.Credentials] The region to send service requests to. * @see http://docs.amazonwebservices.com/general/latest/gr/rande.html * A list of available endpoints for each AWS service * * @!attribute maxRetries * @return [Integer] the maximum amount of retries to perform for a * service request. By default this value is calculated by the specific * service object that the request is being made to. * * @!attribute maxRedirects * @return [Integer] the maximum amount of redirects to follow for a * service request. Defaults to 10. * * @!attribute paramValidation * @return [Boolean|map] whether input parameters should be validated against * the operation description before sending the request. Defaults to true. * Pass a map to enable any of the following specific validation features: * * * **min** [Boolean] — Validates that a value meets the min * constraint. This is enabled by default when paramValidation is set * to `true`. * * **max** [Boolean] — Validates that a value meets the max * constraint. * * **pattern** [Boolean] — Validates that a string value matches a * regular expression. * * **enum** [Boolean] — Validates that a string value matches one * of the allowable enum values. * * @!attribute computeChecksums * @return [Boolean] whether to compute checksums for payload bodies when * the service accepts it (currently supported in S3 and SQS only). * * @!attribute convertResponseTypes * @return [Boolean] whether types are converted when parsing response data. * Currently only supported for JSON based services. Turning this off may * improve performance on large response payloads. Defaults to `true`. * * @!attribute correctClockSkew * @return [Boolean] whether to apply a clock skew correction and retry * requests that fail because of an skewed client clock. Defaults to * `false`. * * @!attribute sslEnabled * @return [Boolean] whether SSL is enabled for requests * * @!attribute s3ForcePathStyle * @return [Boolean] whether to force path style URLs for S3 objects * * @!attribute s3BucketEndpoint * @note Setting this configuration option requires an `endpoint` to be * provided explicitly to the service constructor. * @return [Boolean] whether the provided endpoint addresses an individual * bucket (false if it addresses the root API endpoint). * * @!attribute s3DisableBodySigning * @return [Boolean] whether to disable S3 body signing when using signature version `v4`. * Body signing can only be disabled when using https. Defaults to `true`. * * @!attribute s3UsEast1RegionalEndpoint * @return ['legacy'|'regional'] when region is set to 'us-east-1', whether to send s3 * request to global endpoints or 'us-east-1' regional endpoints. This config is only * applicable to S3 client; * Defaults to 'legacy' * @!attribute s3UseArnRegion * @return [Boolean] whether to override the request region with the region inferred * from requested resource's ARN. Only available for S3 buckets * Defaults to `true` * * @!attribute useAccelerateEndpoint * @note This configuration option is only compatible with S3 while accessing * dns-compatible buckets. * @return [Boolean] Whether to use the Accelerate endpoint with the S3 service. * Defaults to `false`. * * @!attribute retryDelayOptions * @example Set the base retry delay for all services to 300 ms * AWS.config.update({retryDelayOptions: {base: 300}}); * // Delays with maxRetries = 3: 300, 600, 1200 * @example Set a custom backoff function to provide delay values on retries * AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount, err) { * // returns delay in ms * }}}); * @return [map] A set of options to configure the retry delay on retryable errors. * Currently supported options are: * * * **base** [Integer] — The base number of milliseconds to use in the * exponential backoff for operation retries. Defaults to 100 ms for all services except * DynamoDB, where it defaults to 50ms. * * * **customBackoff ** [function] — A custom function that accepts a * retry count and error and returns the amount of time to delay in * milliseconds. If the result is a non-zero negative value, no further * retry attempts will be made. The `base` option will be ignored if this * option is supplied. The function is only called for retryable errors. * * @!attribute httpOptions * @return [map] A set of options to pass to the low-level HTTP request. * Currently supported options are: * * * **proxy** [String] — the URL to proxy requests through * * **agent** [http.Agent, https.Agent] — the Agent object to perform * HTTP requests with. Used for connection pooling. Note that for * SSL connections, a special Agent object is used in order to enable * peer certificate verification. This feature is only supported in the * Node.js environment. * * **connectTimeout** [Integer] — Sets the socket to timeout after * failing to establish a connection with the server after * `connectTimeout` milliseconds. This timeout has no effect once a socket * connection has been established. * * **timeout** [Integer] — The number of milliseconds a request can * take before automatically being terminated. * Defaults to two minutes (120000). * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous * HTTP requests. Used in the browser environment only. Set to false to * send requests synchronously. Defaults to true (async on). * * **xhrWithCredentials** [Boolean] — Sets the "withCredentials" * property of an XMLHttpRequest object. Used in the browser environment * only. Defaults to false. * @!attribute logger * @return [#write,#log] an object that responds to .write() (like a stream) * or .log() (like the console object) in order to log information about * requests * * @!attribute systemClockOffset * @return [Number] an offset value in milliseconds to apply to all signing * times. Use this to compensate for clock skew when your system may be * out of sync with the service time. Note that this configuration option * can only be applied to the global `AWS.config` object and cannot be * overridden in service-specific configuration. Defaults to 0 milliseconds. * * @!attribute signatureVersion * @return [String] the signature version to sign requests with (overriding * the API configuration). Possible values are: 'v2', 'v3', 'v4'. * * @!attribute signatureCache * @return [Boolean] whether the signature to sign requests with (overriding * the API configuration) is cached. Only applies to the signature version 'v4'. * Defaults to `true`. * * @!attribute endpointDiscoveryEnabled * @return [Boolean|undefined] whether to call operations with endpoints * given by service dynamically. Setting this config to `true` will enable * endpoint discovery for all applicable operations. Setting it to `false` * will explicitly disable endpoint discovery even though operations that * require endpoint discovery will presumably fail. Leaving it to * `undefined` means SDK only do endpoint discovery when it's required. * Defaults to `undefined` * * @!attribute endpointCacheSize * @return [Number] the size of the global cache storing endpoints from endpoint * discovery operations. Once endpoint cache is created, updating this setting * cannot change existing cache size. * Defaults to 1000 * * @!attribute hostPrefixEnabled * @return [Boolean] whether to marshal request parameters to the prefix of * hostname. Defaults to `true`. * * @!attribute stsRegionalEndpoints * @return ['legacy'|'regional'] whether to send sts request to global endpoints or * regional endpoints. * Defaults to 'legacy'. * * @!attribute useFipsEndpoint * @return [Boolean] Enables FIPS compatible endpoints. Defaults to `false`. * * @!attribute useDualstackEndpoint * @return [Boolean] Enables IPv6 dualstack endpoint. Defaults to `false`. */AWS.Config=AWS.util.inherit({/** * @!endgroup *//** * Creates a new configuration object. This is the object that passes * option data along to service requests, including credentials, security, * region information, and some service specific settings. * * @example Creating a new configuration object with credentials and region * var config = new AWS.Config({ * accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2' * }); * @option options accessKeyId [String] your AWS access key ID. * @option options secretAccessKey [String] your AWS secret access key. * @option options sessionToken [AWS.Credentials] the optional AWS * session token to sign requests with. * @option options credentials [AWS.Credentials] the AWS credentials * to sign requests with. You can either specify this object, or * specify the accessKeyId and secretAccessKey options directly. * @option options credentialProvider [AWS.CredentialProviderChain] the * provider chain used to resolve credentials if no static `credentials` * property is set. * @option options region [String] the region to send service requests to. * See {region} for more information. * @option options maxRetries [Integer] the maximum amount of retries to * attempt with a request. See {maxRetries} for more information. * @option options maxRedirects [Integer] the maximum amount of redirects to * follow with a request. See {maxRedirects} for more information. * @option options sslEnabled [Boolean] whether to enable SSL for * requests. * @option options paramValidation [Boolean|map] whether input parameters * should be validated against the operation description before sending * the request. Defaults to true. Pass a map to enable any of the * following specific validation features: * * * **min** [Boolean] — Validates that a value meets the min * constraint. This is enabled by default when paramValidation is set * to `true`. * * **max** [Boolean] — Validates that a value meets the max * constraint. * * **pattern** [Boolean] — Validates that a string value matches a * regular expression. * * **enum** [Boolean] — Validates that a string value matches one * of the allowable enum values. * @option options computeChecksums [Boolean] whether to compute checksums * for payload bodies when the service accepts it (currently supported * in S3 only) * @option options convertResponseTypes [Boolean] whether types are converted * when parsing response data. Currently only supported for JSON based * services. Turning this off may improve performance on large response * payloads. Defaults to `true`. * @option options correctClockSkew [Boolean] whether to apply a clock skew * correction and retry requests that fail because of an skewed client * clock. Defaults to `false`. * @option options s3ForcePathStyle [Boolean] whether to force path * style URLs for S3 objects. * @option options s3BucketEndpoint [Boolean] whether the provided endpoint * addresses an individual bucket (false if it addresses the root API * endpoint). Note that setting this configuration option requires an * `endpoint` to be provided explicitly to the service constructor. * @option options s3DisableBodySigning [Boolean] whether S3 body signing * should be disabled when using signature version `v4`. Body signing * can only be disabled when using https. Defaults to `true`. * @option options s3UsEast1RegionalEndpoint ['legacy'|'regional'] when region * is set to 'us-east-1', whether to send s3 request to global endpoints or * 'us-east-1' regional endpoints. This config is only applicable to S3 client. * Defaults to `legacy` * @option options s3UseArnRegion [Boolean] whether to override the request region * with the region inferred from requested resource's ARN. Only available for S3 buckets * Defaults to `true` * * @option options retryDelayOptions [map] A set of options to configure * the retry delay on retryable errors. Currently supported options are: * * * **base** [Integer] — The base number of milliseconds to use in the * exponential backoff for operation retries. Defaults to 100 ms for all * services except DynamoDB, where it defaults to 50ms. * * **customBackoff ** [function] — A custom function that accepts a * retry count and error and returns the amount of time to delay in * milliseconds. If the result is a non-zero negative value, no further * retry attempts will be made. The `base` option will be ignored if this * option is supplied. The function is only called for retryable errors. * @option options httpOptions [map] A set of options to pass to the low-level * HTTP request. Currently supported options are: * * * **proxy** [String] — the URL to proxy requests through * * **agent** [http.Agent, https.Agent] — the Agent object to perform * HTTP requests with. Used for connection pooling. Defaults to the global * agent (`http.globalAgent`) for non-SSL connections. Note that for * SSL connections, a special Agent object is used in order to enable * peer certificate verification. This feature is only available in the * Node.js environment. * * **connectTimeout** [Integer] — Sets the socket to timeout after * failing to establish a connection with the server after * `connectTimeout` milliseconds. This timeout has no effect once a socket * connection has been established. * * **timeout** [Integer] — Sets the socket to timeout after timeout * milliseconds of inactivity on the socket. Defaults to two minutes * (120000). * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous * HTTP requests. Used in the browser environment only. Set to false to * send requests synchronously. Defaults to true (async on). * * **xhrWithCredentials** [Boolean] — Sets the "withCredentials" * property of an XMLHttpRequest object. Used in the browser environment * only. Defaults to false. * @option options apiVersion [String, Date] a String in YYYY-MM-DD format * (or a date) that represents the latest possible API version that can be * used in all services (unless overridden by `apiVersions`). Specify * 'latest' to use the latest possible version. * @option options apiVersions [map] a map of service * identifiers (the lowercase service class name) with the API version to * use when instantiating a service. Specify 'latest' for each individual * that can use the latest available version. * @option options logger [#write,#log] an object that responds to .write() * (like a stream) or .log() (like the console object) in order to log * information about requests * @option options systemClockOffset [Number] an offset value in milliseconds * to apply to all signing times. Use this to compensate for clock skew * when your system may be out of sync with the service time. Note that * this configuration option can only be applied to the global `AWS.config` * object and cannot be overridden in service-specific configuration. * Defaults to 0 milliseconds. * @option options signatureVersion [String] the signature version to sign * requests with (overriding the API configuration). Possible values are: * 'v2', 'v3', 'v4'. * @option options signatureCache [Boolean] whether the signature to sign * requests with (overriding the API configuration) is cached. Only applies * to the signature version 'v4'. Defaults to `true`. * @option options dynamoDbCrc32 [Boolean] whether to validate the CRC32 * checksum of HTTP response bodies returned by DynamoDB. Default: `true`. * @option options useAccelerateEndpoint [Boolean] Whether to use the * S3 Transfer Acceleration endpoint with the S3 service. Default: `false`. * @option options clientSideMonitoring [Boolean] whether to collect and * publish this client's performance metrics of all its API requests. * @option options endpointDiscoveryEnabled [Boolean|undefined] whether to * call operations with endpoints given by service dynamically. Setting this * config to `true` will enable endpoint discovery for all applicable operations. * Setting it to `false` will explicitly disable endpoint discovery even though * operations that require endpoint discovery will presumably fail. Leaving it * to `undefined` means SDK will only do endpoint discovery when it's required. * Defaults to `undefined` * @option options endpointCacheSize [Number] the size of the global cache storing * endpoints from endpoint discovery operations. Once endpoint cache is created, * updating this setting cannot change existing cache size. * Defaults to 1000 * @option options hostPrefixEnabled [Boolean] whether to marshal request * parameters to the prefix of hostname. * Defaults to `true`. * @option options stsRegionalEndpoints ['legacy'|'regional'] whether to send sts request * to global endpoints or regional endpoints. * Defaults to 'legacy'. * @option options useFipsEndpoint [Boolean] Enables FIPS compatible endpoints. * Defaults to `false`. * @option options useDualstackEndpoint [Boolean] Enables IPv6 dualstack endpoint. * Defaults to `false`. */constructor:function Config(options){if(options===undefined)options={};options=this.extractCredentials(options);AWS.util.each.call(this,this.keys,function(key,value){this.set(key,options[key],value);});},/** * @!group Managing Credentials *//** * Loads credentials from the configuration object. This is used internally * by the SDK to ensure that refreshable {Credentials} objects are properly * refreshed and loaded when sending a request. If you want to ensure that * your credentials are loaded prior to a request, you can use this method * directly to provide accurate credential data stored in the object. * * @note If you configure the SDK with static or environment credentials, * the credential data should already be present in {credentials} attribute. * This method is primarily necessary to load credentials from asynchronous * sources, or sources that can refresh credentials periodically. * @example Getting your access key * AWS.config.getCredentials(function(err) { * if (err) console.log(err.stack); // credentials not loaded * else console.log("Access Key:", AWS.config.credentials.accessKeyId); * }) * @callback callback function(err) * Called when the {credentials} have been properly set on the configuration * object. * * @param err [Error] if this is set, credentials were not successfully * loaded and this error provides information why. * @see credentials * @see Credentials */getCredentials:function getCredentials(callback){var self=this;function finish(err){callback(err,err?null:self.credentials);}function credError(msg,err){return new AWS.util.error(err||new Error(),{code:'CredentialsError',message:msg,name:'CredentialsError'});}function getAsyncCredentials(){self.credentials.get(function(err){if(err){var msg='Could not load credentials from '+self.credentials.constructor.name;err=credError(msg,err);}finish(err);});}function getStaticCredentials(){var err=null;if(!self.credentials.accessKeyId||!self.credentials.secretAccessKey){err=credError('Missing credentials');}finish(err);}if(self.credentials){if(typeof self.credentials.get==='function'){getAsyncCredentials();}else{// static credentials getStaticCredentials();}}else if(self.credentialProvider){self.credentialProvider.resolve(function(err,creds){if(err){err=credError('Could not load credentials from any providers',err);}self.credentials=creds;finish(err);});}else{finish(credError('No credentials to load'));}},/** * Loads token from the configuration object. This is used internally * by the SDK to ensure that refreshable {Token} objects are properly * refreshed and loaded when sending a request. If you want to ensure that * your token is loaded prior to a request, you can use this method * directly to provide accurate token data stored in the object. * * @note If you configure the SDK with static token, the token data should * already be present in {token} attribute. This method is primarily necessary * to load token from asynchronous sources, or sources that can refresh * token periodically. * @example Getting your access token * AWS.config.getToken(function(err) { * if (err) console.log(err.stack); // token not loaded * else console.log("Token:", AWS.config.token.token); * }) * @callback callback function(err) * Called when the {token} have been properly set on the configuration object. * * @param err [Error] if this is set, token was not successfully loaded and * this error provides information why. * @see token */getToken:function getToken(callback){var self=this;function finish(err){callback(err,err?null:self.token);}function tokenError(msg,err){return new AWS.util.error(err||new Error(),{code:'TokenError',message:msg,name:'TokenError'});}function getAsyncToken(){self.token.get(function(err){if(err){var msg='Could not load token from '+self.token.constructor.name;err=tokenError(msg,err);}finish(err);});}function getStaticToken(){var err=null;if(!self.token.token){err=tokenError('Missing token');}finish(err);}if(self.token){if(typeof self.token.get==='function'){getAsyncToken();}else{// static token getStaticToken();}}else if(self.tokenProvider){self.tokenProvider.resolve(function(err,token){if(err){err=tokenError('Could not load token from any providers',err);}self.token=token;finish(err);});}else{finish(tokenError('No token to load'));}},/** * @!group Loading and Setting Configuration Options *//** * @overload update(options, allowUnknownKeys = false) * Updates the current configuration object with new options. * * @example Update maxRetries property of a configuration object * config.update({maxRetries: 10}); * @param [Object] options a map of option keys and values. * @param [Boolean] allowUnknownKeys whether unknown keys can be set on * the configuration object. Defaults to `false`. * @see constructor */update:function update(options,allowUnknownKeys){allowUnknownKeys=allowUnknownKeys||false;options=this.extractCredentials(options);AWS.util.each.call(this,options,function(key,value){if(allowUnknownKeys||Object.prototype.hasOwnProperty.call(this.keys,key)||AWS.Service.hasService(key)){this.set(key,value);}});},/** * Loads configuration data from a JSON file into this config object. * @note Loading configuration will reset all existing configuration * on the object. * @!macro nobrowser * @param path [String] the path relative to your process's current * working directory to load configuration from. * @return [AWS.Config] the same configuration object */loadFromPath:function loadFromPath(path){this.clear();var options=JSON.parse(AWS.util.readFileSync(path));var fileSystemCreds=new AWS.FileSystemCredentials(path);var chain=new AWS.CredentialProviderChain();chain.providers.unshift(fileSystemCreds);chain.resolve(function(err,creds){if(err)throw err;else options.credentials=creds;});this.constructor(options);return this;},/** * Clears configuration data on this object * * @api private */clear:function clear(){/*jshint forin:false */AWS.util.each.call(this,this.keys,function(key){delete this[key];});// reset credential provider this.set('credentials',undefined);this.set('credentialProvider',undefined);},/** * Sets a property on the configuration object, allowing for a * default value * @api private */set:function set(property,value,defaultValue){if(value===undefined){if(defaultValue===undefined){defaultValue=this.keys[property];}if(typeof defaultValue==='function'){this[property]=defaultValue.call(this);}else{this[property]=defaultValue;}}else if(property==='httpOptions'&&this[property]){// deep merge httpOptions this[property]=AWS.util.merge(this[property],value);}else{this[property]=value;}},/** * All of the keys with their default values. * * @constant * @api private */keys:{credentials:null,credentialProvider:null,region:null,logger:null,apiVersions:{},apiVersion:null,endpoint:undefined,httpOptions:{timeout:120000},maxRetries:undefined,maxRedirects:10,paramValidation:true,sslEnabled:true,s3ForcePathStyle:false,s3BucketEndpoint:false,s3DisableBodySigning:true,s3UsEast1RegionalEndpoint:'legacy',s3UseArnRegion:undefined,computeChecksums:true,convertResponseTypes:true,correctClockSkew:false,customUserAgent:null,dynamoDbCrc32:true,systemClockOffset:0,signatureVersion:null,signatureCache:true,retryDelayOptions:{},useAccelerateEndpoint:false,clientSideMonitoring:false,endpointDiscoveryEnabled:undefined,endpointCacheSize:1000,hostPrefixEnabled:true,stsRegionalEndpoints:'legacy',useFipsEndpoint:false,useDualstackEndpoint:false,token:null},/** * Extracts accessKeyId, secretAccessKey and sessionToken * from a configuration hash. * * @api private */extractCredentials:function extractCredentials(options){if(options.accessKeyId&&options.secretAccessKey){options=AWS.util.copy(options);options.credentials=new AWS.Credentials(options);}return options;},/** * Sets the promise dependency the SDK will use wherever Promises are returned. * Passing `null` will force the SDK to use native Promises if they are available. * If native Promises are not available, passing `null` will have no effect. * @param [Constructor] dep A reference to a Promise constructor */setPromisesDependency:function setPromisesDependency(dep){PromisesDependency=dep;// if null was passed in, we should try to use native promises if(dep===null&&typeof Promise==='function'){PromisesDependency=Promise;}var constructors=[AWS.Request,AWS.Credentials,AWS.CredentialProviderChain];if(AWS.S3){constructors.push(AWS.S3);if(AWS.S3.ManagedUpload){constructors.push(AWS.S3.ManagedUpload);}}AWS.util.addPromises(constructors,PromisesDependency);},/** * Gets the promise dependency set by `AWS.config.setPromisesDependency`. */getPromisesDependency:function getPromisesDependency(){return PromisesDependency;}});/** * @return [AWS.Config] The global configuration object singleton instance * @readonly * @see AWS.Config */AWS.config=new AWS.Config();},{"./core":19,"./credentials":20,"./credentials/credential_provider_chain":23}],18:[function(require,module,exports){(function(process){(function(){var AWS=require('./core');/** * @api private */function validateRegionalEndpointsFlagValue(configValue,errorOptions){if(typeof configValue!=='string')return undefined;else if(['legacy','regional'].indexOf(configValue.toLowerCase())>=0){return configValue.toLowerCase();}else{throw AWS.util.error(new Error(),errorOptions);}}/** * Resolve the configuration value for regional endpoint from difference sources: client * config, environmental variable, shared config file. Value can be case-insensitive * 'legacy' or 'reginal'. * @param originalConfig user-supplied config object to resolve * @param options a map of config property names from individual configuration source * - env: name of environmental variable that refers to the config * - sharedConfig: name of shared configuration file property that refers to the config * - clientConfig: name of client configuration property that refers to the config * * @api private */function resolveRegionalEndpointsFlag(originalConfig,options){originalConfig=originalConfig||{};//validate config value var resolved;if(originalConfig[options.clientConfig]){resolved=validateRegionalEndpointsFlagValue(originalConfig[options.clientConfig],{code:'InvalidConfiguration',message:'invalid "'+options.clientConfig+'" configuration. Expect "legacy" '+' or "regional". Got "'+originalConfig[options.clientConfig]+'".'});if(resolved)return resolved;}if(!AWS.util.isNode())return resolved;//validate environmental variable if(Object.prototype.hasOwnProperty.call(process.env,options.env)){var envFlag=process.env[options.env];resolved=validateRegionalEndpointsFlagValue(envFlag,{code:'InvalidEnvironmentalVariable',message:'invalid '+options.env+' environmental variable. Expect "legacy" '+' or "regional". Got "'+process.env[options.env]+'".'});if(resolved)return resolved;}//validate shared config file var profile={};try{var profiles=AWS.util.getProfilesFromSharedConfig(AWS.util.iniLoader);profile=profiles[process.env.AWS_PROFILE||AWS.util.defaultProfile];}catch(e){};if(profile&&Object.prototype.hasOwnProperty.call(profile,options.sharedConfig)){var fileFlag=profile[options.sharedConfig];resolved=validateRegionalEndpointsFlagValue(fileFlag,{code:'InvalidConfiguration',message:'invalid '+options.sharedConfig+' profile config. Expect "legacy" '+' or "regional". Got "'+profile[options.sharedConfig]+'".'});if(resolved)return resolved;}return resolved;}module.exports=resolveRegionalEndpointsFlag;}).call(this);}).call(this,require('_process'));},{"./core":19,"_process":91}],19:[function(require,module,exports){/** * The main AWS namespace */var AWS={util:require('./util')};/** * @api private * @!macro [new] nobrowser * @note This feature is not supported in the browser environment of the SDK. */var _hidden={};_hidden.toString();// hack to parse macro /** * @api private */module.exports=AWS;AWS.util.update(AWS,{/** * @constant */VERSION:'2.1589.0',/** * @api private */Signers:{},/** * @api private */Protocol:{Json:require('./protocol/json'),Query:require('./protocol/query'),Rest:require('./protocol/rest'),RestJson:require('./protocol/rest_json'),RestXml:require('./protocol/rest_xml')},/** * @api private */XML:{Builder:require('./xml/builder'),Parser:null// conditionally set based on environment },/** * @api private */JSON:{Builder:require('./json/builder'),Parser:require('./json/parser')},/** * @api private */Model:{Api:require('./model/api'),Operation:require('./model/operation'),Shape:require('./model/shape'),Paginator:require('./model/paginator'),ResourceWaiter:require('./model/resource_waiter')},/** * @api private */apiLoader:require('./api_loader'),/** * @api private */EndpointCache:require('../vendor/endpoint-cache').EndpointCache});require('./sequential_executor');require('./service');require('./config');require('./http');require('./event_listeners');require('./request');require('./response');require('./resource_waiter');require('./signers/request_signer');require('./param_validator');require('./maintenance_mode_message');/** * @readonly * @return [AWS.SequentialExecutor] a collection of global event listeners that * are attached to every sent request. * @see AWS.Request AWS.Request for a list of events to listen for * @example Logging the time taken to send a request * AWS.events.on('send', function startSend(resp) { * resp.startTime = new Date().getTime(); * }).on('complete', function calculateTime(resp) { * var time = (new Date().getTime() - resp.startTime) / 1000; * console.log('Request took ' + time + ' seconds'); * }); * * new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds' */AWS.events=new AWS.SequentialExecutor();//create endpoint cache lazily AWS.util.memoizedProperty(AWS,'endpointCache',function(){return new AWS.EndpointCache(AWS.config.endpointCacheSize);},true);},{"../vendor/endpoint-cache":111,"./api_loader":9,"./config":17,"./event_listeners":34,"./http":35,"./json/builder":37,"./json/parser":38,"./maintenance_mode_message":39,"./model/api":40,"./model/operation":42,"./model/paginator":43,"./model/resource_waiter":44,"./model/shape":45,"./param_validator":46,"./protocol/json":48,"./protocol/query":49,"./protocol/rest":50,"./protocol/rest_json":51,"./protocol/rest_xml":52,"./request":58,"./resource_waiter":59,"./response":60,"./sequential_executor":61,"./service":62,"./signers/request_signer":66,"./util":74,"./xml/builder":76}],20:[function(require,module,exports){var AWS=require('./core');/** * Represents your AWS security credentials, specifically the * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}. * Creating a `Credentials` object allows you to pass around your * security information to configuration and service objects. * * Note that this class typically does not need to be constructed manually, * as the {AWS.Config} and {AWS.Service} classes both accept simple * options hashes with the three keys. These structures will be converted * into Credentials objects automatically. * * ## Expiring and Refreshing Credentials * * Occasionally credentials can expire in the middle of a long-running * application. In this case, the SDK will automatically attempt to * refresh the credentials from the storage location if the Credentials * class implements the {refresh} method. * * If you are implementing a credential storage location, you * will want to create a subclass of the `Credentials` class and * override the {refresh} method. This method allows credentials to be * retrieved from the backing store, be it a file system, database, or * some network storage. The method should reset the credential attributes * on the object. * * @!attribute expired * @return [Boolean] whether the credentials have been expired and * require a refresh. Used in conjunction with {expireTime}. * @!attribute expireTime * @return [Date] a time when credentials should be considered expired. Used * in conjunction with {expired}. * @!attribute accessKeyId * @return [String] the AWS access key ID * @!attribute secretAccessKey * @return [String] the AWS secret access key * @!attribute sessionToken * @return [String] an optional AWS session token */AWS.Credentials=AWS.util.inherit({/** * A credentials object can be created using positional arguments or an options * hash. * * @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null) * Creates a Credentials object with a given set of credential information * as positional arguments. * @param accessKeyId [String] the AWS access key ID * @param secretAccessKey [String] the AWS secret access key * @param sessionToken [String] the optional AWS session token * @example Create a credentials object with AWS credentials * var creds = new AWS.Credentials('akid', 'secret', 'session'); * @overload AWS.Credentials(options) * Creates a Credentials object with a given set of credential information * as an options hash. * @option options accessKeyId [String] the AWS access key ID * @option options secretAccessKey [String] the AWS secret access key * @option options sessionToken [String] the optional AWS session token * @example Create a credentials object with AWS credentials * var creds = new AWS.Credentials({ * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session' * }); */constructor:function Credentials(){// hide secretAccessKey from being displayed with util.inspect AWS.util.hideProperties(this,['secretAccessKey']);this.expired=false;this.expireTime=null;this.refreshCallbacks=[];if(arguments.length===1&&_typeof(arguments[0])==='object'){var creds=arguments[0].credentials||arguments[0];this.accessKeyId=creds.accessKeyId;this.secretAccessKey=creds.secretAccessKey;this.sessionToken=creds.sessionToken;}else{this.accessKeyId=arguments[0];this.secretAccessKey=arguments[1];this.sessionToken=arguments[2];}},/** * @return [Integer] the number of seconds before {expireTime} during which * the credentials will be considered expired. */expiryWindow:15,/** * @return [Boolean] whether the credentials object should call {refresh} * @note Subclasses should override this method to provide custom refresh * logic. */needsRefresh:function needsRefresh(){var currentTime=AWS.util.date.getDate().getTime();var adjustedTime=new Date(currentTime+this.expiryWindow*1000);if(this.expireTime&&adjustedTime>this.expireTime){return true;}else{return this.expired||!this.accessKeyId||!this.secretAccessKey;}},/** * Gets the existing credentials, refreshing them if they are not yet loaded * or have expired. Users should call this method before using {refresh}, * as this will not attempt to reload credentials when they are already * loaded into the object. * * @callback callback function(err) * When this callback is called with no error, it means either credentials * do not need to be refreshed or refreshed credentials information has * been loaded into the object (as the `accessKeyId`, `secretAccessKey`, * and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled */get:function get(callback){var self=this;if(this.needsRefresh()){this.refresh(function(err){if(!err)self.expired=false;// reset expired flag if(callback)callback(err);});}else if(callback){callback();}},/** * @!method getPromise() * Returns a 'thenable' promise. * Gets the existing credentials, refreshing them if they are not yet loaded * or have expired. Users should call this method before using {refresh}, * as this will not attempt to reload credentials when they are already * loaded into the object. * * Two callbacks can be provided to the `then` method on the returned promise. * The first callback will be called if the promise is fulfilled, and the second * callback will be called if the promise is rejected. * @callback fulfilledCallback function() * Called if the promise is fulfilled. When this callback is called, it * means either credentials do not need to be refreshed or refreshed * credentials information has been loaded into the object (as the * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). * @callback rejectedCallback function(err) * Called if the promise is rejected. * @param err [Error] if an error occurred, this value will be filled * @return [Promise] A promise that represents the state of the `get` call. * @example Calling the `getPromise` method. * var promise = credProvider.getPromise(); * promise.then(function() { ... }, function(err) { ... }); *//** * @!method refreshPromise() * Returns a 'thenable' promise. * Refreshes the credentials. Users should call {get} before attempting * to forcibly refresh credentials. * * Two callbacks can be provided to the `then` method on the returned promise. * The first callback will be called if the promise is fulfilled, and the second * callback will be called if the promise is rejected. * @callback fulfilledCallback function() * Called if the promise is fulfilled. When this callback is called, it * means refreshed credentials information has been loaded into the object * (as the `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). * @callback rejectedCallback function(err) * Called if the promise is rejected. * @param err [Error] if an error occurred, this value will be filled * @return [Promise] A promise that represents the state of the `refresh` call. * @example Calling the `refreshPromise` method. * var promise = credProvider.refreshPromise(); * promise.then(function() { ... }, function(err) { ... }); *//** * Refreshes the credentials. Users should call {get} before attempting * to forcibly refresh credentials. * * @callback callback function(err) * When this callback is called with no error, it means refreshed * credentials information has been loaded into the object (as the * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @note Subclasses should override this class to reset the * {accessKeyId}, {secretAccessKey} and optional {sessionToken} * on the credentials object and then call the callback with * any error information. * @see get */refresh:function refresh(callback){this.expired=false;callback();},/** * @api private * @param callback */coalesceRefresh:function coalesceRefresh(callback,sync){var self=this;if(self.refreshCallbacks.push(callback)===1){self.load(function onLoad(err){AWS.util.arrayEach(self.refreshCallbacks,function(callback){if(sync){callback(err);}else{// callback could throw, so defer to ensure all callbacks are notified AWS.util.defer(function(){callback(err);});}});self.refreshCallbacks.length=0;});}},/** * @api private * @param callback */load:function load(callback){callback();}});/** * @api private */AWS.Credentials.addPromisesToClass=function addPromisesToClass(PromiseDependency){this.prototype.getPromise=AWS.util.promisifyMethod('get',PromiseDependency);this.prototype.refreshPromise=AWS.util.promisifyMethod('refresh',PromiseDependency);};/** * @api private */AWS.Credentials.deletePromisesFromClass=function deletePromisesFromClass(){delete this.prototype.getPromise;delete this.prototype.refreshPromise;};AWS.util.addPromises(AWS.Credentials);},{"./core":19}],21:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** * Represents temporary credentials retrieved from {AWS.STS}. Without any * extra parameters, credentials will be fetched from the * {AWS.STS.getSessionToken} operation. If an IAM role is provided, the * {AWS.STS.assumeRole} operation will be used to fetch credentials for the * role instead. * * AWS.ChainableTemporaryCredentials differs from AWS.TemporaryCredentials in * the way masterCredentials and refreshes are handled. * AWS.ChainableTemporaryCredentials refreshes expired credentials using the * masterCredentials passed by the user to support chaining of STS credentials. * However, AWS.TemporaryCredentials recursively collapses the masterCredentials * during instantiation, precluding the ability to refresh credentials which * require intermediate, temporary credentials. * * For example, if the application should use RoleA, which must be assumed from * RoleB, and the environment provides credentials which can assume RoleB, then * AWS.ChainableTemporaryCredentials must be used to support refreshing the * temporary credentials for RoleA: * * ```javascript * var roleACreds = new AWS.ChainableTemporaryCredentials({ * params: {RoleArn: 'RoleA'}, * masterCredentials: new AWS.ChainableTemporaryCredentials({ * params: {RoleArn: 'RoleB'}, * masterCredentials: new AWS.EnvironmentCredentials('AWS') * }) * }); * ``` * * If AWS.TemporaryCredentials had been used in the previous example, * `roleACreds` would fail to refresh because `roleACreds` would * use the environment credentials for the AssumeRole request. * * Another difference is that AWS.ChainableTemporaryCredentials creates the STS * service instance during instantiation while AWS.TemporaryCredentials creates * the STS service instance during the first refresh. Creating the service * instance during instantiation effectively captures the master credentials * from the global config, so that subsequent changes to the global config do * not affect the master credentials used to refresh the temporary credentials. * * This allows an instance of AWS.ChainableTemporaryCredentials to be assigned * to AWS.config.credentials: * * ```javascript * var envCreds = new AWS.EnvironmentCredentials('AWS'); * AWS.config.credentials = envCreds; * // masterCredentials will be envCreds * AWS.config.credentials = new AWS.ChainableTemporaryCredentials({ * params: {RoleArn: '...'} * }); * ``` * * Similarly, to use the CredentialProviderChain's default providers as the * master credentials, simply create a new instance of * AWS.ChainableTemporaryCredentials: * * ```javascript * AWS.config.credentials = new ChainableTemporaryCredentials({ * params: {RoleArn: '...'} * }); * ``` * * @!attribute service * @return [AWS.STS] the STS service instance used to * get and refresh temporary credentials from AWS STS. * @note (see constructor) */AWS.ChainableTemporaryCredentials=AWS.util.inherit(AWS.Credentials,{/** * Creates a new temporary credentials object. * * @param options [map] a set of options * @option options params [map] ({}) a map of options that are passed to the * {AWS.STS.assumeRole} or {AWS.STS.getSessionToken} operations. * If a `RoleArn` parameter is passed in, credentials will be based on the * IAM role. If a `SerialNumber` parameter is passed in, {tokenCodeFn} must * also be passed in or an error will be thrown. * @option options masterCredentials [AWS.Credentials] the master credentials * used to get and refresh temporary credentials from AWS STS. By default, * AWS.config.credentials or AWS.config.credentialProvider will be used. * @option options tokenCodeFn [Function] (null) Function to provide * `TokenCode`, if `SerialNumber` is provided for profile in {params}. Function * is called with value of `SerialNumber` and `callback`, and should provide * the `TokenCode` or an error to the callback in the format * `callback(err, token)`. * @example Creating a new credentials object for generic temporary credentials * AWS.config.credentials = new AWS.ChainableTemporaryCredentials(); * @example Creating a new credentials object for an IAM role * AWS.config.credentials = new AWS.ChainableTemporaryCredentials({ * params: { * RoleArn: 'arn:aws:iam::1234567890:role/TemporaryCredentials' * } * }); * @see AWS.STS.assumeRole * @see AWS.STS.getSessionToken */constructor:function ChainableTemporaryCredentials(options){AWS.Credentials.call(this);options=options||{};this.errorCode='ChainableTemporaryCredentialsProviderFailure';this.expired=true;this.tokenCodeFn=null;var params=AWS.util.copy(options.params)||{};if(params.RoleArn){params.RoleSessionName=params.RoleSessionName||'temporary-credentials';}if(params.SerialNumber){if(!options.tokenCodeFn||typeof options.tokenCodeFn!=='function'){throw new AWS.util.error(new Error('tokenCodeFn must be a function when params.SerialNumber is given'),{code:this.errorCode});}else{this.tokenCodeFn=options.tokenCodeFn;}}var config=AWS.util.merge({params:params,credentials:options.masterCredentials||AWS.config.credentials},options.stsConfig||{});this.service=new STS(config);},/** * Refreshes credentials using {AWS.STS.assumeRole} or * {AWS.STS.getSessionToken}, depending on whether an IAM role ARN was passed * to the credentials {constructor}. * * @callback callback function(err) * Called when the STS service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see AWS.Credentials.get */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private * @param callback */load:function load(callback){var self=this;var operation=self.service.config.params.RoleArn?'assumeRole':'getSessionToken';this.getTokenCode(function(err,tokenCode){var params={};if(err){callback(err);return;}if(tokenCode){params.TokenCode=tokenCode;}self.service[operation](params,function(err,data){if(!err){self.service.credentialsFrom(data,self);}callback(err);});});},/** * @api private */getTokenCode:function getTokenCode(callback){var self=this;if(this.tokenCodeFn){this.tokenCodeFn(this.service.config.params.SerialNumber,function(err,token){if(err){var message=err;if(err instanceof Error){message=err.message;}callback(AWS.util.error(new Error('Error fetching MFA token: '+message),{code:self.errorCode}));return;}callback(null,token);});}else{callback(null);}}});},{"../../clients/sts":8,"../core":19}],22:[function(require,module,exports){var AWS=require('../core');var CognitoIdentity=require('../../clients/cognitoidentity');var STS=require('../../clients/sts');/** * Represents credentials retrieved from STS Web Identity Federation using * the Amazon Cognito Identity service. * * By default this provider gets credentials using the * {AWS.CognitoIdentity.getCredentialsForIdentity} service operation, which * requires either an `IdentityId` or an `IdentityPoolId` (Amazon Cognito * Identity Pool ID), which is used to call {AWS.CognitoIdentity.getId} to * obtain an `IdentityId`. If the identity or identity pool is not configured in * the Amazon Cognito Console to use IAM roles with the appropriate permissions, * then additionally a `RoleArn` is required containing the ARN of the IAM trust * policy for the Amazon Cognito role that the user will log into. If a `RoleArn` * is provided, then this provider gets credentials using the * {AWS.STS.assumeRoleWithWebIdentity} service operation, after first getting an * Open ID token from {AWS.CognitoIdentity.getOpenIdToken}. * * In addition, if this credential provider is used to provide authenticated * login, the `Logins` map may be set to the tokens provided by the respective * identity providers. See {constructor} for an example on creating a credentials * object with proper property values. * * ## Refreshing Credentials from Identity Service * * In addition to AWS credentials expiring after a given amount of time, the * login token from the identity provider will also expire. Once this token * expires, it will not be usable to refresh AWS credentials, and another * token will be needed. The SDK does not manage refreshing of the token value, * but this can be done through a "refresh token" supported by most identity * providers. Consult the documentation for the identity provider for refreshing * tokens. Once the refreshed token is acquired, you should make sure to update * this new token in the credentials object's {params} property. The following * code will update the WebIdentityToken, assuming you have retrieved an updated * token from the identity provider: * * ```javascript * AWS.config.credentials.params.Logins['graph.facebook.com'] = updatedToken; * ``` * * Future calls to `credentials.refresh()` will now use the new token. * * @!attribute params * @return [map] the map of params passed to * {AWS.CognitoIdentity.getId}, * {AWS.CognitoIdentity.getOpenIdToken}, and * {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the * `params.WebIdentityToken` property. * @!attribute data * @return [map] the raw data response from the call to * {AWS.CognitoIdentity.getCredentialsForIdentity}, or * {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get * access to other properties from the response. * @!attribute identityId * @return [String] the Cognito ID returned by the last call to * {AWS.CognitoIdentity.getOpenIdToken}. This ID represents the actual * final resolved identity ID from Amazon Cognito. */AWS.CognitoIdentityCredentials=AWS.util.inherit(AWS.Credentials,{/** * @api private */localStorageKey:{id:'aws.cognito.identity-id.',providers:'aws.cognito.identity-providers.'},/** * Creates a new credentials object. * @example Creating a new credentials object * AWS.config.credentials = new AWS.CognitoIdentityCredentials({ * * // either IdentityPoolId or IdentityId is required * // See the IdentityPoolId param for AWS.CognitoIdentity.getID (linked below) * // See the IdentityId param for AWS.CognitoIdentity.getCredentialsForIdentity * // or AWS.CognitoIdentity.getOpenIdToken (linked below) * IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030', * IdentityId: 'us-east-1:128d0a74-c82f-4553-916d-90053e4a8b0f' * * // optional, only necessary when the identity pool is not configured * // to use IAM roles in the Amazon Cognito Console * // See the RoleArn param for AWS.STS.assumeRoleWithWebIdentity (linked below) * RoleArn: 'arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity', * * // optional tokens, used for authenticated login * // See the Logins param for AWS.CognitoIdentity.getID (linked below) * Logins: { * 'graph.facebook.com': 'FBTOKEN', * 'www.amazon.com': 'AMAZONTOKEN', * 'accounts.google.com': 'GOOGLETOKEN', * 'api.twitter.com': 'TWITTERTOKEN', * 'www.digits.com': 'DIGITSTOKEN' * }, * * // optional name, defaults to web-identity * // See the RoleSessionName param for AWS.STS.assumeRoleWithWebIdentity (linked below) * RoleSessionName: 'web', * * // optional, only necessary when application runs in a browser * // and multiple users are signed in at once, used for caching * LoginId: 'example@gmail.com' * * }, { * // optionally provide configuration to apply to the underlying service clients * // if configuration is not provided, then configuration will be pulled from AWS.config * * // region should match the region your identity pool is located in * region: 'us-east-1', * * // specify timeout options * httpOptions: { * timeout: 100 * } * }); * @see AWS.CognitoIdentity.getId * @see AWS.CognitoIdentity.getCredentialsForIdentity * @see AWS.STS.assumeRoleWithWebIdentity * @see AWS.CognitoIdentity.getOpenIdToken * @see AWS.Config * @note If a region is not provided in the global AWS.config, or * specified in the `clientConfig` to the CognitoIdentityCredentials * constructor, you may encounter a 'Missing credentials in config' error * when calling making a service call. */constructor:function CognitoIdentityCredentials(params,clientConfig){AWS.Credentials.call(this);this.expired=true;this.params=params;this.data=null;this._identityId=null;this._clientConfig=AWS.util.copy(clientConfig||{});this.loadCachedId();var self=this;Object.defineProperty(this,'identityId',{get:function get(){self.loadCachedId();return self._identityId||self.params.IdentityId;},set:function set(identityId){self._identityId=identityId;}});},/** * Refreshes credentials using {AWS.CognitoIdentity.getCredentialsForIdentity}, * or {AWS.STS.assumeRoleWithWebIdentity}. * * @callback callback function(err) * Called when the STS service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see AWS.Credentials.get */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private * @param callback */load:function load(callback){var self=this;self.createClients();self.data=null;self._identityId=null;self.getId(function(err){if(!err){if(!self.params.RoleArn){self.getCredentialsForIdentity(callback);}else{self.getCredentialsFromSTS(callback);}}else{self.clearIdOnNotAuthorized(err);callback(err);}});},/** * Clears the cached Cognito ID associated with the currently configured * identity pool ID. Use this to manually invalidate your cache if * the identity pool ID was deleted. */clearCachedId:function clearCache(){this._identityId=null;delete this.params.IdentityId;var poolId=this.params.IdentityPoolId;var loginId=this.params.LoginId||'';delete this.storage[this.localStorageKey.id+poolId+loginId];delete this.storage[this.localStorageKey.providers+poolId+loginId];},/** * @api private */clearIdOnNotAuthorized:function clearIdOnNotAuthorized(err){var self=this;if(err.code=='NotAuthorizedException'){self.clearCachedId();}},/** * Retrieves a Cognito ID, loading from cache if it was already retrieved * on this device. * * @callback callback function(err, identityId) * @param err [Error, null] an error object if the call failed or null if * it succeeded. * @param identityId [String, null] if successful, the callback will return * the Cognito ID. * @note If not loaded explicitly, the Cognito ID is loaded and stored in * localStorage in the browser environment of a device. * @api private */getId:function getId(callback){var self=this;if(typeof self.params.IdentityId==='string'){return callback(null,self.params.IdentityId);}self.cognito.getId(function(err,data){if(!err&&data.IdentityId){self.params.IdentityId=data.IdentityId;callback(null,data.IdentityId);}else{callback(err);}});},/** * @api private */loadCredentials:function loadCredentials(data,credentials){if(!data||!credentials)return;credentials.expired=false;credentials.accessKeyId=data.Credentials.AccessKeyId;credentials.secretAccessKey=data.Credentials.SecretKey;credentials.sessionToken=data.Credentials.SessionToken;credentials.expireTime=data.Credentials.Expiration;},/** * @api private */getCredentialsForIdentity:function getCredentialsForIdentity(callback){var self=this;self.cognito.getCredentialsForIdentity(function(err,data){if(!err){self.cacheId(data);self.data=data;self.loadCredentials(self.data,self);}else{self.clearIdOnNotAuthorized(err);}callback(err);});},/** * @api private */getCredentialsFromSTS:function getCredentialsFromSTS(callback){var self=this;self.cognito.getOpenIdToken(function(err,data){if(!err){self.cacheId(data);self.params.WebIdentityToken=data.Token;self.webIdentityCredentials.refresh(function(webErr){if(!webErr){self.data=self.webIdentityCredentials.data;self.sts.credentialsFrom(self.data,self);}callback(webErr);});}else{self.clearIdOnNotAuthorized(err);callback(err);}});},/** * @api private */loadCachedId:function loadCachedId(){var self=this;// in the browser we source default IdentityId from localStorage if(AWS.util.isBrowser()&&!self.params.IdentityId){var id=self.getStorage('id');if(id&&self.params.Logins){var actualProviders=Object.keys(self.params.Logins);var cachedProviders=(self.getStorage('providers')||'').split(',');// only load ID if at least one provider used this ID before var intersect=cachedProviders.filter(function(n){return actualProviders.indexOf(n)!==-1;});if(intersect.length!==0){self.params.IdentityId=id;}}else if(id){self.params.IdentityId=id;}}},/** * @api private */createClients:function createClients(){var clientConfig=this._clientConfig;this.webIdentityCredentials=this.webIdentityCredentials||new AWS.WebIdentityCredentials(this.params,clientConfig);if(!this.cognito){var cognitoConfig=AWS.util.merge({},clientConfig);cognitoConfig.params=this.params;this.cognito=new CognitoIdentity(cognitoConfig);}this.sts=this.sts||new STS(clientConfig);},/** * @api private */cacheId:function cacheId(data){this._identityId=data.IdentityId;this.params.IdentityId=this._identityId;// cache this IdentityId in browser localStorage if possible if(AWS.util.isBrowser()){this.setStorage('id',data.IdentityId);if(this.params.Logins){this.setStorage('providers',Object.keys(this.params.Logins).join(','));}}},/** * @api private */getStorage:function getStorage(key){return this.storage[this.localStorageKey[key]+this.params.IdentityPoolId+(this.params.LoginId||'')];},/** * @api private */setStorage:function setStorage(key,val){try{this.storage[this.localStorageKey[key]+this.params.IdentityPoolId+(this.params.LoginId||'')]=val;}catch(_){}},/** * @api private */storage:function(){try{var storage=AWS.util.isBrowser()&&window.localStorage!==null&&_typeof(window.localStorage)==='object'?window.localStorage:{};// Test set/remove which would throw an error in Safari's private browsing storage['aws.test-storage']='foobar';delete storage['aws.test-storage'];return storage;}catch(_){return{};}}()});},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":19}],23:[function(require,module,exports){var AWS=require('../core');/** * Creates a credential provider chain that searches for AWS credentials * in a list of credential providers specified by the {providers} property. * * By default, the chain will use the {defaultProviders} to resolve credentials. * These providers will look in the environment using the * {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes. * * ## Setting Providers * * Each provider in the {providers} list should be a function that returns * a {AWS.Credentials} object, or a hardcoded credentials object. The function * form allows for delayed execution of the credential construction. * * ## Resolving Credentials from a Chain * * Call {resolve} to return the first valid credential object that can be * loaded by the provider chain. * * For example, to resolve a chain with a custom provider that checks a file * on disk after the set of {defaultProviders}: * * ```javascript * var diskProvider = new AWS.FileSystemCredentials('./creds.json'); * var chain = new AWS.CredentialProviderChain(); * chain.providers.push(diskProvider); * chain.resolve(); * ``` * * The above code will return the `diskProvider` object if the * file contains credentials and the `defaultProviders` do not contain * any credential settings. * * @!attribute providers * @return [Array] * a list of credentials objects or functions that return credentials * objects. If the provider is a function, the function will be * executed lazily when the provider needs to be checked for valid * credentials. By default, this object will be set to the * {defaultProviders}. * @see defaultProviders */AWS.CredentialProviderChain=AWS.util.inherit(AWS.Credentials,{/** * Creates a new CredentialProviderChain with a default set of providers * specified by {defaultProviders}. */constructor:function CredentialProviderChain(providers){if(providers){this.providers=providers;}else{this.providers=AWS.CredentialProviderChain.defaultProviders.slice(0);}this.resolveCallbacks=[];},/** * @!method resolvePromise() * Returns a 'thenable' promise. * Resolves the provider chain by searching for the first set of * credentials in {providers}. * * Two callbacks can be provided to the `then` method on the returned promise. * The first callback will be called if the promise is fulfilled, and the second * callback will be called if the promise is rejected. * @callback fulfilledCallback function(credentials) * Called if the promise is fulfilled and the provider resolves the chain * to a credentials object * @param credentials [AWS.Credentials] the credentials object resolved * by the provider chain. * @callback rejectedCallback function(error) * Called if the promise is rejected. * @param err [Error] the error object returned if no credentials are found. * @return [Promise] A promise that represents the state of the `resolve` method call. * @example Calling the `resolvePromise` method. * var promise = chain.resolvePromise(); * promise.then(function(credentials) { ... }, function(err) { ... }); *//** * Resolves the provider chain by searching for the first set of * credentials in {providers}. * * @callback callback function(err, credentials) * Called when the provider resolves the chain to a credentials object * or null if no credentials can be found. * * @param err [Error] the error object returned if no credentials are * found. * @param credentials [AWS.Credentials] the credentials object resolved * by the provider chain. * @return [AWS.CredentialProviderChain] the provider, for chaining. */resolve:function resolve(callback){var self=this;if(self.providers.length===0){callback(new Error('No providers'));return self;}if(self.resolveCallbacks.push(callback)===1){var _resolveNext=function resolveNext(err,creds){if(!err&&creds||index===providers.length){AWS.util.arrayEach(self.resolveCallbacks,function(callback){callback(err,creds);});self.resolveCallbacks.length=0;return;}var provider=providers[index++];if(typeof provider==='function'){creds=provider.call();}else{creds=provider;}if(creds.get){creds.get(function(getErr){_resolveNext(getErr,getErr?null:creds);});}else{_resolveNext(null,creds);}};var index=0;var providers=self.providers.slice(0);_resolveNext();}return self;}});/** * The default set of providers used by a vanilla CredentialProviderChain. * * In the browser: * * ```javascript * AWS.CredentialProviderChain.defaultProviders = [] * ``` * * In Node.js: * * ```javascript * AWS.CredentialProviderChain.defaultProviders = [ * function () { return new AWS.EnvironmentCredentials('AWS'); }, * function () { return new AWS.EnvironmentCredentials('AMAZON'); }, * function () { return new AWS.SsoCredentials(); }, * function () { return new AWS.SharedIniFileCredentials(); }, * function () { return new AWS.ECSCredentials(); }, * function () { return new AWS.ProcessCredentials(); }, * function () { return new AWS.TokenFileWebIdentityCredentials(); }, * function () { return new AWS.EC2MetadataCredentials() } * ] * ``` */AWS.CredentialProviderChain.defaultProviders=[];/** * @api private */AWS.CredentialProviderChain.addPromisesToClass=function addPromisesToClass(PromiseDependency){this.prototype.resolvePromise=AWS.util.promisifyMethod('resolve',PromiseDependency);};/** * @api private */AWS.CredentialProviderChain.deletePromisesFromClass=function deletePromisesFromClass(){delete this.prototype.resolvePromise;};AWS.util.addPromises(AWS.CredentialProviderChain);},{"../core":19}],24:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** * Represents credentials retrieved from STS SAML support. * * By default this provider gets credentials using the * {AWS.STS.assumeRoleWithSAML} service operation. This operation * requires a `RoleArn` containing the ARN of the IAM trust policy for the * application for which credentials will be given, as well as a `PrincipalArn` * representing the ARN for the SAML identity provider. In addition, the * `SAMLAssertion` must be set to the token provided by the identity * provider. See {constructor} for an example on creating a credentials * object with proper `RoleArn`, `PrincipalArn`, and `SAMLAssertion` values. * * ## Refreshing Credentials from Identity Service * * In addition to AWS credentials expiring after a given amount of time, the * login token from the identity provider will also expire. Once this token * expires, it will not be usable to refresh AWS credentials, and another * token will be needed. The SDK does not manage refreshing of the token value, * but this can be done through a "refresh token" supported by most identity * providers. Consult the documentation for the identity provider for refreshing * tokens. Once the refreshed token is acquired, you should make sure to update * this new token in the credentials object's {params} property. The following * code will update the SAMLAssertion, assuming you have retrieved an updated * token from the identity provider: * * ```javascript * AWS.config.credentials.params.SAMLAssertion = updatedToken; * ``` * * Future calls to `credentials.refresh()` will now use the new token. * * @!attribute params * @return [map] the map of params passed to * {AWS.STS.assumeRoleWithSAML}. To update the token, set the * `params.SAMLAssertion` property. */AWS.SAMLCredentials=AWS.util.inherit(AWS.Credentials,{/** * Creates a new credentials object. * @param (see AWS.STS.assumeRoleWithSAML) * @example Creating a new credentials object * AWS.config.credentials = new AWS.SAMLCredentials({ * RoleArn: 'arn:aws:iam::1234567890:role/SAMLRole', * PrincipalArn: 'arn:aws:iam::1234567890:role/SAMLPrincipal', * SAMLAssertion: 'base64-token', // base64-encoded token from IdP * }); * @see AWS.STS.assumeRoleWithSAML */constructor:function SAMLCredentials(params){AWS.Credentials.call(this);this.expired=true;this.params=params;},/** * Refreshes credentials using {AWS.STS.assumeRoleWithSAML} * * @callback callback function(err) * Called when the STS service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see get */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private */load:function load(callback){var self=this;self.createClients();self.service.assumeRoleWithSAML(function(err,data){if(!err){self.service.credentialsFrom(data,self);}callback(err);});},/** * @api private */createClients:function createClients(){this.service=this.service||new STS({params:this.params});}});},{"../../clients/sts":8,"../core":19}],25:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** * Represents temporary credentials retrieved from {AWS.STS}. Without any * extra parameters, credentials will be fetched from the * {AWS.STS.getSessionToken} operation. If an IAM role is provided, the * {AWS.STS.assumeRole} operation will be used to fetch credentials for the * role instead. * * @note AWS.TemporaryCredentials is deprecated, but remains available for * backwards compatibility. {AWS.ChainableTemporaryCredentials} is the * preferred class for temporary credentials. * * To setup temporary credentials, configure a set of master credentials * using the standard credentials providers (environment, EC2 instance metadata, * or from the filesystem), then set the global credentials to a new * temporary credentials object: * * ```javascript * // Note that environment credentials are loaded by default, * // the following line is shown for clarity: * AWS.config.credentials = new AWS.EnvironmentCredentials('AWS'); * * // Now set temporary credentials seeded from the master credentials * AWS.config.credentials = new AWS.TemporaryCredentials(); * * // subsequent requests will now use temporary credentials from AWS STS. * new AWS.S3().listBucket(function(err, data) { ... }); * ``` * * @!attribute masterCredentials * @return [AWS.Credentials] the master (non-temporary) credentials used to * get and refresh temporary credentials from AWS STS. * @note (see constructor) */AWS.TemporaryCredentials=AWS.util.inherit(AWS.Credentials,{/** * Creates a new temporary credentials object. * * @note In order to create temporary credentials, you first need to have * "master" credentials configured in {AWS.Config.credentials}. These * master credentials are necessary to retrieve the temporary credentials, * as well as refresh the credentials when they expire. * @param params [map] a map of options that are passed to the * {AWS.STS.assumeRole} or {AWS.STS.getSessionToken} operations. * If a `RoleArn` parameter is passed in, credentials will be based on the * IAM role. * @param masterCredentials [AWS.Credentials] the master (non-temporary) credentials * used to get and refresh temporary credentials from AWS STS. * @example Creating a new credentials object for generic temporary credentials * AWS.config.credentials = new AWS.TemporaryCredentials(); * @example Creating a new credentials object for an IAM role * AWS.config.credentials = new AWS.TemporaryCredentials({ * RoleArn: 'arn:aws:iam::1234567890:role/TemporaryCredentials', * }); * @see AWS.STS.assumeRole * @see AWS.STS.getSessionToken */constructor:function TemporaryCredentials(params,masterCredentials){AWS.Credentials.call(this);this.loadMasterCredentials(masterCredentials);this.expired=true;this.params=params||{};if(this.params.RoleArn){this.params.RoleSessionName=this.params.RoleSessionName||'temporary-credentials';}},/** * Refreshes credentials using {AWS.STS.assumeRole} or * {AWS.STS.getSessionToken}, depending on whether an IAM role ARN was passed * to the credentials {constructor}. * * @callback callback function(err) * Called when the STS service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see get */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private */load:function load(callback){var self=this;self.createClients();self.masterCredentials.get(function(){self.service.config.credentials=self.masterCredentials;var operation=self.params.RoleArn?self.service.assumeRole:self.service.getSessionToken;operation.call(self.service,function(err,data){if(!err){self.service.credentialsFrom(data,self);}callback(err);});});},/** * @api private */loadMasterCredentials:function loadMasterCredentials(masterCredentials){this.masterCredentials=masterCredentials||AWS.config.credentials;while(this.masterCredentials.masterCredentials){this.masterCredentials=this.masterCredentials.masterCredentials;}if(typeof this.masterCredentials.get!=='function'){this.masterCredentials=new AWS.Credentials(this.masterCredentials);}},/** * @api private */createClients:function createClients(){this.service=this.service||new STS({params:this.params});}});},{"../../clients/sts":8,"../core":19}],26:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** * Represents credentials retrieved from STS Web Identity Federation support. * * By default this provider gets credentials using the * {AWS.STS.assumeRoleWithWebIdentity} service operation. This operation * requires a `RoleArn` containing the ARN of the IAM trust policy for the * application for which credentials will be given. In addition, the * `WebIdentityToken` must be set to the token provided by the identity * provider. See {constructor} for an example on creating a credentials * object with proper `RoleArn` and `WebIdentityToken` values. * * ## Refreshing Credentials from Identity Service * * In addition to AWS credentials expiring after a given amount of time, the * login token from the identity provider will also expire. Once this token * expires, it will not be usable to refresh AWS credentials, and another * token will be needed. The SDK does not manage refreshing of the token value, * but this can be done through a "refresh token" supported by most identity * providers. Consult the documentation for the identity provider for refreshing * tokens. Once the refreshed token is acquired, you should make sure to update * this new token in the credentials object's {params} property. The following * code will update the WebIdentityToken, assuming you have retrieved an updated * token from the identity provider: * * ```javascript * AWS.config.credentials.params.WebIdentityToken = updatedToken; * ``` * * Future calls to `credentials.refresh()` will now use the new token. * * @!attribute params * @return [map] the map of params passed to * {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the * `params.WebIdentityToken` property. * @!attribute data * @return [map] the raw data response from the call to * {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get * access to other properties from the response. */AWS.WebIdentityCredentials=AWS.util.inherit(AWS.Credentials,{/** * Creates a new credentials object. * @param (see AWS.STS.assumeRoleWithWebIdentity) * @example Creating a new credentials object * AWS.config.credentials = new AWS.WebIdentityCredentials({ * RoleArn: 'arn:aws:iam::1234567890:role/WebIdentity', * WebIdentityToken: 'ABCDEFGHIJKLMNOP', // token from identity service * RoleSessionName: 'web' // optional name, defaults to web-identity * }, { * // optionally provide configuration to apply to the underlying AWS.STS service client * // if configuration is not provided, then configuration will be pulled from AWS.config * * // specify timeout options * httpOptions: { * timeout: 100 * } * }); * @see AWS.STS.assumeRoleWithWebIdentity * @see AWS.Config */constructor:function WebIdentityCredentials(params,clientConfig){AWS.Credentials.call(this);this.expired=true;this.params=params;this.params.RoleSessionName=this.params.RoleSessionName||'web-identity';this.data=null;this._clientConfig=AWS.util.copy(clientConfig||{});},/** * Refreshes credentials using {AWS.STS.assumeRoleWithWebIdentity} * * @callback callback function(err) * Called when the STS service responds (or fails). When * this callback is called with no error, it means that the credentials * information has been loaded into the object (as the `accessKeyId`, * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see get */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private */load:function load(callback){var self=this;self.createClients();self.service.assumeRoleWithWebIdentity(function(err,data){self.data=null;if(!err){self.data=data;self.service.credentialsFrom(data,self);}callback(err);});},/** * @api private */createClients:function createClients(){if(!this.service){var stsConfig=AWS.util.merge({},this._clientConfig);stsConfig.params=this.params;this.service=new STS(stsConfig);}}});},{"../../clients/sts":8,"../core":19}],27:[function(require,module,exports){(function(process){(function(){var AWS=require('./core');var util=require('./util');var endpointDiscoveryEnabledEnvs=['AWS_ENABLE_ENDPOINT_DISCOVERY','AWS_ENDPOINT_DISCOVERY_ENABLED'];/** * Generate key (except resources and operation part) to index the endpoints in the cache * If input shape has endpointdiscoveryid trait then use * accessKey + operation + resources + region + service as cache key * If input shape doesn't have endpointdiscoveryid trait then use * accessKey + region + service as cache key * @return [map] object with keys to index endpoints. * @api private */function getCacheKey(request){var service=request.service;var api=service.api||{};var operations=api.operations;var identifiers={};if(service.config.region){identifiers.region=service.config.region;}if(api.serviceId){identifiers.serviceId=api.serviceId;}if(service.config.credentials.accessKeyId){identifiers.accessKeyId=service.config.credentials.accessKeyId;}return identifiers;}/** * Recursive helper for marshallCustomIdentifiers(). * Looks for required string input members that have 'endpointdiscoveryid' trait. * @api private */function marshallCustomIdentifiersHelper(result,params,shape){if(!shape||params===undefined||params===null)return;if(shape.type==='structure'&&shape.required&&shape.required.length>0){util.arrayEach(shape.required,function(name){var memberShape=shape.members[name];if(memberShape.endpointDiscoveryId===true){var locationName=memberShape.isLocationName?memberShape.name:name;result[locationName]=String(params[name]);}else{marshallCustomIdentifiersHelper(result,params[name],memberShape);}});}}/** * Get custom identifiers for cache key. * Identifies custom identifiers by checking each shape's `endpointDiscoveryId` trait. * @param [object] request object * @param [object] input shape of the given operation's api * @api private */function marshallCustomIdentifiers(request,shape){var identifiers={};marshallCustomIdentifiersHelper(identifiers,request.params,shape);return identifiers;}/** * Call endpoint discovery operation when it's optional. * When endpoint is available in cache then use the cached endpoints. If endpoints * are unavailable then use regional endpoints and call endpoint discovery operation * asynchronously. This is turned off by default. * @param [object] request object * @api private */function optionalDiscoverEndpoint(request){var service=request.service;var api=service.api;var operationModel=api.operations?api.operations[request.operation]:undefined;var inputShape=operationModel?operationModel.input:undefined;var identifiers=marshallCustomIdentifiers(request,inputShape);var cacheKey=getCacheKey(request);if(Object.keys(identifiers).length>0){cacheKey=util.update(cacheKey,identifiers);if(operationModel)cacheKey.operation=operationModel.name;}var endpoints=AWS.endpointCache.get(cacheKey);if(endpoints&&endpoints.length===1&&endpoints[0].Address===''){//endpoint operation is being made but response not yet received //or endpoint operation just failed in 1 minute return;}else if(endpoints&&endpoints.length>0){//found endpoint record from cache request.httpRequest.updateEndpoint(endpoints[0].Address);}else{//endpoint record not in cache or outdated. make discovery operation var endpointRequest=service.makeRequest(api.endpointOperation,{Operation:operationModel.name,Identifiers:identifiers});addApiVersionHeader(endpointRequest);endpointRequest.removeListener('validate',AWS.EventListeners.Core.VALIDATE_PARAMETERS);endpointRequest.removeListener('retry',AWS.EventListeners.Core.RETRY_CHECK);//put in a placeholder for endpoints already requested, prevent //too much in-flight calls AWS.endpointCache.put(cacheKey,[{Address:'',CachePeriodInMinutes:1}]);endpointRequest.send(function(err,data){if(data&&data.Endpoints){AWS.endpointCache.put(cacheKey,data.Endpoints);}else if(err){AWS.endpointCache.put(cacheKey,[{Address:'',CachePeriodInMinutes:1//not to make more endpoint operation in next 1 minute }]);}});}}var requestQueue={};/** * Call endpoint discovery operation when it's required. * When endpoint is available in cache then use cached ones. If endpoints are * unavailable then SDK should call endpoint operation then use returned new * endpoint for the api call. SDK will automatically attempt to do endpoint * discovery. This is turned off by default * @param [object] request object * @api private */function requiredDiscoverEndpoint(request,done){var service=request.service;var api=service.api;var operationModel=api.operations?api.operations[request.operation]:undefined;var inputShape=operationModel?operationModel.input:undefined;var identifiers=marshallCustomIdentifiers(request,inputShape);var cacheKey=getCacheKey(request);if(Object.keys(identifiers).length>0){cacheKey=util.update(cacheKey,identifiers);if(operationModel)cacheKey.operation=operationModel.name;}var cacheKeyStr=AWS.EndpointCache.getKeyString(cacheKey);var endpoints=AWS.endpointCache.get(cacheKeyStr);//endpoint cache also accepts string keys if(endpoints&&endpoints.length===1&&endpoints[0].Address===''){//endpoint operation is being made but response not yet received //push request object to a pending queue if(!requestQueue[cacheKeyStr])requestQueue[cacheKeyStr]=[];requestQueue[cacheKeyStr].push({request:request,callback:done});return;}else if(endpoints&&endpoints.length>0){request.httpRequest.updateEndpoint(endpoints[0].Address);done();}else{var endpointRequest=service.makeRequest(api.endpointOperation,{Operation:operationModel.name,Identifiers:identifiers});endpointRequest.removeListener('validate',AWS.EventListeners.Core.VALIDATE_PARAMETERS);addApiVersionHeader(endpointRequest);//put in a placeholder for endpoints already requested, prevent //too much in-flight calls AWS.endpointCache.put(cacheKeyStr,[{Address:'',CachePeriodInMinutes:60//long-live cache }]);endpointRequest.send(function(err,data){if(err){request.response.error=util.error(err,{retryable:false});AWS.endpointCache.remove(cacheKey);//fail all the pending requests in batch if(requestQueue[cacheKeyStr]){var pendingRequests=requestQueue[cacheKeyStr];util.arrayEach(pendingRequests,function(requestContext){requestContext.request.response.error=util.error(err,{retryable:false});requestContext.callback();});delete requestQueue[cacheKeyStr];}}else if(data){AWS.endpointCache.put(cacheKeyStr,data.Endpoints);request.httpRequest.updateEndpoint(data.Endpoints[0].Address);//update the endpoint for all the pending requests in batch if(requestQueue[cacheKeyStr]){var pendingRequests=requestQueue[cacheKeyStr];util.arrayEach(pendingRequests,function(requestContext){requestContext.request.httpRequest.updateEndpoint(data.Endpoints[0].Address);requestContext.callback();});delete requestQueue[cacheKeyStr];}}done();});}}/** * add api version header to endpoint operation * @api private */function addApiVersionHeader(endpointRequest){var api=endpointRequest.service.api;var apiVersion=api.apiVersion;if(apiVersion&&!endpointRequest.httpRequest.headers['x-amz-api-version']){endpointRequest.httpRequest.headers['x-amz-api-version']=apiVersion;}}/** * If api call gets invalid endpoint exception, SDK should attempt to remove the invalid * endpoint from cache. * @api private */function invalidateCachedEndpoints(response){var error=response.error;var httpResponse=response.httpResponse;if(error&&(error.code==='InvalidEndpointException'||httpResponse.statusCode===421)){var request=response.request;var operations=request.service.api.operations||{};var inputShape=operations[request.operation]?operations[request.operation].input:undefined;var identifiers=marshallCustomIdentifiers(request,inputShape);var cacheKey=getCacheKey(request);if(Object.keys(identifiers).length>0){cacheKey=util.update(cacheKey,identifiers);if(operations[request.operation])cacheKey.operation=operations[request.operation].name;}AWS.endpointCache.remove(cacheKey);}}/** * If endpoint is explicitly configured, SDK should not do endpoint discovery in anytime. * @param [object] client Service client object. * @api private */function hasCustomEndpoint(client){//if set endpoint is set for specific client, enable endpoint discovery will raise an error. if(client._originalConfig&&client._originalConfig.endpoint&&client._originalConfig.endpointDiscoveryEnabled===true){throw util.error(new Error(),{code:'ConfigurationException',message:'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.'});};var svcConfig=AWS.config[client.serviceIdentifier]||{};return Boolean(AWS.config.endpoint||svcConfig.endpoint||client._originalConfig&&client._originalConfig.endpoint);}/** * @api private */function isFalsy(value){return['false','0'].indexOf(value)>=0;}/** * If endpoint discovery should perform for this request when no operation requires endpoint * discovery for the given service. * SDK performs config resolution in order like below: * 1. If set in client configuration. * 2. If set in env AWS_ENABLE_ENDPOINT_DISCOVERY. * 3. If set in shared ini config file with key 'endpoint_discovery_enabled'. * @param [object] request request object. * @returns [boolean|undefined] if endpoint discovery config is not set in any source, this * function returns undefined * @api private */function resolveEndpointDiscoveryConfig(request){var service=request.service||{};if(service.config.endpointDiscoveryEnabled!==undefined){return service.config.endpointDiscoveryEnabled;}//shared ini file is only available in Node //not to check env in browser if(util.isBrowser())return undefined;// If any of recognized endpoint discovery config env is set for(var i=0;i9223372036854775807||number<-9223372036854775808){throw new Error(number+' is too large (or, if negative, too small) to represent as an Int64');}var bytes=new Uint8Array(8);for(var i=7,remaining=Math.abs(Math.round(number));i>-1&&remaining>0;i--,remaining/=256){bytes[i]=remaining;}if(number<0){negate(bytes);}return new Int64(bytes);};/** * @returns {number} * * @api private */Int64.prototype.valueOf=function(){var bytes=this.bytes.slice(0);var negative=bytes[0]&128;if(negative){negate(bytes);}return parseInt(bytes.toString('hex'),16)*(negative?-1:1);};Int64.prototype.toString=function(){return String(this.valueOf());};/** * @param {Buffer} bytes * * @api private */function negate(bytes){for(var i=0;i<8;i++){bytes[i]^=0xFF;}for(var i=7;i>-1;i--){bytes[i]++;if(bytes[i]!==0){break;}}}/** * @api private */module.exports={Int64:Int64};},{"../core":19}],31:[function(require,module,exports){var parseMessage=require('./parse-message').parseMessage;/** * * @param {*} parser * @param {Buffer} message * @param {*} shape * @api private */function parseEvent(parser,message,shape){var parsedMessage=parseMessage(message);// check if message is an event or error var messageType=parsedMessage.headers[':message-type'];if(messageType){if(messageType.value==='error'){throw parseError(parsedMessage);}else if(messageType.value!=='event'){// not sure how to parse non-events/non-errors, ignore for now return;}}// determine event type var eventType=parsedMessage.headers[':event-type'];// check that the event type is modeled var eventModel=shape.members[eventType.value];if(!eventModel){return;}var result={};// check if an event payload exists var eventPayloadMemberName=eventModel.eventPayloadMemberName;if(eventPayloadMemberName){var payloadShape=eventModel.members[eventPayloadMemberName];// if the shape is binary, return the byte array if(payloadShape.type==='binary'){result[eventPayloadMemberName]=parsedMessage.body;}else{result[eventPayloadMemberName]=parser.parse(parsedMessage.body.toString(),payloadShape);}}// read event headers var eventHeaderNames=eventModel.eventHeaderMemberNames;for(var i=0;i=0){req.httpRequest.headers['X-Amz-Content-Sha256']='UNSIGNED-PAYLOAD';return done();}AWS.util.computeSha256(body,function(err,sha){if(err){done(err);}else{req.httpRequest.headers['X-Amz-Content-Sha256']=sha;done();}});}else{done();}});add('SET_CONTENT_LENGTH','afterBuild',function SET_CONTENT_LENGTH(req){var authtype=getOperationAuthtype(req);var payloadMember=AWS.util.getRequestPayloadShape(req);if(req.httpRequest.headers['Content-Length']===undefined){try{var length=AWS.util.string.byteLength(req.httpRequest.body);req.httpRequest.headers['Content-Length']=length;}catch(err){if(payloadMember&&payloadMember.isStreaming){if(payloadMember.requiresLength){//streaming payload requires length(s3, glacier) throw err;}else if(authtype.indexOf('unsigned-body')>=0){//unbounded streaming payload(lex, mediastore) req.httpRequest.headers['Transfer-Encoding']='chunked';return;}else{throw err;}}throw err;}}});add('SET_HTTP_HOST','afterBuild',function SET_HTTP_HOST(req){req.httpRequest.headers['Host']=req.httpRequest.endpoint.host;});add('SET_TRACE_ID','afterBuild',function SET_TRACE_ID(req){var traceIdHeaderName='X-Amzn-Trace-Id';if(AWS.util.isNode()&&!Object.hasOwnProperty.call(req.httpRequest.headers,traceIdHeaderName)){var ENV_LAMBDA_FUNCTION_NAME='AWS_LAMBDA_FUNCTION_NAME';var ENV_TRACE_ID='_X_AMZN_TRACE_ID';var functionName=process.env[ENV_LAMBDA_FUNCTION_NAME];var traceId=process.env[ENV_TRACE_ID];if(typeof functionName==='string'&&functionName.length>0&&typeof traceId==='string'&&traceId.length>0){req.httpRequest.headers[traceIdHeaderName]=traceId;}}});add('RESTART','restart',function RESTART(){var err=this.response.error;if(!err||!err.retryable)return;this.httpRequest=new AWS.HttpRequest(this.service.endpoint,this.service.region);if(this.response.retryCount=60*10){// if we signed 10min ago, re-sign this.emit('sign',[this],function(err){if(err)done(err);else executeSend();});}else{executeSend();}});add('HTTP_HEADERS','httpHeaders',function HTTP_HEADERS(statusCode,headers,resp,statusMessage){resp.httpResponse.statusCode=statusCode;resp.httpResponse.statusMessage=statusMessage;resp.httpResponse.headers=headers;resp.httpResponse.body=AWS.util.buffer.toBuffer('');resp.httpResponse.buffers=[];resp.httpResponse.numBytes=0;var dateHeader=headers.date||headers.Date;var service=resp.request.service;if(dateHeader){var serverTime=Date.parse(dateHeader);if(service.config.correctClockSkew&&service.isClockSkewed(serverTime)){service.applyClockOffset(serverTime);}}});add('HTTP_DATA','httpData',function HTTP_DATA(chunk,resp){if(chunk){if(AWS.util.isNode()){resp.httpResponse.numBytes+=chunk.length;var total=resp.httpResponse.headers['content-length'];var progress={loaded:resp.httpResponse.numBytes,total:total};resp.request.emit('httpDownloadProgress',[progress,resp]);}resp.httpResponse.buffers.push(AWS.util.buffer.toBuffer(chunk));}});add('HTTP_DONE','httpDone',function HTTP_DONE(resp){// convert buffers array into single buffer if(resp.httpResponse.buffers&&resp.httpResponse.buffers.length>0){var body=AWS.util.buffer.concat(resp.httpResponse.buffers);resp.httpResponse.body=body;}delete resp.httpResponse.numBytes;delete resp.httpResponse.buffers;});add('FINALIZE_ERROR','retry',function FINALIZE_ERROR(resp){if(resp.httpResponse.statusCode){resp.error.statusCode=resp.httpResponse.statusCode;if(resp.error.retryable===undefined){resp.error.retryable=this.service.retryableError(resp.error,this);}}});add('INVALIDATE_CREDENTIALS','retry',function INVALIDATE_CREDENTIALS(resp){if(!resp.error)return;switch(resp.error.code){case'RequestExpired':// EC2 only case'ExpiredTokenException':case'ExpiredToken':resp.error.retryable=true;resp.request.service.config.credentials.expired=true;}});add('EXPIRED_SIGNATURE','retry',function EXPIRED_SIGNATURE(resp){var err=resp.error;if(!err)return;if(typeof err.code==='string'&&typeof err.message==='string'){if(err.code.match(/Signature/)&&err.message.match(/expired/)){resp.error.retryable=true;}}});add('CLOCK_SKEWED','retry',function CLOCK_SKEWED(resp){if(!resp.error)return;if(this.service.clockSkewError(resp.error)&&this.service.config.correctClockSkew){resp.error.retryable=true;}});add('REDIRECT','retry',function REDIRECT(resp){if(resp.error&&resp.error.statusCode>=300&&resp.error.statusCode<400&&resp.httpResponse.headers['location']){this.httpRequest.endpoint=new AWS.Endpoint(resp.httpResponse.headers['location']);this.httpRequest.headers['Host']=this.httpRequest.endpoint.host;resp.error.redirect=true;resp.error.retryable=true;}});add('RETRY_CHECK','retry',function RETRY_CHECK(resp){if(resp.error){if(resp.error.redirect&&resp.redirectCount=0){resp.error=null;setTimeout(done,delay);}else{done();}});}),CorePost:new SequentialExecutor().addNamedListeners(function(add){add('EXTRACT_REQUEST_ID','extractData',AWS.util.extractRequestId);add('EXTRACT_REQUEST_ID','extractError',AWS.util.extractRequestId);add('ENOTFOUND_ERROR','httpError',function ENOTFOUND_ERROR(err){function isDNSError(err){return err.errno==='ENOTFOUND'||typeof err.errno==='number'&&typeof AWS.util.getSystemErrorName==='function'&&['EAI_NONAME','EAI_NODATA'].indexOf(AWS.util.getSystemErrorName(err.errno)>=0);}if(err.code==='NetworkingError'&&isDNSError(err)){var message='Inaccessible host: `'+err.hostname+'\' at port `'+err.port+'\'. This service may not be available in the `'+err.region+'\' region.';this.response.error=AWS.util.error(new Error(message),{code:'UnknownEndpoint',region:err.region,hostname:err.hostname,retryable:true,originalError:err});}});}),Logger:new SequentialExecutor().addNamedListeners(function(add){add('LOG_REQUEST','complete',function LOG_REQUEST(resp){var req=resp.request;var logger=req.service.config.logger;if(!logger)return;function filterSensitiveLog(inputShape,shape){if(!shape){return shape;}if(inputShape.isSensitive){return'***SensitiveInformation***';}switch(inputShape.type){case'structure':var struct={};AWS.util.each(shape,function(subShapeName,subShape){if(Object.prototype.hasOwnProperty.call(inputShape.members,subShapeName)){struct[subShapeName]=filterSensitiveLog(inputShape.members[subShapeName],subShape);}else{struct[subShapeName]=subShape;}});return struct;case'list':var list=[];AWS.util.arrayEach(shape,function(subShape,index){list.push(filterSensitiveLog(inputShape.member,subShape));});return list;case'map':var map={};AWS.util.each(shape,function(key,value){map[key]=filterSensitiveLog(inputShape.value,value);});return map;default:return shape;}}function buildMessage(){var time=resp.request.service.getSkewCorrectedDate().getTime();var delta=(time-req.startTime.getTime())/1000;var ansi=logger.isTTY?true:false;var status=resp.httpResponse.statusCode;var censoredParams=req.params;if(req.service.api.operations&&req.service.api.operations[req.operation]&&req.service.api.operations[req.operation].input){var inputShape=req.service.api.operations[req.operation].input;censoredParams=filterSensitiveLog(inputShape,req.params);}var params=require('util').inspect(censoredParams,true,null);var message='';if(ansi)message+='\x1B[33m';message+='[AWS '+req.service.serviceIdentifier+' '+status;message+=' '+delta.toString()+'s '+resp.retryCount+' retries]';if(ansi)message+='\x1B[0;1m';message+=' '+AWS.util.string.lowerFirst(req.operation);message+='('+params+')';if(ansi)message+='\x1B[0m';return message;}var line=buildMessage();if(typeof logger.log==='function'){logger.log(line);}else if(typeof logger.write==='function'){logger.write(line+'\n');}});}),Json:new SequentialExecutor().addNamedListeners(function(add){var svc=require('./protocol/json');add('BUILD','build',svc.buildRequest);add('EXTRACT_DATA','extractData',svc.extractData);add('EXTRACT_ERROR','extractError',svc.extractError);}),Rest:new SequentialExecutor().addNamedListeners(function(add){var svc=require('./protocol/rest');add('BUILD','build',svc.buildRequest);add('EXTRACT_DATA','extractData',svc.extractData);add('EXTRACT_ERROR','extractError',svc.extractError);}),RestJson:new SequentialExecutor().addNamedListeners(function(add){var svc=require('./protocol/rest_json');add('BUILD','build',svc.buildRequest);add('EXTRACT_DATA','extractData',svc.extractData);add('EXTRACT_ERROR','extractError',svc.extractError);add('UNSET_CONTENT_LENGTH','afterBuild',svc.unsetContentLength);}),RestXml:new SequentialExecutor().addNamedListeners(function(add){var svc=require('./protocol/rest_xml');add('BUILD','build',svc.buildRequest);add('EXTRACT_DATA','extractData',svc.extractData);add('EXTRACT_ERROR','extractError',svc.extractError);}),Query:new SequentialExecutor().addNamedListeners(function(add){var svc=require('./protocol/query');add('BUILD','build',svc.buildRequest);add('EXTRACT_DATA','extractData',svc.extractData);add('EXTRACT_ERROR','extractError',svc.extractError);})};}).call(this);}).call(this,require('_process'));},{"./core":19,"./discover_endpoint":27,"./protocol/json":48,"./protocol/query":49,"./protocol/rest":50,"./protocol/rest_json":51,"./protocol/rest_xml":52,"./sequential_executor":61,"_process":91,"util":85}],35:[function(require,module,exports){var AWS=require('./core');var inherit=AWS.util.inherit;/** * The endpoint that a service will talk to, for example, * `'https://ec2.ap-southeast-1.amazonaws.com'`. If * you need to override an endpoint for a service, you can * set the endpoint on a service by passing the endpoint * object with the `endpoint` option key: * * ```javascript * var ep = new AWS.Endpoint('awsproxy.example.com'); * var s3 = new AWS.S3({endpoint: ep}); * s3.service.endpoint.hostname == 'awsproxy.example.com' * ``` * * Note that if you do not specify a protocol, the protocol will * be selected based on your current {AWS.config} configuration. * * @!attribute protocol * @return [String] the protocol (http or https) of the endpoint * URL * @!attribute hostname * @return [String] the host portion of the endpoint, e.g., * example.com * @!attribute host * @return [String] the host portion of the endpoint including * the port, e.g., example.com:80 * @!attribute port * @return [Integer] the port of the endpoint * @!attribute href * @return [String] the full URL of the endpoint */AWS.Endpoint=inherit({/** * @overload Endpoint(endpoint) * Constructs a new endpoint given an endpoint URL. If the * URL omits a protocol (http or https), the default protocol * set in the global {AWS.config} will be used. * @param endpoint [String] the URL to construct an endpoint from */constructor:function Endpoint(endpoint,config){AWS.util.hideProperties(this,['slashes','auth','hash','search','query']);if(typeof endpoint==='undefined'||endpoint===null){throw new Error('Invalid endpoint: '+endpoint);}else if(typeof endpoint!=='string'){return AWS.util.copy(endpoint);}if(!endpoint.match(/^http/)){var useSSL=config&&config.sslEnabled!==undefined?config.sslEnabled:AWS.config.sslEnabled;endpoint=(useSSL?'https':'http')+'://'+endpoint;}AWS.util.update(this,AWS.util.urlParse(endpoint));// Ensure the port property is set as an integer if(this.port){this.port=parseInt(this.port,10);}else{this.port=this.protocol==='https:'?443:80;}}});/** * The low level HTTP request object, encapsulating all HTTP header * and body data sent by a service request. * * @!attribute method * @return [String] the HTTP method of the request * @!attribute path * @return [String] the path portion of the URI, e.g., * "/list/?start=5&num=10" * @!attribute headers * @return [map] * a map of header keys and their respective values * @!attribute body * @return [String] the request body payload * @!attribute endpoint * @return [AWS.Endpoint] the endpoint for the request * @!attribute region * @api private * @return [String] the region, for signing purposes only. */AWS.HttpRequest=inherit({/** * @api private */constructor:function HttpRequest(endpoint,region){endpoint=new AWS.Endpoint(endpoint);this.method='POST';this.path=endpoint.path||'/';this.headers={};this.body='';this.endpoint=endpoint;this.region=region;this._userAgent='';this.setUserAgent();},/** * @api private */setUserAgent:function setUserAgent(){this._userAgent=this.headers[this.getUserAgentHeaderName()]=AWS.util.userAgent();},getUserAgentHeaderName:function getUserAgentHeaderName(){var prefix=AWS.util.isBrowser()?'X-Amz-':'';return prefix+'User-Agent';},/** * @api private */appendToUserAgent:function appendToUserAgent(agentPartial){if(typeof agentPartial==='string'&&agentPartial){this._userAgent+=' '+agentPartial;}this.headers[this.getUserAgentHeaderName()]=this._userAgent;},/** * @api private */getUserAgent:function getUserAgent(){return this._userAgent;},/** * @return [String] the part of the {path} excluding the * query string */pathname:function pathname(){return this.path.split('?',1)[0];},/** * @return [String] the query string portion of the {path} */search:function search(){var query=this.path.split('?',2)[1];if(query){query=AWS.util.queryStringParse(query);return AWS.util.queryParamsToString(query);}return'';},/** * @api private * update httpRequest endpoint with endpoint string */updateEndpoint:function updateEndpoint(endpointStr){var newEndpoint=new AWS.Endpoint(endpointStr);this.endpoint=newEndpoint;this.path=newEndpoint.path||'/';if(this.headers['Host']){this.headers['Host']=newEndpoint.host;}}});/** * The low level HTTP response object, encapsulating all HTTP header * and body data returned from the request. * * @!attribute statusCode * @return [Integer] the HTTP status code of the response (e.g., 200, 404) * @!attribute headers * @return [map] * a map of response header keys and their respective values * @!attribute body * @return [String] the response body payload * @!attribute [r] streaming * @return [Boolean] whether this response is being streamed at a low-level. * Defaults to `false` (buffered reads). Do not modify this manually, use * {createUnbufferedStream} to convert the stream to unbuffered mode * instead. */AWS.HttpResponse=inherit({/** * @api private */constructor:function HttpResponse(){this.statusCode=undefined;this.headers={};this.body=undefined;this.streaming=false;this.stream=null;},/** * Disables buffering on the HTTP response and returns the stream for reading. * @return [Stream, XMLHttpRequest, null] the underlying stream object. * Use this object to directly read data off of the stream. * @note This object is only available after the {AWS.Request~httpHeaders} * event has fired. This method must be called prior to * {AWS.Request~httpData}. * @example Taking control of a stream * request.on('httpHeaders', function(statusCode, headers) { * if (statusCode < 300) { * if (headers.etag === 'xyz') { * // pipe the stream, disabling buffering * var stream = this.response.httpResponse.createUnbufferedStream(); * stream.pipe(process.stdout); * } else { // abort this request and set a better error message * this.abort(); * this.response.error = new Error('Invalid ETag'); * } * } * }).send(console.log); */createUnbufferedStream:function createUnbufferedStream(){this.streaming=true;return this.stream;}});AWS.HttpClient=inherit({});/** * @api private */AWS.HttpClient.getInstance=function getInstance(){if(this.singleton===undefined){this.singleton=new this();}return this.singleton;};},{"./core":19}],36:[function(require,module,exports){var AWS=require('../core');var EventEmitter=require('events').EventEmitter;require('../http');/** * @api private */AWS.XHRClient=AWS.util.inherit({handleRequest:function handleRequest(httpRequest,httpOptions,callback,errCallback){var self=this;var endpoint=httpRequest.endpoint;var emitter=new EventEmitter();var href=endpoint.protocol+'//'+endpoint.hostname;if(endpoint.port!==80&&endpoint.port!==443){href+=':'+endpoint.port;}href+=httpRequest.path;var xhr=new XMLHttpRequest(),headersEmitted=false;httpRequest.stream=xhr;xhr.addEventListener('readystatechange',function(){try{if(xhr.status===0)return;// 0 code is invalid }catch(e){return;}if(this.readyState>=this.HEADERS_RECEIVED&&!headersEmitted){emitter.statusCode=xhr.status;emitter.headers=self.parseHeaders(xhr.getAllResponseHeaders());emitter.emit('headers',emitter.statusCode,emitter.headers,xhr.statusText);headersEmitted=true;}if(this.readyState===this.DONE){self.finishRequest(xhr,emitter);}},false);xhr.upload.addEventListener('progress',function(evt){emitter.emit('sendProgress',evt);});xhr.addEventListener('progress',function(evt){emitter.emit('receiveProgress',evt);},false);xhr.addEventListener('timeout',function(){errCallback(AWS.util.error(new Error('Timeout'),{code:'TimeoutError'}));},false);xhr.addEventListener('error',function(){errCallback(AWS.util.error(new Error('Network Failure'),{code:'NetworkingError'}));},false);xhr.addEventListener('abort',function(){errCallback(AWS.util.error(new Error('Request aborted'),{code:'RequestAbortedError'}));},false);callback(emitter);xhr.open(httpRequest.method,href,httpOptions.xhrAsync!==false);AWS.util.each(httpRequest.headers,function(key,value){if(key!=='Content-Length'&&key!=='User-Agent'&&key!=='Host'){xhr.setRequestHeader(key,value);}});if(httpOptions.timeout&&httpOptions.xhrAsync!==false){xhr.timeout=httpOptions.timeout;}if(httpOptions.xhrWithCredentials){xhr.withCredentials=true;}try{xhr.responseType='arraybuffer';}catch(e){}try{if(httpRequest.body){xhr.send(httpRequest.body);}else{xhr.send();}}catch(err){if(httpRequest.body&&_typeof(httpRequest.body.buffer)==='object'){xhr.send(httpRequest.body.buffer);// send ArrayBuffer directly }else{throw err;}}return emitter;},parseHeaders:function parseHeaders(rawHeaders){var headers={};AWS.util.arrayEach(rawHeaders.split(/\r?\n/),function(line){var key=line.split(':',1)[0];var value=line.substring(key.length+2);if(key.length>0)headers[key.toLowerCase()]=value;});return headers;},finishRequest:function finishRequest(xhr,emitter){var buffer;if(xhr.responseType==='arraybuffer'&&xhr.response){var ab=xhr.response;buffer=new AWS.util.Buffer(ab.byteLength);var view=new Uint8Array(ab);for(var i=0;i-1?value||'':value;if(this.isJsonValue){return JSON.parse(value);}return value&&typeof value.toString==='function'?value.toString():value;};this.toWireFormat=function(value){return this.isJsonValue?JSON.stringify(value):value;};}function FloatShape(){Shape.apply(this,arguments);this.toType=function(value){if(value===null||value===undefined)return null;return parseFloat(value);};this.toWireFormat=this.toType;}function IntegerShape(){Shape.apply(this,arguments);this.toType=function(value){if(value===null||value===undefined)return null;return parseInt(value,10);};this.toWireFormat=this.toType;}function BinaryShape(){Shape.apply(this,arguments);this.toType=function(value){var buf=util.base64.decode(value);if(this.isSensitive&&util.isNode()&&typeof util.Buffer.alloc==='function'){/* Node.js can create a Buffer that is not isolated. * i.e. buf.byteLength !== buf.buffer.byteLength * This means that the sensitive data is accessible to anyone with access to buf.buffer. * If this is the node shared Buffer, then other code within this process _could_ find this secret. * Copy sensitive data to an isolated Buffer and zero the sensitive data. * While this is safe to do here, copying this code somewhere else may produce unexpected results. */var secureBuf=util.Buffer.alloc(buf.length,buf);buf.fill(0);buf=secureBuf;}return buf;};this.toWireFormat=util.base64.encode;}function Base64Shape(){BinaryShape.apply(this,arguments);}function BooleanShape(){Shape.apply(this,arguments);this.toType=function(value){if(typeof value==='boolean')return value;if(value===null||value===undefined)return null;return value==='true';};}/** * @api private */Shape.shapes={StructureShape:StructureShape,ListShape:ListShape,MapShape:MapShape,StringShape:StringShape,BooleanShape:BooleanShape,Base64Shape:Base64Shape};/** * @api private */module.exports=Shape;},{"../util":74,"./collection":41}],46:[function(require,module,exports){var AWS=require('./core');/** * @api private */AWS.ParamValidator=AWS.util.inherit({/** * Create a new validator object. * * @param validation [Boolean|map] whether input parameters should be * validated against the operation description before sending the * request. Pass a map to enable any of the following specific * validation features: * * * **min** [Boolean] — Validates that a value meets the min * constraint. This is enabled by default when paramValidation is set * to `true`. * * **max** [Boolean] — Validates that a value meets the max * constraint. * * **pattern** [Boolean] — Validates that a string value matches a * regular expression. * * **enum** [Boolean] — Validates that a string value matches one * of the allowable enum values. */constructor:function ParamValidator(validation){if(validation===true||validation===undefined){validation={'min':true};}this.validation=validation;},validate:function validate(shape,params,context){this.errors=[];this.validateMember(shape,params||{},context||'params');if(this.errors.length>1){var msg=this.errors.join('\n* ');msg='There were '+this.errors.length+' validation errors:\n* '+msg;throw AWS.util.error(new Error(msg),{code:'MultipleValidationErrors',errors:this.errors});}else if(this.errors.length===1){throw this.errors[0];}else{return true;}},fail:function fail(code,message){this.errors.push(AWS.util.error(new Error(message),{code:code}));},validateStructure:function validateStructure(shape,params,context){if(shape.isDocument)return true;this.validateType(params,context,['object'],'structure');var paramName;for(var i=0;shape.required&&i= 1,'+' but found "'+value+'" for '+context);}}},validatePattern:function validatePattern(shape,value,context){if(this.validation['pattern']&&shape['pattern']!==undefined){if(!new RegExp(shape['pattern']).test(value)){this.fail('PatternMatchError','Provided value "'+value+'" '+'does not match regex pattern /'+shape['pattern']+'/ for '+context);}}},validateRange:function validateRange(shape,value,context,descriptor){if(this.validation['min']){if(shape['min']!==undefined&&value= '+shape['min']+', but found '+value+' for '+context);}}if(this.validation['max']){if(shape['max']!==undefined&&value>shape['max']){this.fail('MaxRangeError','Expected '+descriptor+' <= '+shape['max']+', but found '+value+' for '+context);}}},validateEnum:function validateRange(shape,value,context){if(this.validation['enum']&&shape['enum']!==undefined){// Fail if the string value is not present in the enum list if(shape['enum'].indexOf(value)===-1){this.fail('EnumError','Found string value of '+value+', but '+'expected '+shape['enum'].join('|')+' for '+context);}}},validateType:function validateType(value,context,acceptedTypes,type){// We will not log an error for null or undefined, but we will return // false so that callers know that the expected type was not strictly met. if(value===null||value===undefined)return false;var foundInvalidType=false;for(var i=0;i63){throw util.error(new Error(),{code:'ValidationError',message:'Hostname label length should be between 1 to 63 characters, inclusive.'});}if(!hostPattern.test(label)){throw AWS.util.error(new Error(),{code:'ValidationError',message:label+' is not hostname compatible.'});}});}module.exports={populateHostPrefix:populateHostPrefix};},{"../core":19,"../util":74}],48:[function(require,module,exports){var util=require('../util');var JsonBuilder=require('../json/builder');var JsonParser=require('../json/parser');var populateHostPrefix=require('./helpers').populateHostPrefix;function buildRequest(req){var httpRequest=req.httpRequest;var api=req.service.api;var target=api.targetPrefix+'.'+api.operations[req.operation].name;var version=api.jsonVersion||'1.0';var input=api.operations[req.operation].input;var builder=new JsonBuilder();if(version===1)version='1.0';if(api.awsQueryCompatible){if(!httpRequest.params){httpRequest.params={};}// because Query protocol does this. Object.assign(httpRequest.params,req.params);}httpRequest.body=builder.build(req.params||{},input);httpRequest.headers['Content-Type']='application/x-amz-json-'+version;httpRequest.headers['X-Amz-Target']=target;populateHostPrefix(req);}function extractError(resp){var error={};var httpResponse=resp.httpResponse;error.code=httpResponse.headers['x-amzn-errortype']||'UnknownError';if(typeof error.code==='string'){error.code=error.code.split(':')[0];}if(httpResponse.body.length>0){try{var e=JSON.parse(httpResponse.body.toString());var code=e.__type||e.code||e.Code;if(code){error.code=code.split('#').pop();}if(error.code==='RequestEntityTooLarge'){error.message='Request body must be less than 1 MB';}else{error.message=e.message||e.Message||null;}// The minimized models do not have error shapes, so // without expanding the model size, it's not possible // to validate the response shape (members) or // check if any are sensitive to logging. // Assign the fields as non-enumerable, allowing specific access only. for(var key in e||{}){if(key==='code'||key==='message'){continue;}error['['+key+']']='See error.'+key+' for details.';Object.defineProperty(error,key,{value:e[key],enumerable:false,writable:true});}}catch(e){error.statusCode=httpResponse.statusCode;error.message=httpResponse.statusMessage;}}else{error.statusCode=httpResponse.statusCode;error.message=httpResponse.statusCode.toString();}resp.error=util.error(new Error(),error);}function extractData(resp){var body=resp.httpResponse.body.toString()||'{}';if(resp.request.service.config.convertResponseTypes===false){resp.data=JSON.parse(body);}else{var operation=resp.request.service.api.operations[resp.request.operation];var shape=operation.output||{};var parser=new JsonParser();resp.data=parser.parse(body,shape);}}/** * @api private */module.exports={buildRequest:buildRequest,extractError:extractError,extractData:extractData};},{"../json/builder":37,"../json/parser":38,"../util":74,"./helpers":47}],49:[function(require,module,exports){var AWS=require('../core');var util=require('../util');var QueryParamSerializer=require('../query/query_param_serializer');var Shape=require('../model/shape');var populateHostPrefix=require('./helpers').populateHostPrefix;function buildRequest(req){var operation=req.service.api.operations[req.operation];var httpRequest=req.httpRequest;httpRequest.headers['Content-Type']='application/x-www-form-urlencoded; charset=utf-8';httpRequest.params={Version:req.service.api.apiVersion,Action:operation.name};// convert the request parameters into a list of query params, // e.g. Deeply.NestedParam.0.Name=value var builder=new QueryParamSerializer();builder.serialize(req.params,operation.input,function(name,value){httpRequest.params[name]=value;});httpRequest.body=util.queryParamsToString(httpRequest.params);populateHostPrefix(req);}function extractError(resp){var data,body=resp.httpResponse.body.toString();if(body.match('=0?'&':'?';var parts=[];util.arrayEach(Object.keys(queryString).sort(),function(key){if(!Array.isArray(queryString[key])){queryString[key]=[queryString[key]];}for(var i=0;i=0){delete req.httpRequest.headers['Content-Length'];}}function populateBody(req){var builder=new JsonBuilder();var input=req.service.api.operations[req.operation].input;if(input.payload){var params={};var payloadShape=input.members[input.payload];params=req.params[input.payload];if(payloadShape.type==='structure'){req.httpRequest.body=builder.build(params||{},payloadShape);applyContentTypeHeader(req);}else if(params!==undefined){// non-JSON payload req.httpRequest.body=params;if(payloadShape.type==='binary'||payloadShape.isStreaming){applyContentTypeHeader(req,true);}}}else{req.httpRequest.body=builder.build(req.params,input);applyContentTypeHeader(req);}}function applyContentTypeHeader(req,isBinary){if(!req.httpRequest.headers['Content-Type']){var type=isBinary?'binary/octet-stream':'application/json';req.httpRequest.headers['Content-Type']=type;}}function buildRequest(req){Rest.buildRequest(req);// never send body payload on GET/HEAD/DELETE if(METHODS_WITHOUT_BODY.indexOf(req.httpRequest.method)<0){populateBody(req);}}function extractError(resp){Json.extractError(resp);}function extractData(resp){Rest.extractData(resp);var req=resp.request;var operation=req.service.api.operations[req.operation];var rules=req.service.api.operations[req.operation].output||{};var parser;var hasEventOutput=operation.hasEventOutput;if(rules.payload){var payloadMember=rules.members[rules.payload];var body=resp.httpResponse.body;if(payloadMember.isEventStream){parser=new JsonParser();resp.data[payload]=util.createEventStream(AWS.HttpClient.streamsApiVersion===2?resp.httpResponse.stream:body,parser,payloadMember);}else if(payloadMember.type==='structure'||payloadMember.type==='list'){var parser=new JsonParser();resp.data[rules.payload]=parser.parse(body,payloadMember);}else if(payloadMember.type==='binary'||payloadMember.isStreaming){resp.data[rules.payload]=body;}else{resp.data[rules.payload]=payloadMember.toType(body);}}else{var data=resp.data;Json.extractData(resp);resp.data=util.merge(data,resp.data);}}/** * @api private */module.exports={buildRequest:buildRequest,extractError:extractError,extractData:extractData,unsetContentLength:unsetContentLength};},{"../json/builder":37,"../json/parser":38,"../util":74,"./json":48,"./rest":50}],52:[function(require,module,exports){var AWS=require('../core');var util=require('../util');var Rest=require('./rest');function populateBody(req){var input=req.service.api.operations[req.operation].input;var builder=new AWS.XML.Builder();var params=req.params;var payload=input.payload;if(payload){var payloadMember=input.members[payload];params=params[payload];if(params===undefined)return;if(payloadMember.type==='structure'){var rootElement=payloadMember.name;req.httpRequest.body=builder.toXML(params,payloadMember,rootElement,true);}else{// non-xml payload req.httpRequest.body=params;}}else{req.httpRequest.body=builder.toXML(params,input,input.name||input.shape||util.string.upperFirst(req.operation)+'Request');}}function buildRequest(req){Rest.buildRequest(req);// never send body payload on GET/HEAD if(['GET','HEAD'].indexOf(req.httpRequest.method)<0){populateBody(req);}}function extractError(resp){Rest.extractError(resp);var data;try{data=new AWS.XML.Parser().parse(resp.httpResponse.body.toString());}catch(e){data={Code:resp.httpResponse.statusCode,Message:resp.httpResponse.statusMessage};}if(data.Errors)data=data.Errors;if(data.Error)data=data.Error;if(data.Code){resp.error=util.error(new Error(),{code:data.Code,message:data.Message});}else{resp.error=util.error(new Error(),{code:resp.httpResponse.statusCode,message:null});}}function extractData(resp){Rest.extractData(resp);var parser;var req=resp.request;var body=resp.httpResponse.body;var operation=req.service.api.operations[req.operation];var output=operation.output;var hasEventOutput=operation.hasEventOutput;var payload=output.payload;if(payload){var payloadMember=output.members[payload];if(payloadMember.isEventStream){parser=new AWS.XML.Parser();resp.data[payload]=util.createEventStream(AWS.HttpClient.streamsApiVersion===2?resp.httpResponse.stream:resp.httpResponse.body,parser,payloadMember);}else if(payloadMember.type==='structure'){parser=new AWS.XML.Parser();resp.data[payload]=parser.parse(body.toString(),payloadMember);}else if(payloadMember.type==='binary'||payloadMember.isStreaming){resp.data[payload]=body;}else{resp.data[payload]=payloadMember.toType(body);}}else if(body.length>0){parser=new AWS.XML.Parser();var data=parser.parse(body.toString(),output);util.update(resp.data,data);}}/** * @api private */module.exports={buildRequest:buildRequest,extractError:extractError,extractData:extractData};},{"../core":19,"../util":74,"./rest":50}],53:[function(require,module,exports){var util=require('../util');function QueryParamSerializer(){}QueryParamSerializer.prototype.serialize=function(params,shape,fn){serializeStructure('',params,shape,fn);};function ucfirst(shape){if(shape.isQueryName||shape.api.protocol!=='ec2'){return shape.name;}else{return shape.name[0].toUpperCase()+shape.name.substr(1);}}function serializeStructure(prefix,struct,rules,fn){util.each(rules.members,function(name,member){var value=struct[name];if(value===null||value===undefined)return;var memberName=ucfirst(member);memberName=prefix?prefix+'.'+memberName:memberName;serializeMember(memberName,value,member,fn);});}function serializeMap(name,map,rules,fn){var i=1;util.each(map,function(key,value){var prefix=rules.flattened?'.':'.entry.';var position=prefix+i++ +'.';var keyName=position+(rules.key.name||'key');var valueName=position+(rules.value.name||'value');serializeMember(name+keyName,key,rules.key,fn);serializeMember(name+valueName,value,rules.value,fn);});}function serializeList(name,list,rules,fn){var memberRules=rules.member||{};if(list.length===0){fn.call(this,name,null);return;}util.arrayEach(list,function(v,n){var suffix='.'+(n+1);if(rules.api.protocol==='ec2'){// Do nothing for EC2 suffix=suffix+'';// make linter happy }else if(rules.flattened){if(memberRules.name){var parts=name.split('.');parts.pop();parts.push(ucfirst(memberRules));name=parts.join('.');}}else{suffix='.'+(memberRules.name?memberRules.name:'member')+suffix;}serializeMember(name+suffix,v,memberRules,fn);});}function serializeMember(name,value,rules,fn){if(value===null||value===undefined)return;if(rules.type==='structure'){serializeStructure(name,value,rules,fn);}else if(rules.type==='list'){serializeList(name,value,rules,fn);}else if(rules.type==='map'){serializeMap(name,value,rules,fn);}else{fn(name,rules.toWireFormat(value).toString());}}/** * @api private */module.exports=QueryParamSerializer;},{"../util":74}],54:[function(require,module,exports){module.exports={//provide realtime clock for performance measurement now:function now(){if(typeof performance!=='undefined'&&typeof performance.now==='function'){return performance.now();}return Date.now();}};},{}],55:[function(require,module,exports){function isFipsRegion(region){return typeof region==='string'&&(region.startsWith('fips-')||region.endsWith('-fips'));}function isGlobalRegion(region){return typeof region==='string'&&['aws-global','aws-us-gov-global'].includes(region);}function getRealRegion(region){return['fips-aws-global','aws-fips','aws-global'].includes(region)?'us-east-1':['fips-aws-us-gov-global','aws-us-gov-global'].includes(region)?'us-gov-west-1':region.replace(/fips-(dkr-|prod-)?|-fips/,'');}module.exports={isFipsRegion:isFipsRegion,isGlobalRegion:isGlobalRegion,getRealRegion:getRealRegion};},{}],56:[function(require,module,exports){var util=require('./util');var regionConfig=require('./region_config_data.json');function generateRegionPrefix(region){if(!region)return null;var parts=region.split('-');if(parts.length<3)return null;return parts.slice(0,parts.length-2).join('-')+'-*';}function derivedKeys(service){var region=service.config.region;var regionPrefix=generateRegionPrefix(region);var endpointPrefix=service.api.endpointPrefix;return[[region,endpointPrefix],[regionPrefix,endpointPrefix],[region,'*'],[regionPrefix,'*'],['*',endpointPrefix],[region,'internal-*'],['*','*']].map(function(item){return item[0]&&item[1]?item.join('/'):null;});}function applyConfig(service,config){util.each(config,function(key,value){if(key==='globalEndpoint')return;if(service.config[key]===undefined||service.config[key]===null){service.config[key]=value;}});}function configureEndpoint(service){var keys=derivedKeys(service);var useFipsEndpoint=service.config.useFipsEndpoint;var useDualstackEndpoint=service.config.useDualstackEndpoint;for(var i=0;i] the response headers * @param (see AWS.Request~send) * @param statusMessage [String] A status message corresponding to the HTTP * response code * @context (see AWS.Request~send) * * @!event httpData(chunk, response) * Triggered when data is sent by the remote server * @param chunk [Buffer] the buffer data containing the next data chunk * from the server * @param (see AWS.Request~send) * @context (see AWS.Request~send) * @see AWS.EventListeners.Core.HTTP_DATA * * @!event httpUploadProgress(progress, response) * Triggered when the HTTP request has uploaded more data * @param progress [map] An object containing the `loaded` and `total` bytes * of the request. * @param (see AWS.Request~send) * @context (see AWS.Request~send) * @note This event will not be emitted in Node.js 0.8.x. * * @!event httpDownloadProgress(progress, response) * Triggered when the HTTP request has downloaded more data * @param progress [map] An object containing the `loaded` and `total` bytes * of the request. * @param (see AWS.Request~send) * @context (see AWS.Request~send) * @note This event will not be emitted in Node.js 0.8.x. * * @!event httpError(error, response) * Triggered when the HTTP request failed * @param error [Error] the error object that was thrown * @param (see AWS.Request~send) * @context (see AWS.Request~send) * * @!event httpDone(response) * Triggered when the server is finished sending data * @param (see AWS.Request~send) * @context (see AWS.Request~send) * * @see AWS.Response */AWS.Request=inherit({/** * Creates a request for an operation on a given service with * a set of input parameters. * * @param service [AWS.Service] the service to perform the operation on * @param operation [String] the operation to perform on the service * @param params [Object] parameters to send to the operation. * See the operation's documentation for the format of the * parameters. */constructor:function Request(service,operation,params){var endpoint=service.endpoint;var region=service.config.region;var customUserAgent=service.config.customUserAgent;if(service.signingRegion){region=service.signingRegion;}else if(service.isGlobalEndpoint){region='us-east-1';}this.domain=domain&&domain.active;this.service=service;this.operation=operation;this.params=params||{};this.httpRequest=new AWS.HttpRequest(endpoint,region);this.httpRequest.appendToUserAgent(customUserAgent);this.startTime=service.getSkewCorrectedDate();this.response=new AWS.Response(this);this._asm=new AcceptorStateMachine(fsm.states,'validate');this._haltHandlersOnError=false;AWS.SequentialExecutor.call(this);this.emit=this.emitEvent;},/** * @!group Sending a Request *//** * @overload send(callback = null) * Sends the request object. * * @callback callback function(err, data) * If a callback is supplied, it is called when a response is returned * from the service. * @context [AWS.Request] the request object being sent. * @param err [Error] the error object returned from the request. * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. * @example Sending a request with a callback * request = s3.putObject({Bucket: 'bucket', Key: 'key'}); * request.send(function(err, data) { console.log(err, data); }); * @example Sending a request with no callback (using event handlers) * request = s3.putObject({Bucket: 'bucket', Key: 'key'}); * request.on('complete', function(response) { ... }); // register a callback * request.send(); */send:function send(callback){if(callback){// append to user agent this.httpRequest.appendToUserAgent('callback');this.on('complete',function(resp){callback.call(resp,resp.error,resp.data);});}this.runTo();return this.response;},/** * @!method promise() * Sends the request and returns a 'thenable' promise. * * Two callbacks can be provided to the `then` method on the returned promise. * The first callback will be called if the promise is fulfilled, and the second * callback will be called if the promise is rejected. * @callback fulfilledCallback function(data) * Called if the promise is fulfilled. * @param data [Object] the de-serialized data returned from the request. * @callback rejectedCallback function(error) * Called if the promise is rejected. * @param error [Error] the error object returned from the request. * @return [Promise] A promise that represents the state of the request. * @example Sending a request using promises. * var request = s3.putObject({Bucket: 'bucket', Key: 'key'}); * var result = request.promise(); * result.then(function(data) { ... }, function(error) { ... }); *//** * @api private */build:function build(callback){return this.runTo('send',callback);},/** * @api private */runTo:function runTo(state,done){this._asm.runTo(state,done,this);return this;},/** * Aborts a request, emitting the error and complete events. * * @!macro nobrowser * @example Aborting a request after sending * var params = { * Bucket: 'bucket', Key: 'key', * Body: Buffer.alloc(1024 * 1024 * 5) // 5MB payload * }; * var request = s3.putObject(params); * request.send(function (err, data) { * if (err) console.log("Error:", err.code, err.message); * else console.log(data); * }); * * // abort request in 1 second * setTimeout(request.abort.bind(request), 1000); * * // prints "Error: RequestAbortedError Request aborted by user" * @return [AWS.Request] the same request object, for chaining. * @since v1.4.0 */abort:function abort(){this.removeAllListeners('validateResponse');this.removeAllListeners('extractError');this.on('validateResponse',function addAbortedError(resp){resp.error=AWS.util.error(new Error('Request aborted by user'),{code:'RequestAbortedError',retryable:false});});if(this.httpRequest.stream&&!this.httpRequest.stream.didCallback){// abort HTTP stream this.httpRequest.stream.abort();if(this.httpRequest._abortCallback){this.httpRequest._abortCallback();}else{this.removeAllListeners('send');// haven't sent yet, so let's not }}return this;},/** * Iterates over each page of results given a pageable request, calling * the provided callback with each page of data. After all pages have been * retrieved, the callback is called with `null` data. * * @note This operation can generate multiple requests to a service. * @example Iterating over multiple pages of objects in an S3 bucket * var pages = 1; * s3.listObjects().eachPage(function(err, data) { * if (err) return; * console.log("Page", pages++); * console.log(data); * }); * @example Iterating over multiple pages with an asynchronous callback * s3.listObjects(params).eachPage(function(err, data, done) { * doSomethingAsyncAndOrExpensive(function() { * // The next page of results isn't fetched until done is called * done(); * }); * }); * @callback callback function(err, data, [doneCallback]) * Called with each page of resulting data from the request. If the * optional `doneCallback` is provided in the function, it must be called * when the callback is complete. * * @param err [Error] an error object, if an error occurred. * @param data [Object] a single page of response data. If there is no * more data, this object will be `null`. * @param doneCallback [Function] an optional done callback. If this * argument is defined in the function declaration, it should be called * when the next page is ready to be retrieved. This is useful for * controlling serial pagination across asynchronous operations. * @return [Boolean] if the callback returns `false`, pagination will * stop. * * @see AWS.Request.eachItem * @see AWS.Response.nextPage * @since v1.4.0 */eachPage:function eachPage(callback){// Make all callbacks async-ish callback=AWS.util.fn.makeAsync(callback,3);function wrappedCallback(response){callback.call(response,response.error,response.data,function(result){if(result===false)return;if(response.hasNextPage()){response.nextPage().on('complete',wrappedCallback).send();}else{callback.call(response,null,null,AWS.util.fn.noop);}});}this.on('complete',wrappedCallback).send();},/** * Enumerates over individual items of a request, paging the responses if * necessary. * * @api experimental * @since v1.4.0 */eachItem:function eachItem(callback){var self=this;function wrappedCallback(err,data){if(err)return callback(err,null);if(data===null)return callback(null,null);var config=self.service.paginationConfig(self.operation);var resultKey=config.resultKey;if(Array.isArray(resultKey))resultKey=resultKey[0];var items=jmespath.search(data,resultKey);var continueIteration=true;AWS.util.arrayEach(items,function(item){continueIteration=callback(null,item);if(continueIteration===false){return AWS.util.abort;}});return continueIteration;}this.eachPage(wrappedCallback);},/** * @return [Boolean] whether the operation can return multiple pages of * response data. * @see AWS.Response.eachPage * @since v1.4.0 */isPageable:function isPageable(){return this.service.paginationConfig(this.operation)?true:false;},/** * Sends the request and converts the request object into a readable stream * that can be read from or piped into a writable stream. * * @note The data read from a readable stream contains only * the raw HTTP body contents. * @example Manually reading from a stream * request.createReadStream().on('data', function(data) { * console.log("Got data:", data.toString()); * }); * @example Piping a request body into a file * var out = fs.createWriteStream('/path/to/outfile.jpg'); * s3.service.getObject(params).createReadStream().pipe(out); * @return [Stream] the readable stream object that can be piped * or read from (by registering 'data' event listeners). * @!macro nobrowser */createReadStream:function createReadStream(){var streams=AWS.util.stream;var req=this;var stream=null;if(AWS.HttpClient.streamsApiVersion===2){stream=new streams.PassThrough();process.nextTick(function(){req.send();});}else{stream=new streams.Stream();stream.readable=true;stream.sent=false;stream.on('newListener',function(event){if(!stream.sent&&event==='data'){stream.sent=true;process.nextTick(function(){req.send();});}});}this.on('error',function(err){stream.emit('error',err);});this.on('httpHeaders',function streamHeaders(statusCode,headers,resp){if(statusCode<300){req.removeListener('httpData',AWS.EventListeners.Core.HTTP_DATA);req.removeListener('httpError',AWS.EventListeners.Core.HTTP_ERROR);req.on('httpError',function streamHttpError(error){resp.error=error;resp.error.retryable=false;});var shouldCheckContentLength=false;var expectedLen;if(req.httpRequest.method!=='HEAD'){expectedLen=parseInt(headers['content-length'],10);}if(expectedLen!==undefined&&!isNaN(expectedLen)&&expectedLen>=0){shouldCheckContentLength=true;var receivedLen=0;}var checkContentLengthAndEmit=function checkContentLengthAndEmit(){if(shouldCheckContentLength&&receivedLen!==expectedLen){stream.emit('error',AWS.util.error(new Error('Stream content length mismatch. Received '+receivedLen+' of '+expectedLen+' bytes.'),{code:'StreamContentLengthMismatch'}));}else if(AWS.HttpClient.streamsApiVersion===2){stream.end();}else{stream.emit('end');}};var httpStream=resp.httpResponse.createUnbufferedStream();if(AWS.HttpClient.streamsApiVersion===2){if(shouldCheckContentLength){var lengthAccumulator=new streams.PassThrough();lengthAccumulator._write=function(chunk){if(chunk&&chunk.length){receivedLen+=chunk.length;}return streams.PassThrough.prototype._write.apply(this,arguments);};lengthAccumulator.on('end',checkContentLengthAndEmit);stream.on('error',function(err){shouldCheckContentLength=false;httpStream.unpipe(lengthAccumulator);lengthAccumulator.emit('end');lengthAccumulator.end();});httpStream.pipe(lengthAccumulator).pipe(stream,{end:false});}else{httpStream.pipe(stream);}}else{if(shouldCheckContentLength){httpStream.on('data',function(arg){if(arg&&arg.length){receivedLen+=arg.length;}});}httpStream.on('data',function(arg){stream.emit('data',arg);});httpStream.on('end',checkContentLengthAndEmit);}httpStream.on('error',function(err){shouldCheckContentLength=false;stream.emit('error',err);});}});return stream;},/** * @param [Array,Response] args This should be the response object, * or an array of args to send to the event. * @api private */emitEvent:function emit(eventName,args,done){if(typeof args==='function'){done=args;args=null;}if(!done)done=function done(){};if(!args)args=this.eventParameters(eventName,this.response);var origEmit=AWS.SequentialExecutor.prototype.emit;origEmit.call(this,eventName,args,function(err){if(err)this.response.error=err;done.call(this,err);});},/** * @api private */eventParameters:function eventParameters(eventName){switch(eventName){case'restart':case'validate':case'sign':case'build':case'afterValidate':case'afterBuild':return[this];case'error':return[this.response.error,this.response];default:return[this.response];}},/** * @api private */presign:function presign(expires,callback){if(!callback&&typeof expires==='function'){callback=expires;expires=null;}return new AWS.Signers.Presign().sign(this.toGet(),expires,callback);},/** * @api private */isPresigned:function isPresigned(){return Object.prototype.hasOwnProperty.call(this.httpRequest.headers,'presigned-expires');},/** * @api private */toUnauthenticated:function toUnauthenticated(){this._unAuthenticated=true;this.removeListener('validate',AWS.EventListeners.Core.VALIDATE_CREDENTIALS);this.removeListener('sign',AWS.EventListeners.Core.SIGN);return this;},/** * @api private */toGet:function toGet(){if(this.service.api.protocol==='query'||this.service.api.protocol==='ec2'){this.removeListener('build',this.buildAsGet);this.addListener('build',this.buildAsGet);}return this;},/** * @api private */buildAsGet:function buildAsGet(request){request.httpRequest.method='GET';request.httpRequest.path=request.service.endpoint.path+'?'+request.httpRequest.body;request.httpRequest.body='';// don't need these headers on a GET request delete request.httpRequest.headers['Content-Length'];delete request.httpRequest.headers['Content-Type'];},/** * @api private */haltHandlersOnError:function haltHandlersOnError(){this._haltHandlersOnError=true;}});/** * @api private */AWS.Request.addPromisesToClass=function addPromisesToClass(PromiseDependency){this.prototype.promise=function promise(){var self=this;// append to user agent this.httpRequest.appendToUserAgent('promise');return new PromiseDependency(function(resolve,reject){self.on('complete',function(resp){if(resp.error){reject(resp.error);}else{// define $response property so that it is not enumerable // this prevents circular reference errors when stringifying the JSON object resolve(Object.defineProperty(resp.data||{},'$response',{value:resp}));}});self.runTo();});};};/** * @api private */AWS.Request.deletePromisesFromClass=function deletePromisesFromClass(){delete this.prototype.promise;};AWS.util.addPromises(AWS.Request);AWS.util.mixin(AWS.Request,AWS.SequentialExecutor);}).call(this);}).call(this,require('_process'));},{"./core":19,"./state_machine":73,"_process":91,"jmespath":90}],59:[function(require,module,exports){/** * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You * may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */var AWS=require('./core');var inherit=AWS.util.inherit;var jmespath=require('jmespath');/** * @api private */function CHECK_ACCEPTORS(resp){var waiter=resp.request._waiter;var acceptors=waiter.config.acceptors;var acceptorMatched=false;var state='retry';acceptors.forEach(function(acceptor){if(!acceptorMatched){var matcher=waiter.matchers[acceptor.matcher];if(matcher&&matcher(resp,acceptor.expected,acceptor.argument)){acceptorMatched=true;state=acceptor.state;}}});if(!acceptorMatched&&resp.error)state='failure';if(state==='success'){waiter.setSuccess(resp);}else{waiter.setError(resp,state==='retry');}}/** * @api private */AWS.ResourceWaiter=inherit({/** * Waits for a given state on a service object * @param service [Service] the service object to wait on * @param state [String] the state (defined in waiter configuration) to wait * for. * @example Create a waiter for running EC2 instances * var ec2 = new AWS.EC2; * var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning'); */constructor:function constructor(service,state){this.service=service;this.state=state;this.loadWaiterConfig(this.state);},service:null,state:null,config:null,matchers:{path:function path(resp,expected,argument){try{var result=jmespath.search(resp.data,argument);}catch(err){return false;}return jmespath.strictDeepEqual(result,expected);},pathAll:function pathAll(resp,expected,argument){try{var results=jmespath.search(resp.data,argument);}catch(err){return false;}if(!Array.isArray(results))results=[results];var numResults=results.length;if(!numResults)return false;for(var ind=0;ind resp.data * { TableNames: * [ 'table1', 'table2', ... ] } * ``` * * The `data` property can be null if an error occurs (see below). * * ## The `error` property * * In the event of a service error (or transfer error), the * `response.error` property will be filled with the given * error data in the form: * * ``` * { code: 'SHORT_UNIQUE_ERROR_CODE', * message: 'Some human readable error message' } * ``` * * In the case of an error, the `data` property will be `null`. * Note that if you handle events that can be in a failure state, * you should always check whether `response.error` is set * before attempting to access the `response.data` property. * * @!attribute data * @readonly * @!group Data Properties * @note Inside of a {AWS.Request~httpData} event, this * property contains a single raw packet instead of the * full de-serialized service response. * @return [Object] the de-serialized response data * from the service. * * @!attribute error * An structure containing information about a service * or networking error. * @readonly * @!group Data Properties * @note This attribute is only filled if a service or * networking error occurs. * @return [Error] * * code [String] a unique short code representing the * error that was emitted. * * message [String] a longer human readable error message * * retryable [Boolean] whether the error message is * retryable. * * statusCode [Numeric] in the case of a request that reached the service, * this value contains the response status code. * * time [Date] the date time object when the error occurred. * * hostname [String] set when a networking error occurs to easily * identify the endpoint of the request. * * region [String] set when a networking error occurs to easily * identify the region of the request. * * @!attribute requestId * @readonly * @!group Data Properties * @return [String] the unique request ID associated with the response. * Log this value when debugging requests for AWS support. * * @!attribute retryCount * @readonly * @!group Operation Properties * @return [Integer] the number of retries that were * attempted before the request was completed. * * @!attribute redirectCount * @readonly * @!group Operation Properties * @return [Integer] the number of redirects that were * followed before the request was completed. * * @!attribute httpResponse * @readonly * @!group HTTP Properties * @return [AWS.HttpResponse] the raw HTTP response object * containing the response headers and body information * from the server. * * @see AWS.Request */AWS.Response=inherit({/** * @api private */constructor:function Response(request){this.request=request;this.data=null;this.error=null;this.retryCount=0;this.redirectCount=0;this.httpResponse=new AWS.HttpResponse();if(request){this.maxRetries=request.service.numRetries();this.maxRedirects=request.service.config.maxRedirects;}},/** * Creates a new request for the next page of response data, calling the * callback with the page data if a callback is provided. * * @callback callback function(err, data) * Called when a page of data is returned from the next request. * * @param err [Error] an error object, if an error occurred in the request * @param data [Object] the next page of data, or null, if there are no * more pages left. * @return [AWS.Request] the request object for the next page of data * @return [null] if no callback is provided and there are no pages left * to retrieve. * @since v1.4.0 */nextPage:function nextPage(callback){var config;var service=this.request.service;var operation=this.request.operation;try{config=service.paginationConfig(operation,true);}catch(e){this.error=e;}if(!this.hasNextPage()){if(callback)callback(this.error,null);else if(this.error)throw this.error;return null;}var params=AWS.util.copy(this.request.params);if(!this.nextPageTokens){return callback?callback(null,null):null;}else{var inputTokens=config.inputToken;if(typeof inputTokens==='string')inputTokens=[inputTokens];for(var i=0;i-1){listeners.splice(position,1);}}return this;},removeAllListeners:function removeAllListeners(eventName){if(eventName){delete this._events[eventName];}else{this._events={};}return this;},/** * @api private */emit:function emit(eventName,eventArgs,doneCallback){if(!doneCallback)doneCallback=function doneCallback(){};var listeners=this.listeners(eventName);var count=listeners.length;this.callListeners(listeners,eventArgs,doneCallback);return count>0;},/** * @api private */callListeners:function callListeners(listeners,args,doneCallback,prevError){var self=this;var error=prevError||null;function callNextListener(err){if(err){error=AWS.util.error(error||new Error(),err);if(self._haltHandlersOnError){return doneCallback.call(self,error);}}self.callListeners(listeners,args,doneCallback,error);}while(listeners.length>0){var listener=listeners.shift();if(listener._isAsync){// asynchronous listener listener.apply(self,args.concat([callNextListener]));return;// stop here, callNextListener will continue }else{// synchronous listener try{listener.apply(self,args);}catch(err){error=AWS.util.error(error||new Error(),err);}if(error&&self._haltHandlersOnError){doneCallback.call(self,error);return;}}}doneCallback.call(self,error);},/** * Adds or copies a set of listeners from another list of * listeners or SequentialExecutor object. * * @param listeners [map>, AWS.SequentialExecutor] * a list of events and callbacks, or an event emitter object * containing listeners to add to this emitter object. * @return [AWS.SequentialExecutor] the emitter object, for chaining. * @example Adding listeners from a map of listeners * emitter.addListeners({ * event1: [function() { ... }, function() { ... }], * event2: [function() { ... }] * }); * emitter.emit('event1'); // emitter has event1 * emitter.emit('event2'); // emitter has event2 * @example Adding listeners from another emitter object * var emitter1 = new AWS.SequentialExecutor(); * emitter1.on('event1', function() { ... }); * emitter1.on('event2', function() { ... }); * var emitter2 = new AWS.SequentialExecutor(); * emitter2.addListeners(emitter1); * emitter2.emit('event1'); // emitter2 has event1 * emitter2.emit('event2'); // emitter2 has event2 */addListeners:function addListeners(listeners){var self=this;// extract listeners if parameter is an SequentialExecutor object if(listeners._events)listeners=listeners._events;AWS.util.each(listeners,function(event,callbacks){if(typeof callbacks==='function')callbacks=[callbacks];AWS.util.arrayEach(callbacks,function(callback){self.on(event,callback);});});return self;},/** * Registers an event with {on} and saves the callback handle function * as a property on the emitter object using a given `name`. * * @param name [String] the property name to set on this object containing * the callback function handle so that the listener can be removed in * the future. * @param (see on) * @return (see on) * @example Adding a named listener DATA_CALLBACK * var listener = function() { doSomething(); }; * emitter.addNamedListener('DATA_CALLBACK', 'data', listener); * * // the following prints: true * console.log(emitter.DATA_CALLBACK == listener); */addNamedListener:function addNamedListener(name,eventName,callback,toHead){this[name]=callback;this.addListener(eventName,callback,toHead);return this;},/** * @api private */addNamedAsyncListener:function addNamedAsyncListener(name,eventName,callback,toHead){callback._isAsync=true;return this.addNamedListener(name,eventName,callback,toHead);},/** * Helper method to add a set of named listeners using * {addNamedListener}. The callback contains a parameter * with a handle to the `addNamedListener` method. * * @callback callback function(add) * The callback function is called immediately in order to provide * the `add` function to the block. This simplifies the addition of * a large group of named listeners. * @param add [Function] the {addNamedListener} function to call * when registering listeners. * @example Adding a set of named listeners * emitter.addNamedListeners(function(add) { * add('DATA_CALLBACK', 'data', function() { ... }); * add('OTHER', 'otherEvent', function() { ... }); * add('LAST', 'lastEvent', function() { ... }); * }); * * // these properties are now set: * emitter.DATA_CALLBACK; * emitter.OTHER; * emitter.LAST; */addNamedListeners:function addNamedListeners(callback){var self=this;callback(function(){self.addNamedListener.apply(self,arguments);},function(){self.addNamedAsyncListener.apply(self,arguments);});return this;}});/** * {on} is the prefered method. * @api private */AWS.SequentialExecutor.prototype.addListener=AWS.SequentialExecutor.prototype.on;/** * @api private */module.exports=AWS.SequentialExecutor;},{"./core":19}],62:[function(require,module,exports){(function(process){(function(){var AWS=require('./core');var Api=require('./model/api');var regionConfig=require('./region_config');var inherit=AWS.util.inherit;var clientCount=0;var region_utils=require('./region/utils');/** * The service class representing an AWS service. * * @class_abstract This class is an abstract class. * * @!attribute apiVersions * @return [Array] the list of API versions supported by this service. * @readonly */AWS.Service=inherit({/** * Create a new service object with a configuration object * * @param config [map] a map of configuration options */constructor:function Service(config){if(!this.loadServiceClass){throw AWS.util.error(new Error(),'Service must be constructed with `new\' operator');}if(config){if(config.region){var region=config.region;if(region_utils.isFipsRegion(region)){config.region=region_utils.getRealRegion(region);config.useFipsEndpoint=true;}if(region_utils.isGlobalRegion(region)){config.region=region_utils.getRealRegion(region);}}if(typeof config.useDualstack==='boolean'&&typeof config.useDualstackEndpoint!=='boolean'){config.useDualstackEndpoint=config.useDualstack;}}var ServiceClass=this.loadServiceClass(config||{});if(ServiceClass){var originalConfig=AWS.util.copy(config);var svc=new ServiceClass(config);Object.defineProperty(svc,'_originalConfig',{get:function get(){return originalConfig;},enumerable:false,configurable:true});svc._clientId=++clientCount;return svc;}this.initialize(config);},/** * @api private */initialize:function initialize(config){var svcConfig=AWS.config[this.serviceIdentifier];this.config=new AWS.Config(AWS.config);if(svcConfig)this.config.update(svcConfig,true);if(config)this.config.update(config,true);this.validateService();if(!this.config.endpoint)regionConfig.configureEndpoint(this);this.config.endpoint=this.endpointFromTemplate(this.config.endpoint);this.setEndpoint(this.config.endpoint);//enable attaching listeners to service client AWS.SequentialExecutor.call(this);AWS.Service.addDefaultMonitoringListeners(this);if((this.config.clientSideMonitoring||AWS.Service._clientSideMonitoring)&&this.publisher){var publisher=this.publisher;this.addNamedListener('PUBLISH_API_CALL','apiCall',function PUBLISH_API_CALL(event){process.nextTick(function(){publisher.eventHandler(event);});});this.addNamedListener('PUBLISH_API_ATTEMPT','apiCallAttempt',function PUBLISH_API_ATTEMPT(event){process.nextTick(function(){publisher.eventHandler(event);});});}},/** * @api private */validateService:function validateService(){},/** * @api private */loadServiceClass:function loadServiceClass(serviceConfig){var config=serviceConfig;if(!AWS.util.isEmpty(this.api)){return null;}else if(config.apiConfig){return AWS.Service.defineServiceApi(this.constructor,config.apiConfig);}else if(!this.constructor.services){return null;}else{config=new AWS.Config(AWS.config);config.update(serviceConfig,true);var version=config.apiVersions[this.constructor.serviceIdentifier];version=version||config.apiVersion;return this.getLatestServiceClass(version);}},/** * @api private */getLatestServiceClass:function getLatestServiceClass(version){version=this.getLatestServiceVersion(version);if(this.constructor.services[version]===null){AWS.Service.defineServiceApi(this.constructor,version);}return this.constructor.services[version];},/** * @api private */getLatestServiceVersion:function getLatestServiceVersion(version){if(!this.constructor.services||this.constructor.services.length===0){throw new Error('No services defined on '+this.constructor.serviceIdentifier);}if(!version){version='latest';}else if(AWS.util.isType(version,Date)){version=AWS.util.date.iso8601(version).split('T')[0];}if(Object.hasOwnProperty(this.constructor.services,version)){return version;}var keys=Object.keys(this.constructor.services).sort();var selectedVersion=null;for(var i=keys.length-1;i>=0;i--){// versions that end in "*" are not available on disk and can be // skipped, so do not choose these as selectedVersions if(keys[i][keys[i].length-1]!=='*'){selectedVersion=keys[i];}if(keys[i].substr(0,10)<=version){return selectedVersion;}}throw new Error('Could not find '+this.constructor.serviceIdentifier+' API to satisfy version constraint `'+version+'\'');},/** * @api private */api:{},/** * @api private */defaultRetryCount:3,/** * @api private */customizeRequests:function customizeRequests(callback){if(!callback){this.customRequestHandler=null;}else if(typeof callback==='function'){this.customRequestHandler=callback;}else{throw new Error('Invalid callback type \''+_typeof(callback)+'\' provided in customizeRequests');}},/** * Calls an operation on a service with the given input parameters. * * @param operation [String] the name of the operation to call on the service. * @param params [map] a map of input options for the operation * @callback callback function(err, data) * If a callback is supplied, it is called when a response is returned * from the service. * @param err [Error] the error object returned from the request. * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. */makeRequest:function makeRequest(operation,params,callback){if(typeof params==='function'){callback=params;params=null;}params=params||{};if(this.config.params){// copy only toplevel bound params var rules=this.api.operations[operation];if(rules){params=AWS.util.copy(params);AWS.util.each(this.config.params,function(key,value){if(rules.input.members[key]){if(params[key]===undefined||params[key]===null){params[key]=value;}}});}}var request=new AWS.Request(this,operation,params);this.addAllRequestListeners(request);this.attachMonitoringEmitter(request);if(callback)request.send(callback);return request;},/** * Calls an operation on a service with the given input parameters, without * any authentication data. This method is useful for "public" API operations. * * @param operation [String] the name of the operation to call on the service. * @param params [map] a map of input options for the operation * @callback callback function(err, data) * If a callback is supplied, it is called when a response is returned * from the service. * @param err [Error] the error object returned from the request. * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. */makeUnauthenticatedRequest:function makeUnauthenticatedRequest(operation,params,callback){if(typeof params==='function'){callback=params;params={};}var request=this.makeRequest(operation,params).toUnauthenticated();return callback?request.send(callback):request;},/** * Waits for a given state * * @param state [String] the state on the service to wait for * @param params [map] a map of parameters to pass with each request * @option params $waiter [map] a map of configuration options for the waiter * @option params $waiter.delay [Number] The number of seconds to wait between * requests * @option params $waiter.maxAttempts [Number] The maximum number of requests * to send while waiting * @callback callback function(err, data) * If a callback is supplied, it is called when a response is returned * from the service. * @param err [Error] the error object returned from the request. * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. */waitFor:function waitFor(state,params,callback){var waiter=new AWS.ResourceWaiter(this,state);return waiter.wait(params,callback);},/** * @api private */addAllRequestListeners:function addAllRequestListeners(request){var list=[AWS.events,AWS.EventListeners.Core,this.serviceInterface(),AWS.EventListeners.CorePost];for(var i=0;i299){if(error.code)monitoringEvent.FinalAwsException=error.code;if(error.message)monitoringEvent.FinalAwsExceptionMessage=error.message;}else{if(error.code||error.name)monitoringEvent.FinalSdkException=error.code||error.name;if(error.message)monitoringEvent.FinalSdkExceptionMessage=error.message;}}return monitoringEvent;},/** * Event recording metrics for an API call attempt. * @returns {object} a subset of api call attempt metrics * @api private */apiAttemptEvent:function apiAttemptEvent(request){var api=request.service.api.operations[request.operation];var monitoringEvent={Type:'ApiCallAttempt',Api:api?api.name:request.operation,Version:1,Service:request.service.api.serviceId||request.service.api.endpointPrefix,Fqdn:request.httpRequest.endpoint.hostname,UserAgent:request.httpRequest.getUserAgent()};var response=request.response;if(response.httpResponse.statusCode){monitoringEvent.HttpStatusCode=response.httpResponse.statusCode;}if(!request._unAuthenticated&&request.service.config.credentials&&request.service.config.credentials.accessKeyId){monitoringEvent.AccessKey=request.service.config.credentials.accessKeyId;}if(!response.httpResponse.headers)return monitoringEvent;if(request.httpRequest.headers['x-amz-security-token']){monitoringEvent.SessionToken=request.httpRequest.headers['x-amz-security-token'];}if(response.httpResponse.headers['x-amzn-requestid']){monitoringEvent.XAmznRequestId=response.httpResponse.headers['x-amzn-requestid'];}if(response.httpResponse.headers['x-amz-request-id']){monitoringEvent.XAmzRequestId=response.httpResponse.headers['x-amz-request-id'];}if(response.httpResponse.headers['x-amz-id-2']){monitoringEvent.XAmzId2=response.httpResponse.headers['x-amz-id-2'];}return monitoringEvent;},/** * Add metrics of failed request. * @api private */attemptFailEvent:function attemptFailEvent(request){var monitoringEvent=this.apiAttemptEvent(request);var response=request.response;var error=response.error;if(response.httpResponse.statusCode>299){if(error.code)monitoringEvent.AwsException=error.code;if(error.message)monitoringEvent.AwsExceptionMessage=error.message;}else{if(error.code||error.name)monitoringEvent.SdkException=error.code||error.name;if(error.message)monitoringEvent.SdkExceptionMessage=error.message;}return monitoringEvent;},/** * Attach listeners to request object to fetch metrics of each request * and emit data object through \'ApiCall\' and \'ApiCallAttempt\' events. * @api private */attachMonitoringEmitter:function attachMonitoringEmitter(request){var attemptTimestamp;//timestamp marking the beginning of a request attempt var attemptStartRealTime;//Start time of request attempt. Used to calculating attemptLatency var attemptLatency;//latency from request sent out to http response reaching SDK var callStartRealTime;//Start time of API call. Used to calculating API call latency var attemptCount=0;//request.retryCount is not reliable here var region;//region cache region for each attempt since it can be updated in plase (e.g. s3) var callTimestamp;//timestamp when the request is created var self=this;var addToHead=true;request.on('validate',function(){callStartRealTime=AWS.util.realClock.now();callTimestamp=Date.now();},addToHead);request.on('sign',function(){attemptStartRealTime=AWS.util.realClock.now();attemptTimestamp=Date.now();region=request.httpRequest.region;attemptCount++;},addToHead);request.on('validateResponse',function(){attemptLatency=Math.round(AWS.util.realClock.now()-attemptStartRealTime);});request.addNamedListener('API_CALL_ATTEMPT','success',function API_CALL_ATTEMPT(){var apiAttemptEvent=self.apiAttemptEvent(request);apiAttemptEvent.Timestamp=attemptTimestamp;apiAttemptEvent.AttemptLatency=attemptLatency>=0?attemptLatency:0;apiAttemptEvent.Region=region;self.emit('apiCallAttempt',[apiAttemptEvent]);});request.addNamedListener('API_CALL_ATTEMPT_RETRY','retry',function API_CALL_ATTEMPT_RETRY(){var apiAttemptEvent=self.attemptFailEvent(request);apiAttemptEvent.Timestamp=attemptTimestamp;//attemptLatency may not be available if fail before response attemptLatency=attemptLatency||Math.round(AWS.util.realClock.now()-attemptStartRealTime);apiAttemptEvent.AttemptLatency=attemptLatency>=0?attemptLatency:0;apiAttemptEvent.Region=region;self.emit('apiCallAttempt',[apiAttemptEvent]);});request.addNamedListener('API_CALL','complete',function API_CALL(){var apiCallEvent=self.apiCallEvent(request);apiCallEvent.AttemptCount=attemptCount;if(apiCallEvent.AttemptCount<=0)return;apiCallEvent.Timestamp=callTimestamp;var latency=Math.round(AWS.util.realClock.now()-callStartRealTime);apiCallEvent.Latency=latency>=0?latency:0;var response=request.response;if(response.error&&response.error.retryable&&typeof response.retryCount==='number'&&typeof response.maxRetries==='number'&&response.retryCount>=response.maxRetries){apiCallEvent.MaxRetriesExceeded=1;}self.emit('apiCall',[apiCallEvent]);});},/** * Override this method to setup any custom request listeners for each * new request to the service. * * @method_abstract This is an abstract method. */setupRequestListeners:function setupRequestListeners(request){},/** * Gets the signing name for a given request * @api private */getSigningName:function getSigningName(){return this.api.signingName||this.api.endpointPrefix;},/** * Gets the signer class for a given request * @api private */getSignerClass:function getSignerClass(request){var version;// get operation authtype if present var operation=null;var authtype='';if(request){var operations=request.service.api.operations||{};operation=operations[request.operation]||null;authtype=operation?operation.authtype:'';}if(this.config.signatureVersion){version=this.config.signatureVersion;}else if(authtype==='v4'||authtype==='v4-unsigned-body'){version='v4';}else if(authtype==='bearer'){version='bearer';}else{version=this.api.signatureVersion;}return AWS.Signers.RequestSigner.getVersion(version);},/** * @api private */serviceInterface:function serviceInterface(){switch(this.api.protocol){case'ec2':return AWS.EventListeners.Query;case'query':return AWS.EventListeners.Query;case'json':return AWS.EventListeners.Json;case'rest-json':return AWS.EventListeners.RestJson;case'rest-xml':return AWS.EventListeners.RestXml;}if(this.api.protocol){throw new Error('Invalid service `protocol\' '+this.api.protocol+' in API config');}},/** * @api private */successfulResponse:function successfulResponse(resp){return resp.httpResponse.statusCode<300;},/** * How many times a failed request should be retried before giving up. * the defaultRetryCount can be overriden by service classes. * * @api private */numRetries:function numRetries(){if(this.config.maxRetries!==undefined){return this.config.maxRetries;}else{return this.defaultRetryCount;}},/** * @api private */retryDelays:function retryDelays(retryCount,err){return AWS.util.calculateRetryDelay(retryCount,this.config.retryDelayOptions,err);},/** * @api private */retryableError:function retryableError(error){if(this.timeoutError(error))return true;if(this.networkingError(error))return true;if(this.expiredCredentialsError(error))return true;if(this.throttledError(error))return true;if(error.statusCode>=500)return true;return false;},/** * @api private */networkingError:function networkingError(error){return error.code==='NetworkingError';},/** * @api private */timeoutError:function timeoutError(error){return error.code==='TimeoutError';},/** * @api private */expiredCredentialsError:function expiredCredentialsError(error){// TODO : this only handles *one* of the expired credential codes return error.code==='ExpiredTokenException';},/** * @api private */clockSkewError:function clockSkewError(error){switch(error.code){case'RequestTimeTooSkewed':case'RequestExpired':case'InvalidSignatureException':case'SignatureDoesNotMatch':case'AuthFailure':case'RequestInTheFuture':return true;default:return false;}},/** * @api private */getSkewCorrectedDate:function getSkewCorrectedDate(){return new Date(Date.now()+this.config.systemClockOffset);},/** * @api private */applyClockOffset:function applyClockOffset(newServerTime){if(newServerTime){this.config.systemClockOffset=newServerTime-Date.now();}},/** * @api private */isClockSkewed:function isClockSkewed(newServerTime){if(newServerTime){return Math.abs(this.getSkewCorrectedDate().getTime()-newServerTime)>=300000;}},/** * @api private */throttledError:function throttledError(error){// this logic varies between services if(error.statusCode===429)return true;switch(error.code){case'ProvisionedThroughputExceededException':case'Throttling':case'ThrottlingException':case'RequestLimitExceeded':case'RequestThrottled':case'RequestThrottledException':case'TooManyRequestsException':case'TransactionInProgressException'://dynamodb case'EC2ThrottledException':return true;default:return false;}},/** * @api private */endpointFromTemplate:function endpointFromTemplate(endpoint){if(typeof endpoint!=='string')return endpoint;var e=endpoint;e=e.replace(/\{service\}/g,this.api.endpointPrefix);e=e.replace(/\{region\}/g,this.config.region);e=e.replace(/\{scheme\}/g,this.config.sslEnabled?'https':'http');return e;},/** * @api private */setEndpoint:function setEndpoint(endpoint){this.endpoint=new AWS.Endpoint(endpoint,this.config);},/** * @api private */paginationConfig:function paginationConfig(operation,throwException){var paginator=this.api.operations[operation].paginator;if(!paginator){if(throwException){var e=new Error();throw AWS.util.error(e,'No pagination configuration for '+operation);}return null;}return paginator;}});AWS.util.update(AWS.Service,{/** * Adds one method for each operation described in the api configuration * * @api private */defineMethods:function defineMethods(svc){AWS.util.each(svc.prototype.api.operations,function iterator(method){if(svc.prototype[method])return;var operation=svc.prototype.api.operations[method];if(operation.authtype==='none'){svc.prototype[method]=function(params,callback){return this.makeUnauthenticatedRequest(method,params,callback);};}else{svc.prototype[method]=function(params,callback){return this.makeRequest(method,params,callback);};}});},/** * Defines a new Service class using a service identifier and list of versions * including an optional set of features (functions) to apply to the class * prototype. * * @param serviceIdentifier [String] the identifier for the service * @param versions [Array] a list of versions that work with this * service * @param features [Object] an object to attach to the prototype * @return [Class] the service class defined by this function. */defineService:function defineService(serviceIdentifier,versions,features){AWS.Service._serviceMap[serviceIdentifier]=true;if(!Array.isArray(versions)){features=versions;versions=[];}var svc=inherit(AWS.Service,features||{});if(typeof serviceIdentifier==='string'){AWS.Service.addVersions(svc,versions);var identifier=svc.serviceIdentifier||serviceIdentifier;svc.serviceIdentifier=identifier;}else{// defineService called with an API svc.prototype.api=serviceIdentifier;AWS.Service.defineMethods(svc);}AWS.SequentialExecutor.call(this.prototype);//util.clientSideMonitoring is only available in node if(!this.prototype.publisher&&AWS.util.clientSideMonitoring){var Publisher=AWS.util.clientSideMonitoring.Publisher;var configProvider=AWS.util.clientSideMonitoring.configProvider;var publisherConfig=configProvider();this.prototype.publisher=new Publisher(publisherConfig);if(publisherConfig.enabled){//if csm is enabled in environment, SDK should send all metrics AWS.Service._clientSideMonitoring=true;}}AWS.SequentialExecutor.call(svc.prototype);AWS.Service.addDefaultMonitoringListeners(svc.prototype);return svc;},/** * @api private */addVersions:function addVersions(svc,versions){if(!Array.isArray(versions))versions=[versions];svc.services=svc.services||{};for(var i=0;i604800){// one week expiry is invalid var message='Presigning does not support expiry time greater '+'than a week with SigV4 signing.';throw AWS.util.error(new Error(),{code:'InvalidExpiryTime',message:message,retryable:false});}request.httpRequest.headers[expiresHeader]=expires;}else if(signerClass===AWS.Signers.S3){var now=request.service?request.service.getSkewCorrectedDate():AWS.util.date.getDate();request.httpRequest.headers[expiresHeader]=parseInt(AWS.util.date.unixTimestamp(now)+expires,10).toString();}else{throw AWS.util.error(new Error(),{message:'Presigning only supports S3 or SigV4 signing.',code:'UnsupportedSigner',retryable:false});}}/** * @api private */function signedUrlSigner(request){var endpoint=request.httpRequest.endpoint;var parsedUrl=AWS.util.urlParse(request.httpRequest.path);var queryParams={};if(parsedUrl.search){queryParams=AWS.util.queryStringParse(parsedUrl.search.substr(1));}var auth=request.httpRequest.headers['Authorization'].split(' ');if(auth[0]==='AWS'){auth=auth[1].split(':');queryParams['Signature']=auth.pop();queryParams['AWSAccessKeyId']=auth.join(':');AWS.util.each(request.httpRequest.headers,function(key,value){if(key===expiresHeader)key='Expires';if(key.indexOf('x-amz-meta-')===0){// Delete existing, potentially not normalized key delete queryParams[key];key=key.toLowerCase();}queryParams[key]=value;});delete request.httpRequest.headers[expiresHeader];delete queryParams['Authorization'];delete queryParams['Host'];}else if(auth[0]==='AWS4-HMAC-SHA256'){// SigV4 signing auth.shift();var rest=auth.join(' ');var signature=rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];queryParams['X-Amz-Signature']=signature;delete queryParams['Expires'];}// build URL endpoint.pathname=parsedUrl.pathname;endpoint.search=AWS.util.queryParamsToString(queryParams);}/** * @api private */AWS.Signers.Presign=inherit({/** * @api private */sign:function sign(request,expireTime,callback){request.httpRequest.headers[expiresHeader]=expireTime||3600;request.on('build',signedUrlBuilder);request.on('sign',signedUrlSigner);request.removeListener('afterBuild',AWS.EventListeners.Core.SET_CONTENT_LENGTH);request.removeListener('afterBuild',AWS.EventListeners.Core.COMPUTE_SHA256);request.emit('beforePresign',[request]);if(callback){request.build(function(){if(this.response.error)callback(this.response.error);else{callback(null,AWS.util.urlFormat(request.httpRequest.endpoint));}});}else{request.build();if(request.response.error)throw request.response.error;return AWS.util.urlFormat(request.httpRequest.endpoint);}}});/** * @api private */module.exports=AWS.Signers.Presign;},{"../core":19}],66:[function(require,module,exports){var AWS=require('../core');var inherit=AWS.util.inherit;/** * @api private */AWS.Signers.RequestSigner=inherit({constructor:function RequestSigner(request){this.request=request;},setServiceClientId:function setServiceClientId(id){this.serviceClientId=id;},getServiceClientId:function getServiceClientId(){return this.serviceClientId;}});AWS.Signers.RequestSigner.getVersion=function getVersion(version){switch(version){case'v2':return AWS.Signers.V2;case'v3':return AWS.Signers.V3;case's3v4':return AWS.Signers.V4;case'v4':return AWS.Signers.V4;case's3':return AWS.Signers.S3;case'v3https':return AWS.Signers.V3Https;case'bearer':return AWS.Signers.Bearer;}throw new Error('Unknown signing version '+version);};require('./v2');require('./v3');require('./v3https');require('./v4');require('./s3');require('./presign');require('./bearer');},{"../core":19,"./bearer":64,"./presign":65,"./s3":67,"./v2":68,"./v3":69,"./v3https":70,"./v4":71}],67:[function(require,module,exports){var AWS=require('../core');var inherit=AWS.util.inherit;/** * @api private */AWS.Signers.S3=inherit(AWS.Signers.RequestSigner,{/** * When building the stringToSign, these sub resource params should be * part of the canonical resource string with their NON-decoded values */subResources:{'acl':1,'accelerate':1,'analytics':1,'cors':1,'lifecycle':1,'delete':1,'inventory':1,'location':1,'logging':1,'metrics':1,'notification':1,'partNumber':1,'policy':1,'requestPayment':1,'replication':1,'restore':1,'tagging':1,'torrent':1,'uploadId':1,'uploads':1,'versionId':1,'versioning':1,'versions':1,'website':1},// when building the stringToSign, these querystring params should be // part of the canonical resource string with their NON-encoded values responseHeaders:{'response-content-type':1,'response-content-language':1,'response-expires':1,'response-cache-control':1,'response-content-disposition':1,'response-content-encoding':1},addAuthorization:function addAuthorization(credentials,date){if(!this.request.headers['presigned-expires']){this.request.headers['X-Amz-Date']=AWS.util.date.rfc822(date);}if(credentials.sessionToken){// presigned URLs require this header to be lowercased this.request.headers['x-amz-security-token']=credentials.sessionToken;}var signature=this.sign(credentials.secretAccessKey,this.stringToSign());var auth='AWS '+credentials.accessKeyId+':'+signature;this.request.headers['Authorization']=auth;},stringToSign:function stringToSign(){var r=this.request;var parts=[];parts.push(r.method);parts.push(r.headers['Content-MD5']||'');parts.push(r.headers['Content-Type']||'');// This is the "Date" header, but we use X-Amz-Date. // The S3 signing mechanism requires us to pass an empty // string for this Date header regardless. parts.push(r.headers['presigned-expires']||'');var headers=this.canonicalizedAmzHeaders();if(headers)parts.push(headers);parts.push(this.canonicalizedResource());return parts.join('\n');},canonicalizedAmzHeaders:function canonicalizedAmzHeaders(){var amzHeaders=[];AWS.util.each(this.request.headers,function(name){if(name.match(/^x-amz-/i))amzHeaders.push(name);});amzHeaders.sort(function(a,b){return a.toLowerCase()=0?'&':'?';this.request.path+=sep+AWS.util.queryParamsToString(qs);},authorization:function authorization(credentials,datetime){var parts=[];var credString=this.credentialString(datetime);parts.push(this.algorithm+' Credential='+credentials.accessKeyId+'/'+credString);parts.push('SignedHeaders='+this.signedHeaders());parts.push('Signature='+this.signature(credentials,datetime));return parts.join(', ');},signature:function signature(credentials,datetime){var signingKey=v4Credentials.getSigningKey(credentials,datetime.substr(0,8),this.request.region,this.serviceName,this.signatureCache);return AWS.util.crypto.hmac(signingKey,this.stringToSign(datetime),'hex');},stringToSign:function stringToSign(datetime){var parts=[];parts.push('AWS4-HMAC-SHA256');parts.push(datetime);parts.push(this.credentialString(datetime));parts.push(this.hexEncodedHash(this.canonicalString()));return parts.join('\n');},canonicalString:function canonicalString(){var parts=[],pathname=this.request.pathname();if(this.serviceName!=='s3'&&this.signatureVersion!=='s3v4')pathname=AWS.util.uriEscapePath(pathname);parts.push(this.request.method);parts.push(pathname);parts.push(this.request.search());parts.push(this.canonicalHeaders()+'\n');parts.push(this.signedHeaders());parts.push(this.hexEncodedBodyHash());return parts.join('\n');},canonicalHeaders:function canonicalHeaders(){var headers=[];AWS.util.each.call(this,this.request.headers,function(key,item){headers.push([key,item]);});headers.sort(function(a,b){return a[0].toLowerCase()-1&&!request.body){return'UNSIGNED-PAYLOAD';}else if(request.headers['X-Amz-Content-Sha256']){return request.headers['X-Amz-Content-Sha256'];}else{return this.hexEncodedHash(this.request.body||'');}},unsignableHeaders:['authorization','content-type','content-length','user-agent',expiresHeader,'expect','x-amzn-trace-id'],isSignableHeader:function isSignableHeader(key){if(key.toLowerCase().indexOf('x-amz-')===0)return true;return this.unsignableHeaders.indexOf(key)<0;},isPresigned:function isPresigned(){return this.request.headers[expiresHeader]?true:false;}});/** * @api private */module.exports=AWS.Signers.V4;},{"../core":19,"./v4_credentials":72}],72:[function(require,module,exports){var AWS=require('../core');/** * @api private */var cachedSecret={};/** * @api private */var cacheQueue=[];/** * @api private */var maxCacheEntries=50;/** * @api private */var v4Identifier='aws4_request';/** * @api private */module.exports={/** * @api private * * @param date [String] * @param region [String] * @param serviceName [String] * @return [String] */createScope:function createScope(date,region,serviceName){return[date.substr(0,8),region,serviceName,v4Identifier].join('/');},/** * @api private * * @param credentials [Credentials] * @param date [String] * @param region [String] * @param service [String] * @param shouldCache [Boolean] * @return [String] */getSigningKey:function getSigningKey(credentials,date,region,service,shouldCache){var credsIdentifier=AWS.util.crypto.hmac(credentials.secretAccessKey,credentials.accessKeyId,'base64');var cacheKey=[credsIdentifier,date,region,service].join('_');shouldCache=shouldCache!==false;if(shouldCache&&cacheKey in cachedSecret){return cachedSecret[cacheKey];}var kDate=AWS.util.crypto.hmac('AWS4'+credentials.secretAccessKey,date,'buffer');var kRegion=AWS.util.crypto.hmac(kDate,region,'buffer');var kService=AWS.util.crypto.hmac(kRegion,service,'buffer');var signingKey=AWS.util.crypto.hmac(kService,v4Identifier,'buffer');if(shouldCache){cachedSecret[cacheKey]=signingKey;cacheQueue.push(cacheKey);if(cacheQueue.length>maxCacheEntries){// remove the oldest entry (not the least recently used) delete cachedSecret[cacheQueue.shift()];}}return signingKey;},/** * @api private * * Empties the derived signing key cache. Made available for testing purposes * only. */emptyCache:function emptyCache(){cachedSecret={};cacheQueue=[];}};},{"../core":19}],73:[function(require,module,exports){function AcceptorStateMachine(states,state){this.currentState=state||null;this.states=states||{};}AcceptorStateMachine.prototype.runTo=function runTo(finalState,done,bindObject,inputError){if(typeof finalState==='function'){inputError=bindObject;bindObject=done;done=finalState;finalState=null;}var self=this;var state=self.states[self.currentState];state.fn.call(bindObject||self,inputError,function(err){if(err){if(state.fail)self.currentState=state.fail;else return done?done.call(bindObject,err):null;}else{if(state.accept)self.currentState=state.accept;else return done?done.call(bindObject):null;}if(self.currentState===finalState){return done?done.call(bindObject,err):null;}self.runTo(finalState,done,bindObject,err);});};AcceptorStateMachine.prototype.addState=function addState(name,acceptState,failState,fn){if(typeof acceptState==='function'){fn=acceptState;acceptState=null;failState=null;}else if(typeof failState==='function'){fn=failState;failState=null;}if(!this.currentState)this.currentState=name;this.states[name]={accept:acceptState,fail:failState,fn:fn};return this;};/** * @api private */module.exports=AcceptorStateMachine;},{}],74:[function(require,module,exports){(function(process,setImmediate){(function(){/* eslint guard-for-in:0 */var AWS;/** * A set of utility methods for use with the AWS SDK. * * @!attribute abort * Return this value from an iterator function {each} or {arrayEach} * to break out of the iteration. * @example Breaking out of an iterator function * AWS.util.each({a: 1, b: 2, c: 3}, function(key, value) { * if (key == 'b') return AWS.util.abort; * }); * @see each * @see arrayEach * @api private */var util={environment:'nodejs',engine:function engine(){if(util.isBrowser()&&typeof navigator!=='undefined'){return navigator.userAgent;}else{var engine=process.platform+'/'+process.version;if(process.env.AWS_EXECUTION_ENV){engine+=' exec-env/'+process.env.AWS_EXECUTION_ENV;}return engine;}},userAgent:function userAgent(){var name=util.environment;var agent='aws-sdk-'+name+'/'+require('./core').VERSION;if(name==='nodejs')agent+=' '+util.engine();return agent;},uriEscape:function uriEscape(string){var output=encodeURIComponent(string);output=output.replace(/[^A-Za-z0-9_.~\-%]+/g,escape);// AWS percent-encodes some extra non-standard characters in a URI output=output.replace(/[*]/g,function(ch){return'%'+ch.charCodeAt(0).toString(16).toUpperCase();});return output;},uriEscapePath:function uriEscapePath(string){var parts=[];util.arrayEach(string.split('/'),function(part){parts.push(util.uriEscape(part));});return parts.join('/');},urlParse:function urlParse(url){return util.url.parse(url);},urlFormat:function urlFormat(url){return util.url.format(url);},queryStringParse:function queryStringParse(qs){return util.querystring.parse(qs);},queryParamsToString:function queryParamsToString(params){var items=[];var escape=util.uriEscape;var sortedKeys=Object.keys(params).sort();util.arrayEach(sortedKeys,function(name){var value=params[name];var ename=escape(name);var result=ename+'=';if(Array.isArray(value)){var vals=[];util.arrayEach(value,function(item){vals.push(escape(item));});result=ename+'='+vals.sort().join('&'+ename+'=');}else if(value!==undefined&&value!==null){result=ename+'='+escape(value);}items.push(result);});return items.join('&');},readFileSync:function readFileSync(path){if(util.isBrowser())return null;return require('fs').readFileSync(path,'utf-8');},base64:{encode:function encode64(string){if(typeof string==='number'){throw util.error(new Error('Cannot base64 encode number '+string));}if(string===null||typeof string==='undefined'){return string;}var buf=util.buffer.toBuffer(string);return buf.toString('base64');},decode:function decode64(string){if(typeof string==='number'){throw util.error(new Error('Cannot base64 decode number '+string));}if(string===null||typeof string==='undefined'){return string;}return util.buffer.toBuffer(string,'base64');}},buffer:{/** * Buffer constructor for Node buffer and buffer pollyfill */toBuffer:function toBuffer(data,encoding){return typeof util.Buffer.from==='function'&&util.Buffer.from!==Uint8Array.from?util.Buffer.from(data,encoding):new util.Buffer(data,encoding);},alloc:function alloc(size,fill,encoding){if(typeof size!=='number'){throw new Error('size passed to alloc must be a number.');}if(typeof util.Buffer.alloc==='function'){return util.Buffer.alloc(size,fill,encoding);}else{var buf=new util.Buffer(size);if(fill!==undefined&&typeof buf.fill==='function'){buf.fill(fill,undefined,undefined,encoding);}return buf;}},toStream:function toStream(buffer){if(!util.Buffer.isBuffer(buffer))buffer=util.buffer.toBuffer(buffer);var readable=new util.stream.Readable();var pos=0;readable._read=function(size){if(pos>=buffer.length)return readable.push(null);var end=pos+size;if(end>buffer.length)end=buffer.length;readable.push(buffer.slice(pos,end));pos=end;};return readable;},/** * Concatenates a list of Buffer objects. */concat:function concat(buffers){var length=0,offset=0,buffer=null,i;for(i=0;i>>8^tbl[(crc^code)&0xFF];}return(crc^-1)>>>0;},hmac:function hmac(key,string,digest,fn){if(!digest)digest='binary';if(digest==='buffer'){digest=undefined;}if(!fn)fn='sha256';if(typeof string==='string')string=util.buffer.toBuffer(string);return util.crypto.lib.createHmac(fn,key).update(string).digest(digest);},md5:function md5(data,digest,callback){return util.crypto.hash('md5',data,digest,callback);},sha256:function sha256(data,digest,callback){return util.crypto.hash('sha256',data,digest,callback);},hash:function hash(algorithm,data,digest,callback){var hash=util.crypto.createHash(algorithm);if(!digest){digest='binary';}if(digest==='buffer'){digest=undefined;}if(typeof data==='string')data=util.buffer.toBuffer(data);var sliceFn=util.arraySliceFn(data);var isBuffer=util.Buffer.isBuffer(data);//Identifying objects with an ArrayBuffer as buffers if(util.isBrowser()&&typeof ArrayBuffer!=='undefined'&&data&&data.buffer instanceof ArrayBuffer)isBuffer=true;if(callback&&_typeof(data)==='object'&&typeof data.on==='function'&&!isBuffer){data.on('data',function(chunk){hash.update(chunk);});data.on('error',function(err){callback(err);});data.on('end',function(){callback(null,hash.digest(digest));});}else if(callback&&sliceFn&&!isBuffer&&typeof FileReader!=='undefined'){// this might be a File/Blob var index=0,size=1024*512;var reader=new FileReader();reader.onerror=function(){callback(new Error('Failed to read data.'));};reader.onload=function(){var buf=new util.Buffer(new Uint8Array(reader.result));hash.update(buf);index+=buf.length;reader._continueReading();};reader._continueReading=function(){if(index>=data.size){callback(null,hash.digest(digest));return;}var back=index+size;if(back>data.size)back=data.size;reader.readAsArrayBuffer(sliceFn.call(data,index,back));};reader._continueReading();}else{if(util.isBrowser()&&_typeof(data)==='object'&&!isBuffer){data=new util.Buffer(new Uint8Array(data));}var out=hash.update(data).digest(digest);if(callback)callback(null,out);return out;}},toHex:function toHex(data){var out=[];for(var i=0;i=300000,false);return AWS.config.isClockSkewed;}},applyClockOffset:function applyClockOffset(serverTime){if(serverTime)AWS.config.systemClockOffset=serverTime-new Date().getTime();},/** * @api private */extractRequestId:function extractRequestId(resp){var requestId=resp.httpResponse.headers['x-amz-request-id']||resp.httpResponse.headers['x-amzn-requestid'];if(!requestId&&resp.data&&resp.data.ResponseMetadata){requestId=resp.data.ResponseMetadata.RequestId;}if(requestId){resp.requestId=requestId;}if(resp.error){resp.error.requestId=requestId;}},/** * @api private */addPromises:function addPromises(constructors,PromiseDependency){var deletePromises=false;if(PromiseDependency===undefined&&AWS&&AWS.config){PromiseDependency=AWS.config.getPromisesDependency();}if(PromiseDependency===undefined&&typeof Promise!=='undefined'){PromiseDependency=Promise;}if(typeof PromiseDependency!=='function')deletePromises=true;if(!Array.isArray(constructors))constructors=[constructors];for(var ind=0;ind=0){retryCount++;setTimeout(sendRequest,delay+(err.retryAfter||0));return;}}cb(err);};var sendRequest=function sendRequest(){var data='';http.handleRequest(httpRequest,httpOptions,function(httpResponse){httpResponse.on('data',function(chunk){data+=chunk.toString();});httpResponse.on('end',function(){var statusCode=httpResponse.statusCode;if(statusCode<300){cb(null,data);}else{var retryAfter=parseInt(httpResponse.headers['retry-after'],10)*1000||0;var err=util.error(new Error(),{statusCode:statusCode,retryable:statusCode>=500||statusCode===429});if(retryAfter&&err.retryable)err.retryAfter=retryAfter;errCallback(err);}});},errCallback);};AWS.util.defer(sendRequest);},/** * @api private */uuid:{v4:function uuidV4(){return require('uuid').v4();}},/** * @api private */convertPayloadToString:function convertPayloadToString(resp){var req=resp.request;var operation=req.operation;var rules=req.service.api.operations[operation].output||{};if(rules.payload&&resp.data[rules.payload]){resp.data[rules.payload]=resp.data[rules.payload].toString();}},/** * @api private */defer:function defer(callback){if(_typeof(process)==='object'&&typeof process.nextTick==='function'){process.nextTick(callback);}else if(typeof setImmediate==='function'){setImmediate(callback);}else{setTimeout(callback,0);}},/** * @api private */getRequestPayloadShape:function getRequestPayloadShape(req){var operations=req.service.api.operations;if(!operations)return undefined;var operation=(operations||{})[req.operation];if(!operation||!operation.input||!operation.input.payload)return undefined;return operation.input.members[operation.input.payload];},getProfilesFromSharedConfig:function getProfilesFromSharedConfig(iniLoader,filename){var profiles={};var profilesFromConfig={};if(process.env[util.configOptInEnv]){var profilesFromConfig=iniLoader.loadFrom({isConfig:true,filename:process.env[util.sharedConfigFileEnv]});}var profilesFromCreds={};try{var profilesFromCreds=iniLoader.loadFrom({filename:filename||process.env[util.configOptInEnv]&&process.env[util.sharedCredentialsFileEnv]});}catch(error){// if using config, assume it is fully descriptive without a credentials file: if(!process.env[util.configOptInEnv])throw error;}for(var i=0,profileNames=Object.keys(profilesFromConfig);i=6;},parse:function parseARN(arn){var matched=arn.split(':');return{partition:matched[1],service:matched[2],region:matched[3],accountId:matched[4],resource:matched.slice(5).join(':')};},build:function buildARN(arnObject){if(arnObject.service===undefined||arnObject.region===undefined||arnObject.accountId===undefined||arnObject.resource===undefined)throw util.error(new Error('Input ARN object is invalid'));return'arn:'+(arnObject.partition||'aws')+':'+arnObject.service+':'+arnObject.region+':'+arnObject.accountId+':'+arnObject.resource;}},/** * @api private */defaultProfile:'default',/** * @api private */configOptInEnv:'AWS_SDK_LOAD_CONFIG',/** * @api private */sharedCredentialsFileEnv:'AWS_SHARED_CREDENTIALS_FILE',/** * @api private */sharedConfigFileEnv:'AWS_CONFIG_FILE',/** * @api private */imdsDisabledEnv:'AWS_EC2_METADATA_DISABLED'};/** * @api private */module.exports=util;}).call(this);}).call(this,require('_process'),require("timers").setImmediate);},{"../apis/metadata.json":4,"./core":19,"_process":91,"fs":82,"timers":99,"uuid":102}],75:[function(require,module,exports){var util=require('../util');var Shape=require('../model/shape');function DomXmlParser(){}DomXmlParser.prototype.parse=function(xml,shape){if(xml.replace(/^\s+/,'')==='')return{};var result,error;try{if(window.DOMParser){try{var parser=new DOMParser();result=parser.parseFromString(xml,'text/xml');}catch(syntaxError){throw util.error(new Error('Parse error in document'),{originalError:syntaxError,code:'XMLParserError',retryable:true});}if(result.documentElement===null){throw util.error(new Error('Cannot parse empty document.'),{code:'XMLParserError',retryable:true});}var isError=result.getElementsByTagName('parsererror')[0];if(isError&&(isError.parentNode===result||isError.parentNode.nodeName==='body'||isError.parentNode.parentNode===result||isError.parentNode.parentNode.nodeName==='body')){var errorElement=isError.getElementsByTagName('div')[0]||isError;throw util.error(new Error(errorElement.textContent||'Parser error in document'),{code:'XMLParserError',retryable:true});}}else if(window.ActiveXObject){result=new window.ActiveXObject('Microsoft.XMLDOM');result.async=false;if(!result.loadXML(xml)){throw util.error(new Error('Parse error in document'),{code:'XMLParserError',retryable:true});}}else{throw new Error('Cannot load XML parser');}}catch(e){error=e;}if(result&&result.documentElement&&!error){var data=parseXml(result.documentElement,shape);var metadata=getElementByTagName(result.documentElement,'ResponseMetadata');if(metadata){data.ResponseMetadata=parseXml(metadata,{});}return data;}else if(error){throw util.error(error||new Error(),{code:'XMLParserError',retryable:true});}else{// empty xml document return{};}};function getElementByTagName(xml,tag){var elements=xml.getElementsByTagName(tag);for(var i=0,iLen=elements.length;i0||noEmpty?xml.toString():'';};function serialize(xml,value,shape){switch(shape.type){case'structure':return serializeStructure(xml,value,shape);case'map':return serializeMap(xml,value,shape);case'list':return serializeList(xml,value,shape);default:return serializeScalar(xml,value,shape);}}function serializeStructure(xml,params,shape){util.arrayEach(shape.memberNames,function(memberName){var memberShape=shape.members[memberName];if(memberShape.location!=='body')return;var value=params[memberName];var name=memberShape.name;if(value!==undefined&&value!==null){if(memberShape.isXmlAttribute){xml.addAttribute(name,value);}else if(memberShape.flattened){serialize(xml,value,memberShape);}else{var element=new XmlNode(name);xml.addChildNode(element);applyNamespaces(element,memberShape);serialize(element,value,memberShape);}}});}function serializeMap(xml,map,shape){var xmlKey=shape.key.name||'key';var xmlValue=shape.value.name||'value';util.each(map,function(key,value){var entry=new XmlNode(shape.flattened?shape.name:'entry');xml.addChildNode(entry);var entryKey=new XmlNode(xmlKey);var entryValue=new XmlNode(xmlValue);entry.addChildNode(entryKey);entry.addChildNode(entryValue);serialize(entryKey,key,shape.key);serialize(entryValue,value,shape.value);});}function serializeList(xml,list,shape){if(shape.flattened){util.arrayEach(list,function(value){var name=shape.member.name||shape.name;var element=new XmlNode(name);xml.addChildNode(element);serialize(element,value,shape.member);});}else{util.arrayEach(list,function(value){var name=shape.member.name||'member';var element=new XmlNode(name);xml.addChildNode(element);serialize(element,value,shape.member);});}}function serializeScalar(xml,value,shape){xml.addChildNode(new XmlText(shape.toWireFormat(value)));}function applyNamespaces(xml,shape,isRoot){var uri,prefix='xmlns';if(shape.xmlNamespaceUri){uri=shape.xmlNamespaceUri;if(shape.xmlNamespacePrefix)prefix+=':'+shape.xmlNamespacePrefix;}else if(isRoot&&shape.api.xmlNamespaceUri){uri=shape.api.xmlNamespaceUri;}if(uri)xml.addAttribute(prefix,uri);}/** * @api private */module.exports=XmlBuilder;},{"../util":74,"./xml-node":79,"./xml-text":80}],77:[function(require,module,exports){/** * Escapes characters that can not be in an XML attribute. */function escapeAttribute(value){return value.replace(/&/g,'&').replace(/'/g,''').replace(//g,'>').replace(/"/g,'"');}/** * @api private */module.exports={escapeAttribute:escapeAttribute};},{}],78:[function(require,module,exports){/** * Escapes characters that can not be in an XML element. */function escapeElement(value){return value.replace(/&/g,'&').replace(//g,'>').replace(/\r/g,' ').replace(/\n/g,' ').replace(/\u0085/g,'…').replace(/\u2028/,'
');}/** * @api private */module.exports={escapeElement:escapeElement};},{}],79:[function(require,module,exports){var escapeAttribute=require('./escape-attribute').escapeAttribute;/** * Represents an XML node. * @api private */function XmlNode(name,children){if(children===void 0){children=[];}this.name=name;this.children=children;this.attributes={};}XmlNode.prototype.addAttribute=function(name,value){this.attributes[name]=value;return this;};XmlNode.prototype.addChildNode=function(child){this.children.push(child);return this;};XmlNode.prototype.removeAttribute=function(name){delete this.attributes[name];return this;};XmlNode.prototype.toString=function(){var hasChildren=Boolean(this.children.length);var xmlText='<'+this.name;// add attributes var attributes=this.attributes;for(var i=0,attributeNames=Object.keys(attributes);i':'>'+this.children.map(function(c){return c.toString();}).join('')+'';};/** * @api private */module.exports={XmlNode:XmlNode};},{"./escape-attribute":77}],80:[function(require,module,exports){var escapeElement=require('./escape-element').escapeElement;/** * Represents an XML text value. * @api private */function XmlText(value){this.value=value;}XmlText.prototype.toString=function(){return escapeElement(''+this.value);};/** * @api private */module.exports={XmlText:XmlText};},{"./escape-element":78}],81:[function(require,module,exports){'use strict';exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=='undefined'?Uint8Array:Array;var code='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';for(var i=0,len=code.length;i0){throw new Error('Invalid string. Length must be a multiple of 4');}// Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen=b64.indexOf('=');if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen];}// base64 is 4/3 + up to two characters of the original data function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen;}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen;}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;// if there are placeholders, only get up to the last complete 4 chars var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i>16&0xFF;arr[curByte++]=tmp>>8&0xFF;arr[curByte++]=tmp&0xFF;}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&0xFF;}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&0xFF;arr[curByte++]=tmp&0xFF;}return arr;}function tripletToBase64(num){return lookup[num>>18&0x3F]+lookup[num>>12&0x3F]+lookup[num>>6&0x3F]+lookup[num&0x3F];}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength));}// pad the end with zeros, but make sure to not forget the extra bytes if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&0x3F]+'==');}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&0x3F]+lookup[tmp<<2&0x3F]+'=');}return parts.join('');}},{}],82:[function(require,module,exports){},{}],83:[function(require,module,exports){if(typeof Object.create==='function'){// implementation from standard node.js 'util' module module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}});};}else{// old school shim for old browsers module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function TempCtor(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor();ctor.prototype.constructor=ctor;};}},{}],84:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&_typeof(arg)==='object'&&typeof arg.copy==='function'&&typeof arg.fill==='function'&&typeof arg.readUInt8==='function';};},{}],85:[function(require,module,exports){(function(process,global){(function(){// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x;switch(x){case'%s':return String(args[i++]);case'%d':return Number(args[i++]);case'%j':try{return JSON.stringify(args[i++]);}catch(_){return'[Circular]';}default:return x;}});for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){// legacy... ctx.showHidden=opts;}else if(opts){// got an "options" object exports._extend(ctx,opts);}// set default options if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth);}exports.inspect=inspect;// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors={'bold':[1,22],'italic':[3,23],'underline':[4,24],'inverse':[7,27],'white':[37,39],'grey':[90,39],'black':[30,39],'blue':[34,39],'cyan':[36,39],'green':[32,39],'magenta':[35,39],'red':[31,39],'yellow':[33,39]};// Don't use 'blue' not visible on cmd.exe inspect.styles={'special':'cyan','number':'yellow','boolean':'yellow','undefined':'grey','null':'bold','string':'green','date':'magenta',// "name": intentionally not styling 'regexp':'red'};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"\x1B["+inspect.colors[style][0]+'m'+str+"\x1B["+inspect.colors[style][1]+'m';}else{return str;}}function stylizeNoColor(str,styleType){return str;}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true;});return hash;}function formatValue(ctx,value,recurseTimes){// Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if(ctx.customInspect&&value&&isFunction(value.inspect)&&// Filter out the util module, it's inspect function is special value.inspect!==exports.inspect&&// Also filter out any prototype objects using the circular check. !(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes);}return ret;}// Primitive types cannot have properties var primitive=formatPrimitive(ctx,value);if(primitive){return primitive;}// Look up the keys of the object. var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value);}// IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if(isError(value)&&(keys.indexOf('message')>=0||keys.indexOf('description')>=0)){return formatError(value);}// Some type of object without properties can be shortcutted. if(keys.length===0){if(isFunction(value)){var name=value.name?': '+value.name:'';return ctx.stylize('[Function'+name+']','special');}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),'regexp');}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),'date');}if(isError(value)){return formatError(value);}}var base='',array=false,braces=['{','}'];// Make Array say that they are Array if(isArray(value)){array=true;braces=['[',']'];}// Make functions say that they are functions if(isFunction(value)){var n=value.name?': '+value.name:'';base=' [Function'+n+']';}// Make RegExps say that they are RegExps if(isRegExp(value)){base=' '+RegExp.prototype.toString.call(value);}// Make dates with properties first say the date if(isDate(value)){base=' '+Date.prototype.toUTCString.call(value);}// Make error with message first say the error if(isError(value)){base=' '+formatError(value);}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1];}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),'regexp');}else{return ctx.stylize('[Object]','special');}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys);}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array);});}ctx.seen.pop();return reduceToSingleString(output,base,braces);}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize('undefined','undefined');if(isString(value)){var simple='\''+JSON.stringify(value).replace(/^"|"$/g,'').replace(/'/g,"\\'").replace(/\\"/g,'"')+'\'';return ctx.stylize(simple,'string');}if(isNumber(value))return ctx.stylize(''+value,'number');if(isBoolean(value))return ctx.stylize(''+value,'boolean');// For some reason typeof null is "object", so special case here. if(isNull(value))return ctx.stylize('null','null');}function formatError(value){return'['+Error.prototype.toString.call(value)+']';}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split('\n').map(function(line){return' '+line;}).join('\n').substr(2);}else{str='\n'+str.split('\n').map(function(line){return' '+line;}).join('\n');}}}else{str=ctx.stylize('[Circular]','special');}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str;}name=JSON.stringify(''+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,'name');}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,'string');}}return name+': '+str;}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf('\n')>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,'').length+1;},0);if(length>60){return braces[0]+(base===''?'':base+'\n ')+' '+output.join(',\n ')+' '+braces[1];}return braces[0]+base+' '+output.join(', ')+' '+braces[1];}// NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar){return Array.isArray(ar);}exports.isArray=isArray;function isBoolean(arg){return typeof arg==='boolean';}exports.isBoolean=isBoolean;function isNull(arg){return arg===null;}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null;}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==='number';}exports.isNumber=isNumber;function isString(arg){return typeof arg==='string';}exports.isString=isString;function isSymbol(arg){return _typeof(arg)==='symbol';}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0;}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==='[object RegExp]';}exports.isRegExp=isRegExp;function isObject(arg){return _typeof(arg)==='object'&&arg!==null;}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==='[object Date]';}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==='[object Error]'||e instanceof Error);}exports.isError=isError;function isFunction(arg){return typeof arg==='function';}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==='boolean'||typeof arg==='number'||typeof arg==='string'||_typeof(arg)==='symbol'||// ES6 symbol typeof arg==='undefined';}exports.isPrimitive=isPrimitive;exports.isBuffer=require('./support/isBuffer');function objectToString(o){return Object.prototype.toString.call(o);}function pad(n){return n<10?'0'+n.toString(10):n.toString(10);}var months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];// 26 Feb 16:19:34 function timestamp(){var d=new Date();var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(':');return[d.getDate(),months[d.getMonth()],time].join(' ');}// log is just a thin wrapper to console.log that prepends a timestamp exports.log=function(){console.log('%s - %s',timestamp(),exports.format.apply(exports,arguments));};/** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */exports.inherits=require('inherits');exports._extend=function(origin,add){// Don't do anything if add isn't an object if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]];}return origin;};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop);}}).call(this);}).call(this,require('_process'),typeof __webpack_require__.g!=="undefined"?__webpack_require__.g:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"./support/isBuffer":84,"_process":91,"inherits":83}],86:[function(require,module,exports){(function(global,Buffer){(function(){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT *//* eslint-disable no-proto */'use strict';var base64=require('base64-js');var ieee754=require('ieee754');var isArray=require('isarray');exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;/** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();/* * Export kMaxLength after typed array support is determined. */exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function foo(){return 42;}};return arr.foo()===42&&// typed array instances can be augmented typeof arr.subarray==='function'&&// chrome 9-10 lack `subarray` arr.subarray(1,1).byteLength===0;// ie10 has broken `subarray` }catch(e){return false;}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?0x7fffffff:0x3fffffff;}function createBuffer(that,length){if(kMaxLength()=kMaxLength()){throw new RangeError('Attempt to allocate Buffer larger than maximum '+'size: 0x'+kMaxLength().toString(16)+' bytes');}return length|0;}function SlowBuffer(length){if(+length!=length){// eslint-disable-line eqeqeq length=0;}return Buffer.alloc(+length);}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer);};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('Arguments must be Buffers');}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case'base64':return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;// assume utf8 encoding=(''+encoding).toLowerCase();loweredCase=true;}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;// No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if(start===undefined||start<0){start=0;}// Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if(start>this.length){return'';}if(end===undefined||end>this.length){end=this.length;}if(end<=0){return'';}// Force coersion to uint32. This will also coerce falsey/NaN values to 0. end>>>=0;start>>>=0;if(end<=start){return'';}if(!encoding)encoding='utf8';while(true){switch(encoding){case'hex':return hexSlice(this,start,end);case'utf8':case'utf-8':return utf8Slice(this,start,end);case'ascii':return asciiSlice(this,start,end);case'latin1':case'binary':return latin1Slice(this,start,end);case'base64':return base64Slice(this,start,end);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding);encoding=(encoding+'').toLowerCase();loweredCase=true;}}}// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i;}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError('Buffer size must be a multiple of 16-bits');}for(var i=0;i0){str=this.toString('hex',0,max).match(/.{2}/g).join(' ');if(this.length>max)str+=' ... ';}return'';};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError('Argument must be a Buffer');}if(start===undefined){start=0;}if(end===undefined){end=target?target.length:0;}if(thisStart===undefined){thisStart=0;}if(thisEnd===undefined){thisEnd=this.length;}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError('out of range index');}if(thisStart>=thisEnd&&start>=end){return 0;}if(thisStart>=thisEnd){return-1;}if(start>=end){return 1;}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){// Empty buffer means no match if(buffer.length===0)return-1;// Normalize byteOffset if(typeof byteOffset==='string'){encoding=byteOffset;byteOffset=0;}else if(byteOffset>0x7fffffff){byteOffset=0x7fffffff;}else if(byteOffset<-0x80000000){byteOffset=-0x80000000;}byteOffset=+byteOffset;// Coerce to Number. if(isNaN(byteOffset)){// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset=dir?0:buffer.length-1;}// Normalize byteOffset: negative offsets start from the end of the buffer if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1;}else if(byteOffset<0){if(dir)byteOffset=0;else return-1;}// Normalize val if(typeof val==='string'){val=Buffer.from(val,encoding);}// Finally, search either indexOf (if dir is true) or lastIndexOf if(Buffer.isBuffer(val)){// Special case: looking for empty string/buffer always fails if(val.length===0){return-1;}return arrayIndexOf(buffer,val,byteOffset,encoding,dir);}else if(typeof val==='number'){val=val&0xFF;// Search for a byte value [0-255] if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==='function'){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset);}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset);}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir);}throw new TypeError('val must be string, number or Buffer');}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==='ucs2'||encoding==='ucs-2'||encoding==='utf16le'||encoding==='utf-16le'){if(arr.length<2||val.length<2){return-1;}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2;}}function read(buf,i){if(indexSize===1){return buf[i];}else{return buf.readUInt16BE(i*indexSize);}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining;}}// must be an even number of digits var strLen=string.length;if(strLen%2!==0)throw new TypeError('Invalid hex string');if(length>strLen/2){length=strLen/2;}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError('Attempt to write outside buffer bounds');}if(!encoding)encoding='utf8';var loweredCase=false;for(;;){switch(encoding){case'hex':return hexWrite(this,string,offset,length);case'utf8':case'utf-8':return utf8Write(this,string,offset,length);case'ascii':return asciiWrite(this,string,offset,length);case'latin1':case'binary':return latin1Write(this,string,offset,length);case'base64':// Warning: maxLength not taken into account in base64Write return base64Write(this,string,offset,length);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding);encoding=(''+encoding).toLowerCase();loweredCase=true;}}};Buffer.prototype.toJSON=function toJSON(){return{type:'Buffer',data:Array.prototype.slice.call(this._arr||this,0)};};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf);}else{return base64.fromByteArray(buf.slice(start,end));}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i0xEF?4:firstByte>0xDF?3:firstByte>0xBF?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<0x80){codePoint=firstByte;}break;case 2:secondByte=buf[i+1];if((secondByte&0xC0)===0x80){tempCodePoint=(firstByte&0x1F)<<0x6|secondByte&0x3F;if(tempCodePoint>0x7F){codePoint=tempCodePoint;}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0xC|(secondByte&0x3F)<<0x6|thirdByte&0x3F;if(tempCodePoint>0x7FF&&(tempCodePoint<0xD800||tempCodePoint>0xDFFF)){codePoint=tempCodePoint;}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80&&(fourthByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0x12|(secondByte&0x3F)<<0xC|(thirdByte&0x3F)<<0x6|fourthByte&0x3F;if(tempCodePoint>0xFFFF&&tempCodePoint<0x110000){codePoint=tempCodePoint;}}}}if(codePoint===null){// we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint=0xFFFD;bytesPerSequence=1;}else if(codePoint>0xFFFF){// encode to utf16 (surrogate pair dance) codePoint-=0x10000;res.push(codePoint>>>10&0x3FF|0xD800);codePoint=0xDC00|codePoint&0x3FF;}res.push(codePoint);i+=bytesPerSequence;}return decodeCodePointsArray(res);}// Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH=0x1000;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints);// avoid extra slice() }// Decode in chunks to avoid "call stack size exceeded". var res='';var i=0;while(ilen)end=len;var out='';for(var i=start;ilen){start=len;}if(end<0){end+=len;if(end<0)end=0;}else if(end>len){end=len;}if(endlength)throw new RangeError('Trying to access beyond buffer length');}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=0x100)){val+=this[offset+--byteLength]*mul;}return val;};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset];};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8;};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1];};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*0x1000000;};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*0x1000000+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3]);};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val;};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=0x100)){val+=this[offset+--i]*mul;}mul*=0x80;if(val>=mul)val-=Math.pow(2,8*byteLength);return val;};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&0x80))return this[offset];return(0xff-this[offset]+1)*-1;};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&0x8000?val|0xFFFF0000:val;};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&0x8000?val|0xFFFF0000:val;};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24;};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3];};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4);};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4);};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8);};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8);};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError('Index out of range');}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0);}var mul=1;var i=0;this[offset]=value&0xFF;while(++i=0&&(mul*=0x100)){this[offset+i]=value/mul&0xFF;}return offset+byteLength;};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,0xff,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&0xff;return offset+1;};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=0xffff+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8;}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0xffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;}else{objectWriteUInt16(this,value,offset,true);}return offset+2;};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0xffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&0xff;}else{objectWriteUInt16(this,value,offset,false);}return offset+2;};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=0xffffffff+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&0xff;}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&0xff;}else{objectWriteUInt32(this,value,offset,true);}return offset+4;};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&0xff;}else{objectWriteUInt32(this,value,offset,false);}return offset+4;};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit);}var i=0;var mul=1;var sub=0;this[offset]=value&0xFF;while(++i>0)-sub&0xFF;}return offset+byteLength;};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit);}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&0xFF;while(--i>=0&&(mul*=0x100)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1;}this[offset+i]=(value/mul>>0)-sub&0xFF;}return offset+byteLength;};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,0x7f,-0x80);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=0xff+value+1;this[offset]=value&0xff;return offset+1;};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;}else{objectWriteUInt16(this,value,offset,true);}return offset+2;};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&0xff;}else{objectWriteUInt16(this,value,offset,false);}return offset+2;};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;}else{objectWriteUInt32(this,value,offset,true);}return offset+4;};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000);if(value<0)value=0xffffffff+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&0xff;}else{objectWriteUInt32(this,value,offset,false);}return offset+4;};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError('Index out of range');if(offset<0)throw new RangeError('Index out of range');}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e+38,-3.4028234663852886e+38);}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4;}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert);};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert);};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157E+308,-1.7976931348623157E+308);}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8;}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert);};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert);};// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError('sourceStart out of bounds');if(end<0)throw new RangeError('sourceEnd out of bounds');// Are we oob? if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start];}}else if(len<1000||!Buffer.TYPED_ARRAY_SUPPORT){// ascending copy from start for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==='number'){for(i=start;i0xD7FF&&codePoint<0xE000){// last char was a lead if(!leadSurrogate){// no lead yet if(codePoint>0xDBFF){// unexpected trail if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);continue;}else if(i+1===length){// unpaired lead if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);continue;}// valid lead leadSurrogate=codePoint;continue;}// 2 leads in a row if(codePoint<0xDC00){if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);leadSurrogate=codePoint;continue;}// valid surrogate pair codePoint=(leadSurrogate-0xD800<<10|codePoint-0xDC00)+0x10000;}else if(leadSurrogate){// valid bmp char, but last char was a lead if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);}leadSurrogate=null;// encode utf8 if(codePoint<0x80){if((units-=1)<0)break;bytes.push(codePoint);}else if(codePoint<0x800){if((units-=2)<0)break;bytes.push(codePoint>>0x6|0xC0,codePoint&0x3F|0x80);}else if(codePoint<0x10000){if((units-=3)<0)break;bytes.push(codePoint>>0xC|0xE0,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80);}else if(codePoint<0x110000){if((units-=4)<0)break;bytes.push(codePoint>>0x12|0xF0,codePoint>>0xC&0x3F|0x80,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80);}else{throw new Error('Invalid code point');}}return bytes;}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi);}return byteArray;}function base64ToBytes(str){return base64.toByteArray(base64clean(str));}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i];}return i;}function isnan(val){return val!==val;// eslint-disable-line no-self-compare }}).call(this);}).call(this,typeof __webpack_require__.g!=="undefined"?__webpack_require__.g:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer);},{"base64-js":81,"buffer":86,"ieee754":88,"isarray":89}],87:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined;}module.exports=EventEmitter;// Backwards-compat with node 0.10.x EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;// By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners=10;// Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError('n must be a positive number');this._maxListeners=n;return this;};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};// If there is no 'error' event listener then throw. if(type==='error'){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er;// Unhandled 'error' event }else{// At least give some kind of context to the user var err=new Error('Uncaught, unspecified "error" event. ('+er+')');err.context=er;throw err;}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){// fast cases case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;// slower default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args);}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i0&&this._events[type].length>m){this._events[type].warned=true;console.error('(node) warning: possible EventEmitter memory '+'leak detected. %d listeners added. '+'Use emitter.setMaxListeners() to increase limit.',this._events[type].length);if(typeof console.trace==='function'){// not supported in IE 10 console.trace();}}}return this;};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError('listener must be a function');var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments);}}g.listener=listener;this.on(type,g);return this;};// emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError('listener must be a function');if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit('removeListener',type,listener);}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break;}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type];}else{list.splice(position,1);}if(this._events.removeListener)this.emit('removeListener',type,listener);}return this;};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;// not listening for removeListener, no need to emit if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this;}// emit removeListener for all listeners on all events if(arguments.length===0){for(key in this._events){if(key==='removeListener')continue;this.removeAllListeners(key);}this.removeAllListeners('removeListener');this._events={};return this;}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners);}else if(listeners){// LIFO order while(listeners.length)this.removeListener(type,listeners[listeners.length-1]);}delete this._events[type];return this;};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret;};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length;}return 0;};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type);};function isFunction(arg){return typeof arg==='function';}function isNumber(arg){return typeof arg==='number';}function isObject(arg){return _typeof(arg)==='object'&&arg!==null;}function isUndefined(arg){return arg===void 0;}},{}],88:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias;}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity;}else{m=m+Math.pow(2,mLen);e=e-eBias;}return(s?-1:1)*m*Math.pow(2,e-mLen);};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax;}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2;}if(e+eBias>=1){value+=rt/c;}else{value+=rt*Math.pow(2,1-eBias);}if(value*c>=2){e++;c/=2;}if(e+eBias>=eMax){m=0;e=eMax;}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias;}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0;}}for(;mLen>=8;buffer[offset+i]=m&0xff,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&0xff,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128;};},{}],89:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=='[object Array]';};},{}],90:[function(require,module,exports){(function(exports){"use strict";function isArray(obj){if(obj!==null){return Object.prototype.toString.call(obj)==="[object Array]";}else{return false;}}function isObject(obj){if(obj!==null){return Object.prototype.toString.call(obj)==="[object Object]";}else{return false;}}function strictDeepEqual(first,second){// Check the scalar case first. if(first===second){return true;}// Check if they are the same type. var firstType=Object.prototype.toString.call(first);if(firstType!==Object.prototype.toString.call(second)){return false;}// We know that first and second have the same type so we can just check the // first type from now on. if(isArray(first)===true){// Short circuit if they're not the same length; if(first.length!==second.length){return false;}for(var i=0;i',9:'Array'};var TOK_EOF="EOF";var TOK_UNQUOTEDIDENTIFIER="UnquotedIdentifier";var TOK_QUOTEDIDENTIFIER="QuotedIdentifier";var TOK_RBRACKET="Rbracket";var TOK_RPAREN="Rparen";var TOK_COMMA="Comma";var TOK_COLON="Colon";var TOK_RBRACE="Rbrace";var TOK_NUMBER="Number";var TOK_CURRENT="Current";var TOK_EXPREF="Expref";var TOK_PIPE="Pipe";var TOK_OR="Or";var TOK_AND="And";var TOK_EQ="EQ";var TOK_GT="GT";var TOK_LT="LT";var TOK_GTE="GTE";var TOK_LTE="LTE";var TOK_NE="NE";var TOK_FLATTEN="Flatten";var TOK_STAR="Star";var TOK_FILTER="Filter";var TOK_DOT="Dot";var TOK_NOT="Not";var TOK_LBRACE="Lbrace";var TOK_LBRACKET="Lbracket";var TOK_LPAREN="Lparen";var TOK_LITERAL="Literal";// The "&", "[", "<", ">" tokens // are not in basicToken because // there are two token variants // ("&&", "[?", "<=", ">="). This is specially handled // below. var basicTokens={".":TOK_DOT,"*":TOK_STAR,",":TOK_COMMA,":":TOK_COLON,"{":TOK_LBRACE,"}":TOK_RBRACE,"]":TOK_RBRACKET,"(":TOK_LPAREN,")":TOK_RPAREN,"@":TOK_CURRENT};var operatorStartToken={"<":true,">":true,"=":true,"!":true};var skipChars={" ":true,"\t":true,"\n":true};function isAlpha(ch){return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch==="_";}function isNum(ch){return ch>="0"&&ch<="9"||ch==="-";}function isAlphaNum(ch){return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch>="0"&&ch<="9"||ch==="_";}function Lexer(){}Lexer.prototype={tokenize:function tokenize(stream){var tokens=[];this._current=0;var start;var identifier;var token;while(this._current"){if(stream[this._current]==="="){this._current++;return{type:TOK_GTE,value:">=",start:start};}else{return{type:TOK_GT,value:">",start:start};}}else if(startingChar==="="){if(stream[this._current]==="="){this._current++;return{type:TOK_EQ,value:"==",start:start};}}},_consumeLiteral:function _consumeLiteral(stream){this._current++;var start=this._current;var maxLength=stream.length;var literal;while(stream[this._current]!=="`"&&this._current" literal=JSON.parse("\""+literalString+"\"");}// +1 gets us to the ending "`", +1 to move on to the next char. this._current++;return literal;},_looksLikeJSON:function _looksLikeJSON(literalString){var startingChars="[{\"";var jsonLiterals=["true","false","null"];var numberLooking="-0123456789";if(literalString===""){return false;}else if(startingChars.indexOf(literalString[0])>=0){return true;}else if(jsonLiterals.indexOf(literalString)>=0){return true;}else if(numberLooking.indexOf(literalString[0])>=0){try{JSON.parse(literalString);return true;}catch(ex){return false;}}else{return false;}}};var bindingPower={};bindingPower[TOK_EOF]=0;bindingPower[TOK_UNQUOTEDIDENTIFIER]=0;bindingPower[TOK_QUOTEDIDENTIFIER]=0;bindingPower[TOK_RBRACKET]=0;bindingPower[TOK_RPAREN]=0;bindingPower[TOK_COMMA]=0;bindingPower[TOK_RBRACE]=0;bindingPower[TOK_NUMBER]=0;bindingPower[TOK_CURRENT]=0;bindingPower[TOK_EXPREF]=0;bindingPower[TOK_PIPE]=1;bindingPower[TOK_OR]=2;bindingPower[TOK_AND]=3;bindingPower[TOK_EQ]=5;bindingPower[TOK_GT]=5;bindingPower[TOK_LT]=5;bindingPower[TOK_GTE]=5;bindingPower[TOK_LTE]=5;bindingPower[TOK_NE]=5;bindingPower[TOK_FLATTEN]=9;bindingPower[TOK_STAR]=20;bindingPower[TOK_FILTER]=21;bindingPower[TOK_DOT]=40;bindingPower[TOK_NOT]=45;bindingPower[TOK_LBRACE]=50;bindingPower[TOK_LBRACKET]=55;bindingPower[TOK_LPAREN]=60;function Parser(){}Parser.prototype={parse:function parse(expression){this._loadTokens(expression);this.index=0;var ast=this.expression(0);if(this._lookahead(0)!==TOK_EOF){var t=this._lookaheadToken(0);var error=new Error("Unexpected token type: "+t.type+", value: "+t.value);error.name="ParserError";throw error;}return ast;},_loadTokens:function _loadTokens(expression){var lexer=new Lexer();var tokens=lexer.tokenize(expression);tokens.push({type:TOK_EOF,value:"",start:expression.length});this.tokens=tokens;},expression:function expression(rbp){var leftToken=this._lookaheadToken(0);this._advance();var left=this.nud(leftToken);var currentToken=this._lookahead(0);while(rbp=0){return this.expression(rbp);}else if(lookahead===TOK_LBRACKET){this._match(TOK_LBRACKET);return this._parseMultiselectList();}else if(lookahead===TOK_LBRACE){this._match(TOK_LBRACE);return this._parseMultiselectHash();}},_parseProjectionRHS:function _parseProjectionRHS(rbp){var right;if(bindingPower[this._lookahead(0)]<10){right={type:"Identity"};}else if(this._lookahead(0)===TOK_LBRACKET){right=this.expression(rbp);}else if(this._lookahead(0)===TOK_FILTER){right=this.expression(rbp);}else if(this._lookahead(0)===TOK_DOT){this._match(TOK_DOT);right=this._parseDotRHS(rbp);}else{var t=this._lookaheadToken(0);var error=new Error("Sytanx error, unexpected token: "+t.value+"("+t.type+")");error.name="ParserError";throw error;}return right;},_parseMultiselectList:function _parseMultiselectList(){var expressions=[];while(this._lookahead(0)!==TOK_RBRACKET){var expression=this.expression(0);expressions.push(expression);if(this._lookahead(0)===TOK_COMMA){this._match(TOK_COMMA);if(this._lookahead(0)===TOK_RBRACKET){throw new Error("Unexpected token Rbracket");}}}this._match(TOK_RBRACKET);return{type:"MultiSelectList",children:expressions};},_parseMultiselectHash:function _parseMultiselectHash(){var pairs=[];var identifierTypes=[TOK_UNQUOTEDIDENTIFIER,TOK_QUOTEDIDENTIFIER];var keyToken,keyName,value,node;for(;;){keyToken=this._lookaheadToken(0);if(identifierTypes.indexOf(keyToken.type)<0){throw new Error("Expecting an identifier token, got: "+keyToken.type);}keyName=keyToken.value;this._advance();this._match(TOK_COLON);value=this.expression(0);node={type:"KeyValuePair",name:keyName,value:value};pairs.push(node);if(this._lookahead(0)===TOK_COMMA){this._match(TOK_COMMA);}else if(this._lookahead(0)===TOK_RBRACE){this._match(TOK_RBRACE);break;}}return{type:"MultiSelectHash",children:pairs};}};function TreeInterpreter(runtime){this.runtime=runtime;}TreeInterpreter.prototype={search:function search(node,value){return this.visit(node,value);},visit:function visit(node,value){var matched,current,result,first,second,field,left,right,collected,i;switch(node.type){case"Field":if(value!==null&&isObject(value)){field=value[node.name];if(field===undefined){return null;}else{return field;}}return null;case"Subexpression":result=this.visit(node.children[0],value);for(i=1;i0){for(i=start;istop;i+=step){result.push(value[i]);}}return result;case"Projection":// Evaluate left child. var base=this.visit(node.children[0],value);if(!isArray(base)){return null;}collected=[];for(i=0;isecond;break;case TOK_GTE:result=first>=second;break;case TOK_LT:result=first=arrayLength){actualValue=step<0?arrayLength-1:arrayLength;}return actualValue;}};function Runtime(interpreter){this._interpreter=interpreter;this.functionTable={// name: [function, ] // The can be: // // { // args: [[type1, type2], [type1, type2]], // variadic: true|false // } // // Each arg in the arg list is a list of valid types // (if the function is overloaded and supports multiple // types. If the type is "any" then no type checking // occurs on the argument. Variadic is optional // and if not provided is assumed to be false. abs:{_func:this._functionAbs,_signature:[{types:[TYPE_NUMBER]}]},avg:{_func:this._functionAvg,_signature:[{types:[TYPE_ARRAY_NUMBER]}]},ceil:{_func:this._functionCeil,_signature:[{types:[TYPE_NUMBER]}]},contains:{_func:this._functionContains,_signature:[{types:[TYPE_STRING,TYPE_ARRAY]},{types:[TYPE_ANY]}]},"ends_with":{_func:this._functionEndsWith,_signature:[{types:[TYPE_STRING]},{types:[TYPE_STRING]}]},floor:{_func:this._functionFloor,_signature:[{types:[TYPE_NUMBER]}]},length:{_func:this._functionLength,_signature:[{types:[TYPE_STRING,TYPE_ARRAY,TYPE_OBJECT]}]},map:{_func:this._functionMap,_signature:[{types:[TYPE_EXPREF]},{types:[TYPE_ARRAY]}]},max:{_func:this._functionMax,_signature:[{types:[TYPE_ARRAY_NUMBER,TYPE_ARRAY_STRING]}]},"merge":{_func:this._functionMerge,_signature:[{types:[TYPE_OBJECT],variadic:true}]},"max_by":{_func:this._functionMaxBy,_signature:[{types:[TYPE_ARRAY]},{types:[TYPE_EXPREF]}]},sum:{_func:this._functionSum,_signature:[{types:[TYPE_ARRAY_NUMBER]}]},"starts_with":{_func:this._functionStartsWith,_signature:[{types:[TYPE_STRING]},{types:[TYPE_STRING]}]},min:{_func:this._functionMin,_signature:[{types:[TYPE_ARRAY_NUMBER,TYPE_ARRAY_STRING]}]},"min_by":{_func:this._functionMinBy,_signature:[{types:[TYPE_ARRAY]},{types:[TYPE_EXPREF]}]},type:{_func:this._functionType,_signature:[{types:[TYPE_ANY]}]},keys:{_func:this._functionKeys,_signature:[{types:[TYPE_OBJECT]}]},values:{_func:this._functionValues,_signature:[{types:[TYPE_OBJECT]}]},sort:{_func:this._functionSort,_signature:[{types:[TYPE_ARRAY_STRING,TYPE_ARRAY_NUMBER]}]},"sort_by":{_func:this._functionSortBy,_signature:[{types:[TYPE_ARRAY]},{types:[TYPE_EXPREF]}]},join:{_func:this._functionJoin,_signature:[{types:[TYPE_STRING]},{types:[TYPE_ARRAY_STRING]}]},reverse:{_func:this._functionReverse,_signature:[{types:[TYPE_STRING,TYPE_ARRAY]}]},"to_array":{_func:this._functionToArray,_signature:[{types:[TYPE_ANY]}]},"to_string":{_func:this._functionToString,_signature:[{types:[TYPE_ANY]}]},"to_number":{_func:this._functionToNumber,_signature:[{types:[TYPE_ANY]}]},"not_null":{_func:this._functionNotNull,_signature:[{types:[TYPE_ANY],variadic:true}]}};}Runtime.prototype={callFunction:function callFunction(name,resolvedArgs){var functionEntry=this.functionTable[name];if(functionEntry===undefined){throw new Error("Unknown function: "+name+"()");}this._validateArgs(name,resolvedArgs,functionEntry._signature);return functionEntry._func.call(this,resolvedArgs);},_validateArgs:function _validateArgs(name,args,signature){// Validating the args requires validating // the correct arity and the correct type of each arg. // If the last argument is declared as variadic, then we need // a minimum number of args to be required. Otherwise it has to // be an exact amount. var pluralized;if(signature[signature.length-1].variadic){if(args.length=0;i--){reversedStr+=originalStr[i];}return reversedStr;}else{var reversedArray=resolvedArgs[0].slice(0);reversedArray.reverse();return reversedArray;}},_functionAbs:function _functionAbs(resolvedArgs){return Math.abs(resolvedArgs[0]);},_functionCeil:function _functionCeil(resolvedArgs){return Math.ceil(resolvedArgs[0]);},_functionAvg:function _functionAvg(resolvedArgs){var sum=0;var inputArray=resolvedArgs[0];for(var i=0;i=0;},_functionFloor:function _functionFloor(resolvedArgs){return Math.floor(resolvedArgs[0]);},_functionLength:function _functionLength(resolvedArgs){if(!isObject(resolvedArgs[0])){return resolvedArgs[0].length;}else{// As far as I can tell, there's no way to get the length // of an object without O(n) iteration through the object. return Object.keys(resolvedArgs[0]).length;}},_functionMap:function _functionMap(resolvedArgs){var mapped=[];var interpreter=this._interpreter;var exprefNode=resolvedArgs[0];var elements=resolvedArgs[1];for(var i=0;i0){var typeName=this._getTypeName(resolvedArgs[0][0]);if(typeName===TYPE_NUMBER){return Math.max.apply(Math,resolvedArgs[0]);}else{var elements=resolvedArgs[0];var maxElement=elements[0];for(var i=1;i0){var typeName=this._getTypeName(resolvedArgs[0][0]);if(typeName===TYPE_NUMBER){return Math.min.apply(Math,resolvedArgs[0]);}else{var elements=resolvedArgs[0];var minElement=elements[0];for(var i=1;iexprB){return 1;}else if(exprAmaxNumber){maxNumber=current;maxRecord=resolvedArray[i];}}return maxRecord;},_functionMinBy:function _functionMinBy(resolvedArgs){var exprefNode=resolvedArgs[1];var resolvedArray=resolvedArgs[0];var keyFunction=this.createKeyFunction(exprefNode,[TYPE_NUMBER,TYPE_STRING]);var minNumber=Infinity;var minRecord;var current;for(var i=0;i1){for(var i=1;i= 0x80 (not a basic code point)','invalid-input':'Invalid input'},/** Convenience shortcuts */baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,/** Temporary variable */key;/*--------------------------------------------------------------------------*//** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */function error(type){throw new RangeError(errors[type]);}/** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length]);}return result;}/** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */function mapDomain(string,fn){var parts=string.split('@');var result='';if(parts.length>1){// In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result=parts[0]+'@';string=parts[1];}// Avoid `split(regex)` for IE8 compatibility. See #17. string=string.replace(regexSeparators,'\x2E');var labels=string.split('.');var encoded=map(labels,fn).join('.');return result+encoded;}/** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter=0xD800&&value<=0xDBFF&&counter0xFFFF){value-=0x10000;output+=stringFromCharCode(value>>>10&0x3FF|0xD800);value=0xDC00|value&0x3FF;}output+=stringFromCharCode(value);return output;}).join('');}/** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22;}if(codePoint-65<26){return codePoint-65;}if(codePoint-97<26){return codePoint-97;}return base;}/** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */function digitToBasic(digit,flag){// 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit+22+75*(digit<26)-((flag!=0)<<5);}/** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for/* no initialization */(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}/** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */function decode(input){// Don't use UCS-2 var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,/** Cached calculation results */baseMinusT;// Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic=input.lastIndexOf(delimiter);if(basic<0){basic=0;}for(j=0;j=0x80){error('not-basic');}output.push(input.charCodeAt(j));}// Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for/* no final expression */(index=basic>0?basic+1:0;index=inputLength){error('invalid-input');}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error('overflow');}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digitfloor(maxInt/baseMinusT)){error('overflow');}w*=baseMinusT;}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);// `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if(floor(i/out)>maxInt-n){error('overflow');}n+=floor(i/out);i%=out;// Insert `n` at position `i` of the output output.splice(i++,0,n);}return ucs2encode(output);}/** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],/** `inputLength` will hold the number of code points in `input`. */inputLength,/** Cached calculation results */handledCPCountPlusOne,baseMinusT,qMinusT;// Convert the input in UCS-2 to Unicode input=ucs2decode(input);// Cache the length inputLength=input.length;// Initialize the state n=initialN;delta=0;bias=initialBias;// Handle the basic code points for(j=0;j=n&¤tValue state to , // but guard against overflow handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error('overflow');}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;jmaxInt){error('overflow');}if(currentValue==n){// Represent delta as a generalized variable-length integer for/* no condition */(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q * @memberOf punycode * @type Object */'ucs2':{'decode':ucs2decode,'encode':ucs2encode},'decode':decode,'encode':encode,'toASCII':toASCII,'toUnicode':toUnicode};/** Expose `punycode` */// Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if( true&&_typeof(__webpack_require__.amdO)=='object'&&__webpack_require__.amdO){!(__WEBPACK_AMD_DEFINE_RESULT__ = (function(){return punycode;}).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));}else if(freeExports&&freeModule){if(module.exports==freeExports){// in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports=punycode;}else{// in Narwhal or RingoJS v0.7.0- for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key]);}}}else{// in Rhino or a web browser root.punycode=punycode;}})(this);}).call(this);}).call(this,typeof __webpack_require__.g!=="undefined"?__webpack_require__.g:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{}],93:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict';// If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop);}module.exports=function(qs,sep,eq,options){sep=sep||'&';eq=eq||'=';var obj={};if(typeof qs!=='string'||qs.length===0){return obj;}var regexp=/\+/g;qs=qs.split(sep);var maxKeys=1000;if(options&&typeof options.maxKeys==='number'){maxKeys=options.maxKeys;}var len=qs.length;// maxKeys <= 0 means that we should not limit keys count if(maxKeys>0&&len>maxKeys){len=maxKeys;}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1);}else{kstr=x;vstr='';}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v;}else if(isArray(obj[k])){obj[k].push(v);}else{obj[k]=[obj[k],v];}}return obj;};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};},{}],94:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict';var stringifyPrimitive=function stringifyPrimitive(v){switch(_typeof(v)){case'string':return v;case'boolean':return v?'true':'false';case'number':return isFinite(v)?v:'';default:return'';}};module.exports=function(obj,sep,eq,name){sep=sep||'&';eq=eq||'=';if(obj===null){obj=undefined;}if(_typeof(obj)==='object'){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v));}).join(sep);}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]));}}).join(sep);}if(!name)return'';return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj));};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i0&&len>maxKeys){len=maxKeys;}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1);}else{kstr=x;vstr='';}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v;}else if(Array.isArray(obj[k])){obj[k].push(v);}else{obj[k]=[obj[k],v];}}return obj;};},{}],97:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict';var stringifyPrimitive=function stringifyPrimitive(v){switch(_typeof(v)){case'string':return v;case'boolean':return v?'true':'false';case'number':return isFinite(v)?v:'';default:return'';}};module.exports=function(obj,sep,eq,name){sep=sep||'&';eq=eq||'=';if(obj===null){obj=undefined;}if(_typeof(obj)==='object'){return Object.keys(obj).map(function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(Array.isArray(obj[k])){return obj[k].map(function(v){return ks+encodeURIComponent(stringifyPrimitive(v));}).join(sep);}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]));}}).join(sep);}if(!name)return'';return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj));};},{}],98:[function(require,module,exports){arguments[4][95][0].apply(exports,arguments);},{"./decode":96,"./encode":97,"dup":95}],99:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require('process/browser.js').nextTick;var apply=Function.prototype.apply;var slice=Array.prototype.slice;var immediateIds={};var nextImmediateId=0;// DOM APIs, for completeness exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout);};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval);};exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close();};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn;}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id);};// Does not start the time, just sets up the members needed. exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs;};exports.unenroll=function(item){clearTimeout(item._idleTimeoutId);item._idleTimeout=-1;};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout(function onTimeout(){if(item._onTimeout)item._onTimeout();},msecs);}};// That's not how node.js implements it but the exposed api is the same. exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick(function onNextTick(){if(immediateIds[id]){// fn.call() is faster so we optimize for the common use-case // @see http://jsperf.com/call-apply-segu if(args){fn.apply(null,args);}else{fn.call(null);}// Prevent ids from leaking exports.clearImmediate(id);}});return id;};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id];};}).call(this);}).call(this,require("timers").setImmediate,require("timers").clearImmediate);},{"process/browser.js":91,"timers":99}],100:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var punycode=require('punycode');exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null;}// Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,// RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims=['<','>','"','`',' ','\r','\n','\t'],// RFC 2396: characters not allowed for various reasons. unwise=['{','}','|','\\','^','`'].concat(delims),// Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape=['\''].concat(unwise),// Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars=['%','/','?',';','#'].concat(autoEscape),hostEndingChars=['/','?','#'],hostnameMaxLen=255,hostnamePartPattern=/^[a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([a-z0-9A-Z_-]{0,63})(.*)$/,// protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol={'javascript':true,'javascript:':true},// protocols that never have a hostname. hostlessProtocol={'javascript':true,'javascript:':true},// protocols that always contain a // bit. slashedProtocol={'http':true,'https':true,'ftp':true,'gopher':true,'file':true,'http:':true,'https:':true,'ftp:':true,'gopher:':true,'file:':true},querystring=require('querystring');function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&isObject(url)&&url instanceof Url)return url;var u=new Url();u.parse(url,parseQueryString,slashesDenoteHost);return u;}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+_typeof(url));}var rest=url;// trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest=rest.trim();var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length);}// figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==='//';if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true;}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){// there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd=-1;for(var i=0;i host:b auth:a path:/c@d atSign=rest.lastIndexOf('@',hostEnd);}// Now we have a portion which is definitely the auth. // Pull that off. if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth);}// the host is the remaining to the left of the first non-host char hostEnd=-1;for(var i=0;i127){// we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart+='x';}else{newpart+=part[j];}}// we test again with ASCII char only if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2]);}if(notHost.length){rest='/'+notHost.join('.')+rest;}this.hostname=validParts.join('.');break;}}}}if(this.hostname.length>hostnameMaxLen){this.hostname='';}else{// hostnames are always lower case. this.hostname=this.hostname.toLowerCase();}if(!ipv6Hostname){// IDNA Support: Returns a puny coded representation of "domain". // It only converts the part of the domain name that // has non ASCII characters. I.e. it dosent matter if // you call it with a domain that already is in ASCII. var domainArray=this.hostname.split('.');var newOut=[];for(var i=0;i0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift();}}result.search=relative.search;result.query=relative.query;//to support http.request if(!isNull(result.pathname)||!isNull(result.search)){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.href=result.format();return result;}if(!srcPath.length){// no path at all. easy. // we've already handled the other stuff above. result.pathname=null;//to support http.request if(result.search){result.path='/'+result.search;}else{result.path=null;}result.href=result.format();return result;}// if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host)&&(last==='.'||last==='..')||last==='';// strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last=='.'){srcPath.splice(i,1);}else if(last==='..'){srcPath.splice(i,1);up++;}else if(up){srcPath.splice(i,1);up--;}}// if the path is allowed to go above the root, restore leading ..s if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift('..');}}if(mustEndAbs&&srcPath[0]!==''&&(!srcPath[0]||srcPath[0].charAt(0)!=='/')){srcPath.unshift('');}if(hasTrailingSlash&&srcPath.join('/').substr(-1)!=='/'){srcPath.push('');}var isAbsolute=srcPath[0]===''||srcPath[0]&&srcPath[0].charAt(0)==='/';// put the host back if(psychotic){result.hostname=result.host=isAbsolute?'':srcPath.length?srcPath.shift():'';//occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost=result.host&&result.host.indexOf('@')>0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift();}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift('');}if(!srcPath.length){result.pathname=null;result.path=null;}else{result.pathname=srcPath.join('/');}//to support request.http if(!isNull(result.pathname)||!isNull(result.search)){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result;};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==':'){this.port=port.substr(1);}host=host.substr(0,host.length-port.length);}if(host)this.hostname=host;};function isString(arg){return typeof arg==="string";}function isObject(arg){return _typeof(arg)==='object'&&arg!==null;}function isNull(arg){return arg===null;}function isNullOrUndefined(arg){return arg==null;}},{"punycode":92,"querystring":95}],101:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;/** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */var byteToHex=[];for(var i=0;i<256;++i){byteToHex[i]=(i+0x100).toString(16).substr(1);}function bytesToUuid(buf,offset){var i=offset||0;var bth=byteToHex;// join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 return[bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]]].join('');}var _default=bytesToUuid;exports["default"]=_default;},{}],102:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"v1",{enumerable:true,get:function get(){return _v["default"];}});Object.defineProperty(exports,"v3",{enumerable:true,get:function get(){return _v2["default"];}});Object.defineProperty(exports,"v4",{enumerable:true,get:function get(){return _v3["default"];}});Object.defineProperty(exports,"v5",{enumerable:true,get:function get(){return _v4["default"];}});var _v=_interopRequireDefault(require("./v1.js"));var _v2=_interopRequireDefault(require("./v3.js"));var _v3=_interopRequireDefault(require("./v4.js"));var _v4=_interopRequireDefault(require("./v5.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj};}},{"./v1.js":106,"./v3.js":107,"./v4.js":109,"./v5.js":110}],103:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;/* * Browser-compatible JavaScript MD5 * * Modification of JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * https://opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */function md5(bytes){if(typeof bytes=='string'){var msg=unescape(encodeURIComponent(bytes));// UTF8 escape bytes=new Array(msg.length);for(var i=0;i>5]>>>i%32&0xff;hex=parseInt(hexTab.charAt(x>>>4&0x0f)+hexTab.charAt(x&0x0f),16);output.push(hex);}return output;}/* * Calculate the MD5 of an array of little-endian words, and a bit length. */function wordsToMd5(x,len){/* append padding */x[len>>5]|=0x80<>>9<<4)+14]=len;var i;var olda;var oldb;var oldc;var oldd;var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;for(i=0;i255 have their high-byte silently ignored. */function bytesToWords(input){var i;var output=[];output[(input.length>>2)-1]=undefined;for(i=0;i>5]|=(input[i/8]&0xff)<>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&0xffff;}/* * Bitwise rotate a 32-bit number to the left. */function bitRotateLeft(num,cnt){return num<>>32-cnt;}/* * These functions implement the four basic operations the algorithm uses. */function md5cmn(q,a,b,x,s,t){return safeAdd(bitRotateLeft(safeAdd(safeAdd(a,q),safeAdd(x,t)),s),b);}function md5ff(a,b,c,d,x,s,t){return md5cmn(b&c|~b&d,a,b,x,s,t);}function md5gg(a,b,c,d,x,s,t){return md5cmn(b&d|c&~d,a,b,x,s,t);}function md5hh(a,b,c,d,x,s,t){return md5cmn(b^c^d,a,b,x,s,t);}function md5ii(a,b,c,d,x,s,t){return md5cmn(c^(b|~d),a,b,x,s,t);}var _default=md5;exports["default"]=_default;},{}],104:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=rng;// Unique ID creation requires a high quality random # generator. In the browser we therefore // require the crypto API and do not support built-in fallback to lower quality random number // generators (like Math.random()). // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, // find the complete implementation of crypto (msCrypto) on IE11. var getRandomValues=typeof crypto!='undefined'&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!='undefined'&&typeof msCrypto.getRandomValues=='function'&&msCrypto.getRandomValues.bind(msCrypto);var rnds8=new Uint8Array(16);// eslint-disable-line no-undef function rng(){if(!getRandomValues){throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');}return getRandomValues(rnds8);}},{}],105:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;// Adapted from Chris Veness' SHA1 code at // http://www.movable-type.co.uk/scripts/sha1.html function f(s,x,y,z){switch(s){case 0:return x&y^~x&z;case 1:return x^y^z;case 2:return x&y^x&z^y&z;case 3:return x^y^z;}}function ROTL(x,n){return x<>>32-n;}function sha1(bytes){var K=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6];var H=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0];if(typeof bytes=='string'){var msg=unescape(encodeURIComponent(bytes));// UTF8 escape bytes=new Array(msg.length);for(var i=0;i>>0;e=d;d=c;c=ROTL(b,30)>>>0;b=a;a=T;}H[0]=H[0]+a>>>0;H[1]=H[1]+b>>>0;H[2]=H[2]+c>>>0;H[3]=H[3]+d>>>0;H[4]=H[4]+e>>>0;}return[H[0]>>24&0xff,H[0]>>16&0xff,H[0]>>8&0xff,H[0]&0xff,H[1]>>24&0xff,H[1]>>16&0xff,H[1]>>8&0xff,H[1]&0xff,H[2]>>24&0xff,H[2]>>16&0xff,H[2]>>8&0xff,H[2]&0xff,H[3]>>24&0xff,H[3]>>16&0xff,H[3]>>8&0xff,H[3]&0xff,H[4]>>24&0xff,H[4]>>16&0xff,H[4]>>8&0xff,H[4]&0xff];}var _default=sha1;exports["default"]=_default;},{}],106:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _rng=_interopRequireDefault(require("./rng.js"));var _bytesToUuid=_interopRequireDefault(require("./bytesToUuid.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj};}// **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html var _nodeId;var _clockseq;// Previous uuid creation time var _lastMSecs=0;var _lastNSecs=0;// See https://github.com/uuidjs/uuid for API details function v1(options,buf,offset){var i=buf&&offset||0;var b=buf||[];options=options||{};var node=options.node||_nodeId;var clockseq=options.clockseq!==undefined?options.clockseq:_clockseq;// node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if(node==null||clockseq==null){var seedBytes=options.random||(options.rng||_rng["default"])();if(node==null){// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node=_nodeId=[seedBytes[0]|0x01,seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]];}if(clockseq==null){// Per 4.2.2, randomize (14 bit) clockseq clockseq=_clockseq=(seedBytes[6]<<8|seedBytes[7])&0x3fff;}}// UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs=options.msecs!==undefined?options.msecs:new Date().getTime();// Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs=options.nsecs!==undefined?options.nsecs:_lastNSecs+1;// Time since last uuid creation (in msecs) var dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/10000;// Per 4.2.1.2, Bump clockseq on clock regression if(dt<0&&options.clockseq===undefined){clockseq=clockseq+1&0x3fff;}// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if((dt<0||msecs>_lastMSecs)&&options.nsecs===undefined){nsecs=0;}// Per 4.2.1.2 Throw error if too many uuids are requested if(nsecs>=10000){throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");}_lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;// Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs+=12219292800000;// `time_low` var tl=((msecs&0xfffffff)*10000+nsecs)%0x100000000;b[i++]=tl>>>24&0xff;b[i++]=tl>>>16&0xff;b[i++]=tl>>>8&0xff;b[i++]=tl&0xff;// `time_mid` var tmh=msecs/0x100000000*10000&0xfffffff;b[i++]=tmh>>>8&0xff;b[i++]=tmh&0xff;// `time_high_and_version` b[i++]=tmh>>>24&0xf|0x10;// include version b[i++]=tmh>>>16&0xff;// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++]=clockseq>>>8|0x80;// `clock_seq_low` b[i++]=clockseq&0xff;// `node` for(var n=0;n<6;++n){b[i+n]=node[n];}return buf?buf:(0,_bytesToUuid["default"])(b);}var _default=v1;exports["default"]=_default;},{"./bytesToUuid.js":101,"./rng.js":104}],107:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _v=_interopRequireDefault(require("./v35.js"));var _md=_interopRequireDefault(require("./md5.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj};}var v3=(0,_v["default"])('v3',0x30,_md["default"]);var _default=v3;exports["default"]=_default;},{"./md5.js":103,"./v35.js":108}],108:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=_default;exports.URL=exports.DNS=void 0;var _bytesToUuid=_interopRequireDefault(require("./bytesToUuid.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj};}function uuidToBytes(uuid){// Note: We assume we're being passed a valid uuid string var bytes=[];uuid.replace(/[a-fA-F0-9]{2}/g,function(hex){bytes.push(parseInt(hex,16));});return bytes;}function stringToBytes(str){str=unescape(encodeURIComponent(str));// UTF8 escape var bytes=new Array(str.length);for(var i=0;i=0;i--){var record=records[i];if(record.Expire { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; /**--------------------------------------------------------------- * enum ClientMethods */ connect.ClientMethods = connect.makeEnum(['getAgentSnapshot', 'putAgentState', 'getAgentStates', 'getDialableCountryCodes', 'getRoutingProfileQueues', 'getAgentPermissions', 'getAgentConfiguration', 'updateAgentConfiguration', 'acceptContact', 'createOutboundContact', 'createTaskContact', 'clearContact', 'completeContact', 'destroyContact', 'rejectContact', 'notifyContactIssue', 'updateContactAttributes', 'createAdditionalConnection', 'destroyConnection', 'holdConnection', 'resumeConnection', 'toggleActiveConnections', 'conferenceConnections', 'sendClientLogs', 'sendDigits', 'sendSoftphoneCallReport', 'sendSoftphoneCallMetrics', 'getEndpoints', 'getNewAuthToken', 'createTransport', 'muteParticipant', 'unmuteParticipant', 'updateMonitorParticipantState', 'pauseContact', 'resumeContact', 'addNewConnection', 'transferContact']); /**--------------------------------------------------------------- * enum AgentAppClientMethods */ connect.AgentAppClientMethods = { GET_CONTACT: "AgentAppService.Lcms.getContact", DELETE_SPEAKER: "AgentAppService.VoiceId.deleteSpeaker", ENROLL_BY_SESSION: "AgentAppService.VoiceId.enrollBySession", EVALUATE_SESSION: "AgentAppService.VoiceId.evaluateSession", DESCRIBE_SPEAKER: "AgentAppService.VoiceId.describeSpeaker", OPT_OUT_SPEAKER: "AgentAppService.VoiceId.optOutSpeaker", UPDATE_VOICE_ID_DATA: "AgentAppService.Lcms.updateVoiceIdData", DESCRIBE_SESSION: "AgentAppService.VoiceId.describeSession", UPDATE_SESSION: "AgentAppService.VoiceId.updateSession", START_VOICE_ID_SESSION: "AgentAppService.Nasa.startVoiceIdSession", LIST_INTEGRATION_ASSOCIATIONS: "AgentAppService.Acs.listIntegrationAssociations" }; /**--------------------------------------------------------------- * enum MasterMethods */ connect.MasterMethods = connect.makeEnum(['becomeMaster', 'checkMaster']); /**--------------------------------------------------------------- * enum TaskTemplatesClientMethods */ connect.TaskTemplatesClientMethods = connect.makeEnum(['listTaskTemplates', 'getTaskTemplate', 'createTemplatedTask', 'updateContact']); /**--------------------------------------------------------------- * enum ApiProxyClientMethods */ connect.ApiProxyClientMethods = { QR_INTEGRATION_EXISTS: 'qrIntegrationExists', QR_SEARCH_QUICK_RESPONSES: 'qrSearchQuickResponses', START_SCREEN_SHARING: "startScreenSharing" }, /**--------------------------------------------------------------- * client methods that are retryable */ connect.RetryableClientMethodsList = [connect.ClientMethods.GET_AGENT_SNAPSHOT, connect.ClientMethods.GET_AGENT_CONFIGURATION, connect.ClientMethods.GET_AGENT_PERMISSIONS, connect.ClientMethods.GET_AGENT_STATES, connect.ClientMethods.GET_DIALABLE_COUNTRY_CODES, connect.ClientMethods.GET_ROUTING_PROFILE_QUEUES]; /**--------------------------------------------------------------- * retry error types */ connect.RetryableErrors = connect.makeEnum(['unauthorized', 'accessDenied']); /**--------------------------------------------------------------- * retryStatus */ connect.RetryStatus = connect.makeEnum(['retrying', 'exhausted', 'none']); /**--------------------------------------------------------------- * abstract class ClientBase */ var ClientBase = function ClientBase() {}; ClientBase.EMPTY_CALLBACKS = { success: function success() {}, failure: function failure() {} }; ClientBase.prototype.call = function (method, paramsIn, callbacksIn) { connect.assertNotNull(method, 'method'); var params = paramsIn || {}; var callbacks = callbacksIn || ClientBase.EMPTY_CALLBACKS; this._callImpl(method, params, callbacks); }; ClientBase.prototype._callImpl = function (method, params, callbacks) { throw new connect.NotImplementedError(); }; /**--------------------------------------------------------------- * class NullClient extends ClientBase */ var NullClient = function NullClient() { ClientBase.call(this); }; NullClient.prototype = Object.create(ClientBase.prototype); NullClient.prototype.constructor = NullClient; NullClient.prototype._callImpl = function (method, params, callbacks) { if (callbacks && callbacks.failure) { var message = connect.sprintf('No such method exists on NULL client: %s', method); callbacks.failure(new connect.ValueError(message), { message: message }); } }; /**--------------------------------------------------------------- * abstract class UpstreamConduitClientBase extends ClientBase */ var UpstreamConduitClientBase = function UpstreamConduitClientBase(conduit, requestEvent, responseEvent) { ClientBase.call(this); this.conduit = conduit; this.requestEvent = requestEvent; this.responseEvent = responseEvent; this._requestIdCallbacksMap = {}; this.conduit.onUpstream(responseEvent, connect.hitch(this, this._handleResponse)); }; UpstreamConduitClientBase.prototype = Object.create(ClientBase.prototype); UpstreamConduitClientBase.prototype.constructor = UpstreamConduitClientBase; UpstreamConduitClientBase.prototype._callImpl = function (method, params, callbacks) { var request = connect.EventFactory.createRequest(this.requestEvent, method, params); this._requestIdCallbacksMap[request.requestId] = callbacks; var methodsToSkip = [connect.ClientMethods.SEND_CLIENT_LOGS, connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS, connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT]; try { if (request.event === connect.EventType.API_REQUEST && !methodsToSkip.includes(request.method)) { connect.getLog().trace("Sending API_REQUEST event for ".concat(request.method, " to upstream")).withObject({ method: request.method, params: request.params, stack: new Error().stack }).sendInternalLogToServer(); } } catch (err) { connect.getLog().error("Stack trace Log Failed").withObject({ err: err }).sendInternalLogToServer(); } this.conduit.sendUpstream(request.event, request); }; UpstreamConduitClientBase.prototype._getCallbacksForRequest = function (requestId) { var callbacks = this._requestIdCallbacksMap[requestId] || null; if (callbacks != null) { delete this._requestIdCallbacksMap[requestId]; } return callbacks; }; UpstreamConduitClientBase.prototype._handleResponse = function (data) { var callbacks = this._getCallbacksForRequest(data.requestId); if (callbacks == null) { return; } if (data.err && callbacks.failure) { callbacks.failure(data.err, data.data); } else if (callbacks.success) { callbacks.success(data.data); } }; /**--------------------------------------------------------------- * class UpstreamConduitClient extends ClientBase */ var UpstreamConduitClient = function UpstreamConduitClient(conduit) { UpstreamConduitClientBase.call(this, conduit, connect.EventType.API_REQUEST, connect.EventType.API_RESPONSE); }; UpstreamConduitClient.prototype = Object.create(UpstreamConduitClientBase.prototype); UpstreamConduitClient.prototype.constructor = UpstreamConduitClient; /**--------------------------------------------------------------- * class ApiProxyClient extends ClientBase */ var ApiProxyClient = function ApiProxyClient() { ClientBase.call(this); var bus = connect.core.getEventBus(); bus.subscribe(connect.EventType.API_PROXY_RESPONSE, connect.hitch(this, this._handleResponse)); this._requestIdCallbacksMap = {}; }; /** * An eventbus client/wrapper. Sends API_PROXY_REQUEST events and listens for API_PROXY_RESPONSE events. */ ApiProxyClient.prototype = Object.create(ClientBase.prototype); ApiProxyClient.prototype.constructor = ApiProxyClient; ApiProxyClient.prototype._callImpl = function (method, params, callbacks) { var request = connect.EventFactory.createRequest(connect.EventType.API_PROXY_REQUEST, method, params); this._requestIdCallbacksMap[request.requestId] = callbacks; connect.core.getEventBus().trigger(connect.EventType.API_PROXY_REQUEST, request); //sends to CCP listener }; ApiProxyClient.prototype._getCallbacksForRequest = function (requestId) { var callbacks = this._requestIdCallbacksMap[requestId] || null; if (callbacks != null) { delete this._requestIdCallbacksMap[requestId]; } return callbacks; }; ApiProxyClient.prototype._handleResponse = function (data) { var callbacks = this._getCallbacksForRequest(data.requestId); if (callbacks == null) { return; } if (data.err && callbacks.failure) { callbacks.failure(data.err, data.data); } else if (callbacks.success) { callbacks.success(data.data); } }; /**--------------------------------------------------------------- * class UpstreamConduitMasterClient extends ClientBase */ var UpstreamConduitMasterClient = function UpstreamConduitMasterClient(conduit) { UpstreamConduitClientBase.call(this, conduit, connect.EventType.MASTER_REQUEST, connect.EventType.MASTER_RESPONSE); }; UpstreamConduitMasterClient.prototype = Object.create(UpstreamConduitClientBase.prototype); UpstreamConduitMasterClient.prototype.constructor = UpstreamConduitMasterClient; /**--------------------------------------------------------------- * class AgentAppClient extends ClientBase */ var AgentAppClient = function AgentAppClient(authCookieName, authToken, endpoint) { connect.assertNotNull(authCookieName, 'authCookieName'); connect.assertNotNull(authToken, 'authToken'); connect.assertNotNull(endpoint, 'endpoint'); ClientBase.call(this); this.endpointUrl = connect.getUrlWithProtocol(endpoint); this.authToken = authToken; this.authCookieName = authCookieName; }; AgentAppClient.prototype = Object.create(ClientBase.prototype); AgentAppClient.prototype.constructor = AgentAppClient; AgentAppClient.prototype._callImpl = function (method, params, callbacks) { var self = this; var bear = {}; bear[self.authCookieName] = self.authToken; var options = { method: 'post', body: JSON.stringify(params || {}), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Amz-target': method, 'X-Amz-Bearer': JSON.stringify(bear) } }; connect.fetch(self.endpointUrl, options).then(function (res) { callbacks.success(res); })["catch"](function (err) { var reader = err.body.getReader(); var body = ''; var decoder = new TextDecoder(); reader.read().then(function processText(_ref) { var done = _ref.done, value = _ref.value; if (done) { var error = JSON.parse(body); error.status = err.status; callbacks.failure(error); return; } body += decoder.decode(value); return reader.read().then(processText); }); }); }; /**--------------------------------------------------------------- * class AWSClient extends ClientBase */ var AWSClient = function AWSClient(authToken, region, endpointIn) { connect.assertNotNull(authToken, 'authToken'); connect.assertNotNull(region, 'region'); ClientBase.call(this); AWS.config.credentials = new AWS.Credentials({}); AWS.config.region = region; this.authToken = authToken; var baseUrl = connect.getBaseUrl(); var endpointUrl = endpointIn || (baseUrl.includes(".awsapps.com") ? baseUrl + '/connect/api' : baseUrl + '/api'); var endpoint = new AWS.Endpoint(endpointUrl); this.client = new AWS.Connect({ endpoint: endpoint }); this.unauthorizedFailCounter = 0; this.accessDeniedFailCounter = 0; }; AWSClient.prototype = Object.create(ClientBase.prototype); AWSClient.prototype.constructor = AWSClient; AWSClient.prototype._callImpl = function (method, params, callbacks) { var self = this; var log = connect.getLog(); if (!connect.contains(this.client, method)) { var message = connect.sprintf('No such method exists on AWS client: %s', method); callbacks.failure(new connect.ValueError(message), { message: message }); } else { params = this._translateParams(method, params); // only relatedContactId or previousContactId can exist if (params && params.relatedContactId && params.relatedContactId !== null) { if (params.previousContactId) { delete params.previousContactId; } } log.trace("AWSClient: --> Calling operation '%s'", method).sendInternalLogToServer(); this.client[method](params).on('build', function (request) { request.httpRequest.headers['X-Amz-Bearer'] = self.authToken; }).send(function (err, data) { try { if (err) { if (err.code === connect.CTIExceptions.UNAUTHORIZED_EXCEPTION || err.statusCode === 401) { self._retryMethod(method, callbacks, err, data, connect.RetryableErrors.UNAUTHORIZED); } else if (err.code === connect.CTIExceptions.ACCESS_DENIED_EXCEPTION || err.statusCode === 403) { self._retryMethod(method, callbacks, err, data, connect.RetryableErrors.ACCESS_DENIED); } else { self.unauthorizedFailCounter = 0; self.accessDeniedFailCounter = 0; callbacks.failure(self._formatCallError(self._addStatusCodeToError(err)), data); } log.trace("AWSClient: <-- Operation '%s' failed: %s", method, JSON.stringify(err)).sendInternalLogToServer(); } else { var dataAttribute = {}; log.trace("AWSClient: <-- Operation '%s' succeeded.", method).withObject(data).sendInternalLogToServer(); self.unauthorizedFailCounter = 0; self.accessDeniedFailCounter = 0; if (this.httpResponse && this.httpResponse.hasOwnProperty('body')) { dataAttribute.contentLength = this.httpResponse.body.length; } callbacks.success(data, dataAttribute); } } catch (e) { connect.getLog().error("Failed to handle AWS API request for method %s", method).withException(e).sendInternalLogToServer(); } }); } }; AWSClient.prototype._isRetryableMethod = function (method) { return connect.RetryableClientMethodsList.includes(method); }; AWSClient.prototype._retryMethod = function (method, callbacks, err, data, retryableError) { var self = this; var log = connect.getLog(); var formatRetryError = function formatRetryError(err) { return self._formatCallError(self._addStatusCodeToError(err)); }; var retryParams = { maxCount: connect.core.MAX_UNAUTHORIZED_RETRY_COUNT, failCounter: self.unauthorizedFailCounter, increaseCounter: function increaseCounter() { return self.unauthorizedFailCounter += 1; }, resetCounter: function resetCounter() { return self.unauthorizedFailCounter = 0; }, errorMessage: 'unauthorized', exhaustedRetries: self.unauthorizedFailCounter >= connect.core.MAX_UNAUTHORIZED_RETRY_COUNT, retryCallback: function retryCallback(err, data) { return callbacks.failure(formatRetryError(err), data); }, defaultCallback: function defaultCallback(err, data) { return callbacks.authFailure(formatRetryError(err), data); } }; switch (retryableError) { case connect.RetryableErrors.UNAUTHORIZED: break; case connect.RetryableErrors.ACCESS_DENIED: retryParams = _objectSpread(_objectSpread({}, retryParams), {}, { maxCount: connect.core.MAX_ACCESS_DENIED_RETRY_COUNT, failCounter: self.accessDeniedFailCounter, increaseCounter: function increaseCounter() { return self.accessDeniedFailCounter += 1; }, resetCounter: function resetCounter() { return self.accessDeniedFailCounter = 0; }, errorMessage: 'access denied', exhaustedRetries: self.accessDeniedFailCounter >= connect.core.MAX_ACCESS_DENIED_RETRY_COUNT, defaultCallback: function defaultCallback(err, data) { return callbacks.accessDenied(formatRetryError(err), data); } }); break; } var errWithRetry = _objectSpread(_objectSpread({}, err), {}, { retryStatus: connect.RetryStatus.NONE }); if (self._isRetryableMethod(method)) { if (retryParams.exhaustedRetries) { log.trace("AWSClient: <-- Operation ".concat(method, " exhausted max ").concat(retryParams.maxCount, " number of retries for ").concat(retryParams.errorMessage, " error")).sendInternalLogToServer(); retryParams.resetCounter(); errWithRetry = _objectSpread(_objectSpread({}, errWithRetry), {}, { retryStatus: connect.RetryStatus.EXHAUSTED }); } else { log.trace("AWSClient: <-- Operation ".concat(method, " failed with ").concat(retryParams.errorMessage, " error. Retrying call for a ").concat(retryParams.failCounter + 1, " time")).sendInternalLogToServer(); retryParams.increaseCounter(); errWithRetry = _objectSpread(_objectSpread({}, errWithRetry), {}, { retryStatus: connect.RetryStatus.RETRYING }); retryParams.retryCallback(errWithRetry, data); return; } } else { log.trace("AWSClient: <-- Operation ".concat(method, " failed: ").concat(JSON.stringify(err))).sendInternalLogToServer(); } retryParams.defaultCallback(errWithRetry, data); return; }; // Can't pass err directly to postMessage // postMessage() tries to clone the err object and failed. // Refer to https://github.com/goatslacker/alt-devtool/issues/5 AWSClient.prototype._formatCallError = function (err) { var error = _objectSpread({ type: err.code, message: err.message, stack: [], retryStatus: err.retryStatus || connect.RetryStatus.NONE }, err.statusCode && { statusCode: err.statusCode }); if (err.stack) { try { if (Array.isArray(err.stack)) { error.stack = err.stack; } else if (_typeof(err.stack) === 'object') { error.stack = [JSON.stringify(err.stack)]; } else if (typeof err.stack === 'string') { error.stack = err.stack.split('\n'); } } finally {} } return error; }; AWSClient.prototype._addStatusCodeToError = function (err) { if (err.statusCode) return err; var error = _objectSpread({}, err); if (!err.code) { error.statusCode = 400; } else { // TODO: add more here switch (error.code) { case connect.CTIExceptions.UNAUTHORIZED_EXCEPTION: error.statusCode = 401; break; case connect.CTIExceptions.ACCESS_DENIED_EXCEPTION: error.statusCode = 403; break; } } return error; }; AWSClient.prototype._requiresAuthenticationParam = function (method) { return method !== connect.ClientMethods.COMPLETE_CONTACT && method !== connect.ClientMethods.CLEAR_CONTACT && method !== connect.ClientMethods.REJECT_CONTACT && method !== connect.ClientMethods.CREATE_TASK_CONTACT && method !== connect.ClientMethods.UPDATE_MONITOR_PARTICIPANT_STATE && method !== connect.ClientMethods.PAUSE_CONTACT && method !== connect.ClientMethods.RESUME_CONTACT && method !== connect.ClientMethods.ADD_NEW_CONNECTION && method !== connect.ClientMethods.TRANSFER_CONTACT; }; AWSClient.prototype._translateParams = function (method, params) { switch (method) { case connect.ClientMethods.UPDATE_AGENT_CONFIGURATION: params.configuration = this._translateAgentConfiguration(params.configuration); break; case connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS: params.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics(params.softphoneStreamStatistics); break; case connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT: params.report = this._translateSoftphoneCallReport(params.report); break; default: break; } if (this._requiresAuthenticationParam(method)) { params.authentication = { authToken: this.authToken }; } return params; }; AWSClient.prototype._translateAgentConfiguration = function (config) { return { name: config.name, softphoneEnabled: config.softphoneEnabled, softphoneAutoAccept: config.softphoneAutoAccept, extension: config.extension, routingProfile: this._translateRoutingProfile(config.routingProfile), agentPreferences: config.agentPreferences }; }; AWSClient.prototype._translateRoutingProfile = function (profile) { return { name: profile.name, routingProfileARN: profile.routingProfileARN, defaultOutboundQueue: this._translateQueue(profile.defaultOutboundQueue) }; }; AWSClient.prototype._translateQueue = function (queue) { return { queueARN: queue.queueARN, name: queue.name }; }; AWSClient.prototype._translateSoftphoneStreamStatistics = function (stats) { stats.forEach(function (stat) { if ('packetsCount' in stat) { stat.packetCount = stat.packetsCount; delete stat.packetsCount; } }); return stats; }; AWSClient.prototype._translateSoftphoneCallReport = function (report) { if ('handshakingTimeMillis' in report) { report.handshakeTimeMillis = report.handshakingTimeMillis; delete report.handshakingTimeMillis; } if ('preTalkingTimeMillis' in report) { report.preTalkTimeMillis = report.preTalkingTimeMillis; delete report.preTalkingTimeMillis; } if ('handshakingFailure' in report) { report.handshakeFailure = report.handshakingFailure; delete report.handshakingFailure; } if ('talkingTimeMillis' in report) { report.talkTimeMillis = report.talkingTimeMillis; delete report.talkingTimeMillis; } report.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics(report.softphoneStreamStatistics); return report; }; /**--------------------------------------------------------------- * class TaskTemplatesClient extends ClientBase */ var TaskTemplatesClient = function TaskTemplatesClient(endpoint) { connect.assertNotNull(endpoint, 'endpoint'); ClientBase.call(this); if (endpoint.includes('/task-templates')) { this.endpointUrl = connect.getUrlWithProtocol(endpoint); } else { var AWSEndpoint = new AWS.Endpoint(endpoint); var CFPrefix = endpoint.includes('.awsapps.com') ? '/connect' : ''; this.endpointUrl = connect.getUrlWithProtocol("".concat(AWSEndpoint.host).concat(CFPrefix, "/task-templates/api/ccp")); } }; TaskTemplatesClient.prototype = Object.create(ClientBase.prototype); TaskTemplatesClient.prototype.constructor = TaskTemplatesClient; TaskTemplatesClient.prototype._callImpl = function (method, params, callbacks) { // only relatedContactId or previousContactId can exist if (params && params.relatedContactId && params.relatedContactId !== null) { if (params.previousContactId) { delete params.previousContactId; } } connect.assertNotNull(method, 'method'); connect.assertNotNull(params, 'params'); var options = { credentials: 'include', method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'x-csrf-token': 'csrf' } }; var instanceId = params.instanceId; var url = this.endpointUrl; var methods = connect.TaskTemplatesClientMethods; switch (method) { case methods.LIST_TASK_TEMPLATES: url += "/proxy/instance/".concat(instanceId, "/task/template"); if (params.queryParams) { var queryString = new URLSearchParams(params.queryParams).toString(); if (queryString) { url += "?".concat(queryString); } } break; case methods.GET_TASK_TEMPLATE: connect.assertNotNull(params.templateParams, 'params.templateParams'); var id = connect.assertNotNull(params.templateParams.id, 'params.templateParams.id'); var version = params.templateParams.version; url += "/proxy/instance/".concat(instanceId, "/task/template/").concat(id); if (version) { url += "?snapshotVersion=".concat(version); } break; case methods.CREATE_TEMPLATED_TASK: url += "/".concat(method); options.body = JSON.stringify(params); options.method = 'PUT'; break; case methods.UPDATE_CONTACT: url += "/".concat(method); options.body = JSON.stringify(params); options.method = 'POST'; } connect.fetch(url, options).then(function (res) { callbacks.success(res); })["catch"](function (err) { var reader = err.body.getReader(); var body = ''; var decoder = new TextDecoder(); reader.read().then(function processText(_ref2) { var done = _ref2.done, value = _ref2.value; if (done) { var error = JSON.parse(body); error.status = err.status; callbacks.failure(error); return; } body += decoder.decode(value); return reader.read().then(processText); }); }); }; connect.ClientBase = ClientBase; connect.NullClient = NullClient; connect.UpstreamConduitClient = UpstreamConduitClient; connect.ApiProxyClient = ApiProxyClient; connect.UpstreamConduitMasterClient = UpstreamConduitMasterClient; connect.AWSClient = AWSClient; connect.AgentAppClient = AgentAppClient; connect.TaskTemplatesClient = TaskTemplatesClient; })(); /***/ }), /***/ 399: /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; connect.core = {}; connect.globalResiliency = connect.globalResiliency || {}; connect.core.initialized = false; connect.version = "2.22.0"; connect.outerContextStreamsVersion = null; connect.initCCPParams = null; connect.containerDiv = null; connect.DEFAULT_BATCH_SIZE = 500; // NOTE: These constants are currently also set in the global-resiliency file. // Until a solution is found, changes to these values should be done there as well. var CCP_SYN_TIMEOUT = 1000; // 1 sec var CCP_ACK_TIMEOUT = 3000; // 3 sec var CCP_LOAD_TIMEOUT = 5000; // 5 sec var CCP_IFRAME_REFRESH_INTERVAL = 5000; // 5 sec var CCP_DR_IFRAME_REFRESH_INTERVAL = 10000; //10 s var CCP_IFRAME_REFRESH_LIMIT = 10; // 10 attempts var CCP_IFRAME_NAME = 'Amazon Connect CCP'; var LEGACY_LOGIN_URL_PATTERN = "https://{alias}.awsapps.com/auth/?client_id={client_id}&redirect_uri={redirect}"; var CLIENT_ID_MAP = { "us-east-1": "06919f4fd8ed324e" }; var AUTHORIZE_ENDPOINT = "/auth/authorize"; var LEGACY_AUTHORIZE_ENDPOINT = "/connect/auth/authorize"; var AUTHORIZE_RETRY_INTERVAL = 2000; var AUTHORIZE_MAX_RETRY = 5; var LEGACY_WHITELISTED_ORIGINS_ENDPOINT = "/connect/whitelisted-origins"; var WHITELISTED_ORIGINS_ENDPOINT = "/whitelisted-origins"; var WHITELISTED_ORIGINS_RETRY_INTERVAL = 2000; var WHITELISTED_ORIGINS_MAX_RETRY = 5; var CSM_IFRAME_REFRESH_ATTEMPTS = 'IframeRefreshAttempts'; var CSM_IFRAME_REFRESH_ATTEMPTS_DR = 'IframeRefreshAttemptsDr'; var CSM_IFRAME_INITIALIZATION_SUCCESS = 'IframeInitializationSuccess'; var CSM_IFRAME_INITIALIZATION_SUCCESS_DR = 'IframeInitializationSuccessDr'; var CSM_IFRAME_INITIALIZATION_TIME = 'IframeInitializationTime'; var CSM_IFRAME_INITIALIZATION_TIME_DR = 'IframeInitializationTimeDr'; var CSM_SET_RINGER_DEVICE_BEFORE_INIT = 'SetRingerDeviceBeforeInitRingtoneEngine'; var CONNECTED_CCPS_SINGLE_TAB = 'ConnectedCCPSingleTabCount'; var CCP_TABS_ACROSS_BROWSER_COUNT = 'CCPTabsAcrossBrowserCount'; var MULTIPLE_INIT_SOFTPHONE_MANAGER_CALLS = 'MultipleInitSoftphoneManagerCalls'; var CHECK_LOGIN_POPUP_INTERVAL_MS = 1000; var APP = { GUIDES: 'customviews' }; var inactiveContactState = ['ended', 'missed', 'error', 'rejected', 'acw']; connect.numberOfConnectedCCPs = 0; connect.numberOfConnectedCCPsInThisTab = 0; connect.core.MAX_AUTHORIZE_RETRY_COUNT_FOR_SESSION = 3; connect.core.MAX_CTI_AUTH_RETRY_COUNT = 10; connect.core.ctiAuthRetryCount = 0; connect.core.authorizeTimeoutId = null; connect.core.ctiTimeoutId = null; // getSnapshot retries every 5 seconds on failure // this max retry value will issues retries within a 2 minute window connect.core.MAX_UNAUTHORIZED_RETRY_COUNT = 20; // access denied connect.core.MAX_ACCESS_DENIED_RETRY_COUNT = 10; /*---------------------------------------------------------------- * enum SessionStorageKeys */ connect.SessionStorageKeys = connect.makeEnum(['tab_id', 'authorize_retry_count']); /** * @deprecated * This function was only meant for internal use. * The name is misleading for what it should do. * Internally we have replaced its usage with `getLoginUrl`. */ var createLoginUrl = function createLoginUrl(params) { var redirect = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; connect.assertNotNull(redirect); if (params.loginUrl) { return params.loginUrl; } else if (params.alias) { log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."); return LEGACY_LOGIN_URL_PATTERN.replace("{alias}", params.alias).replace("{client_id}", CLIENT_ID_MAP["us-east-1"]).replace("{redirect}", global.encodeURIComponent(redirect)); } else { return params.ccpUrl; } }; /** * Replaces `createLoginUrl`, as that function's name was misleading. * The `params.alias` parameter is deprecated. Please refrain from using it. */ var getLoginUrl = function getLoginUrl(params) { var redirect = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; connect.assertNotNull(redirect); if (params.loginUrl) { return params.loginUrl; } else if (params.alias) { log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."); return LEGACY_LOGIN_URL_PATTERN.replace("{alias}", params.alias).replace("{client_id}", CLIENT_ID_MAP["us-east-1"]).replace("{redirect}", global.encodeURIComponent(redirect)); } else { return params.ccpUrl; } }; /** * baseParamsStorage. Base class to store params of other modules in local storage * Used mainly for cases where embedded CCP gets refreshed. * (not appending to connect core namespace * as we want to limit scope to use by internal functions for now) * @returns {Object} */ var BaseParamsStorage = /*#__PURE__*/function () { function BaseParamsStorage(moduleName) { _classCallCheck(this, BaseParamsStorage); this.key = "".concat(moduleName, "ParamsStorage::").concat(global.location.origin); } return _createClass(BaseParamsStorage, [{ key: "get", value: function get() { try { var item = global.localStorage.getItem(this.key); return item && JSON.parse(item); } catch (e) { connect.getLog().error("".concat(this.key, ":: Failed to get softphone params from local storage!")).withException(e).sendInternalLogToServer(); } return null; } }, { key: "set", value: function set(value) { try { value && global.localStorage.setItem(this.key, JSON.stringify(value)); } catch (e) { connect.getLog().error("".concat(this.key, ":: Failed to set softphone params to local storage!")).withException(e).sendInternalLogToServer(); } } }, { key: "clean", value: function clean() { global.localStorage.removeItem(this.key); } }]); }(); /** * softphoneParamsStorage module to store necessary softphone params in local storage * Used mainly for cases where embedded CCP gets refreshed. * @returns {Object} */ var SoftphoneParamsStorage = /*#__PURE__*/function (_BaseParamsStorage) { function SoftphoneParamsStorage() { _classCallCheck(this, SoftphoneParamsStorage); return _callSuper(this, SoftphoneParamsStorage, ['Softphone']); } _inherits(SoftphoneParamsStorage, _BaseParamsStorage); return _createClass(SoftphoneParamsStorage); }(BaseParamsStorage); var softphoneParamsStorage = new SoftphoneParamsStorage(); /** * ringtoneParamsStorage module to store necessary ringtone params in local storage * Used mainly for cases where embedded CCP gets refreshed. * @returns {Object} */ var RingtoneParamsStorage = /*#__PURE__*/function (_BaseParamsStorage2) { function RingtoneParamsStorage() { _classCallCheck(this, RingtoneParamsStorage); return _callSuper(this, RingtoneParamsStorage, ['Ringtone']); } _inherits(RingtoneParamsStorage, _BaseParamsStorage2); return _createClass(RingtoneParamsStorage); }(BaseParamsStorage); var ringtoneParamsStorage = new RingtoneParamsStorage(); /** * globalResiliencyParamsStorage module to store necessary global resiliency params in local storage * Used mainly for cases where embedded CCP gets refreshed. * @returns {Object} */ var GlobalResiliencyParamsStorage = /*#__PURE__*/function (_BaseParamsStorage3) { function GlobalResiliencyParamsStorage() { _classCallCheck(this, GlobalResiliencyParamsStorage); return _callSuper(this, GlobalResiliencyParamsStorage, ['GlobalResiliency']); } _inherits(GlobalResiliencyParamsStorage, _BaseParamsStorage3); return _createClass(GlobalResiliencyParamsStorage); }(BaseParamsStorage); var globalResiliencyParamsStorage = new GlobalResiliencyParamsStorage(); /**------------------------------------------------------------------------- * Returns scheme://host:port for a given url */ function sanitizeDomain(url) { var domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/ig); return domain.length ? domain[0] : ""; } /**------------------------------------------------------------------------- * Print a warning message if the Connect core is not initialized. */ connect.core.checkNotInitialized = function () { if (connect.core.initialized) { var log = connect.getLog(); log.warn("Connect core already initialized, only needs to be initialized once.").sendInternalLogToServer(); } }; /**------------------------------------------------------------------------- * DISASTER RECOVERY */ var makeAgentOffline = function makeAgentOffline(agent, callbacks) { var offlineState = agent.getAgentStates().find(function (state) { return state.type === connect.AgentStateType.OFFLINE; }); agent.setState(offlineState, callbacks); }; // Suppress Contacts function // This is used by Disaster Recovery as a safeguard to not surface incoming calls/chats to UI // var suppressContacts = function suppressContacts(isSuppressed) { connect.getLog().info("[Disaster Recovery] Signal sharedworker to set contacts suppressor to %s for instance %s.", isSuppressed, connect.core.region).sendInternalLogToServer(); connect.core.getUpstream().sendUpstream(connect.DisasterRecoveryEvents.SUPPRESS, { suppress: isSuppressed, shouldSendFailoverDownstream: false }); }; var setForceOfflineUpstream = function setForceOfflineUpstream(offline, nextActiveArn) { connect.getLog().info("[DISASTER RECOVERY] Signal sharedworker to set forceOffline to %s for instance %s.", offline, connect.core.region).sendInternalLogToServer(); connect.core.getUpstream().sendUpstream(connect.DisasterRecoveryEvents.FORCE_OFFLINE, { offline: offline, nextActiveArn: nextActiveArn }); }; // Force the instance to be offline. // If `shouldSoftFailover` has a truthy value, this will try to disconnect all non-voice contacts in progress. If a voice contact // is in progress, the contact will be allowed to complete, and the agent will be set offline once the contact is destroyed (i.e. ACW is cleared). // If there is no voice contact in progress, or if `shouldSoftFailover` is missing/untruthy, this will disconnect all contacts and set the agent offline immediately. // If any of these requests fail (i.e. the backend is down/inaccessible), the shared worker will be signaled to invoke this function again once the region recovers. var _forceOffline2 = function forceOffline(shouldSoftFailover, nextActiveArn) { var log = connect.getLog(); // if agent is still initializing, we can't get instance ID; fall back to logging the region, else getInstanceId() will throw var instanceIdentifier = connect.agent.initialized ? connect.core.getAgentDataProvider().getInstanceId() : connect.core.region; log.info("[Disaster Recovery] Attempting to force instance ".concat(instanceIdentifier, " offline using ").concat(shouldSoftFailover ? 'soft' : 'hard', " failover")).sendInternalLogToServer(); connect.agent(function (agent) { var contactClosed = 0; var contacts = agent.getContacts(); var failureEncountered = false; if (contacts.length) { var _iterator = _createForOfIteratorHelper(contacts), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var contact = _step.value; if (failureEncountered) { break; // stop after first failure to avoid triggering UI failover multiple times } else if (shouldSoftFailover && (contact.getType() === connect.ContactType.QUEUE_CALLBACK || contact.getType() === connect.ContactType.VOICE)) { log.info("[Disaster Recovery] Will wait to complete failover of instance %s until voice contact with ID %s is destroyed", connect.core.region, contact.getContactId()).sendInternalLogToServer(); connect.core.getUpstream().sendDownstream(connect.DisasterRecoveryEvents.FAILOVER_PENDING, { nextActiveArn: nextActiveArn }); contact.onDestroy(function (contact) { log.info("[Disaster Recovery] Voice contact with ID %s destroyed, continuing with failover in instance %s", contact.getContactId(), connect.core.region); _forceOffline2(true, nextActiveArn); }); } else { contact.getAgentConnection().destroy({ success: function success() { // check if all active contacts are closed if (++contactClosed === contacts.length) { setForceOfflineUpstream(false, nextActiveArn); // It's ok if we're not able to put the agent offline. // since we're suppressing the agents contacts already. makeAgentOffline(agent); log.info("[Disaster Recovery] Instance %s is now offline", connect.core.region).sendInternalLogToServer(); } }, failure: function failure(err) { log.warn("[Disaster Recovery] An error occured while attempting to force this instance to offline in region %s", connect.core.region).sendInternalLogToServer(); log.warn(err).sendInternalLogToServer(); // signal the sharedworker to call forceOffline again when network connection // has been re-established (this happens in case of network or backend failures) setForceOfflineUpstream(true, nextActiveArn); failureEncountered = true; } }); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } else { setForceOfflineUpstream(false, nextActiveArn); makeAgentOffline(agent); log.info("[Disaster Recovery] Instance %s is now offline", connect.core.region).sendInternalLogToServer(); } }); }; /** * Terminates a customviews application. * This function locates the iframe generated by agentApp.initApp for a custom view using the iframeSuffix if provided, posts a termination message to it, hides it, and then stops * the application associated with that view in the AppRegistry. Will default to terminating a customviews application with iframeId="customviews" if iframeSuffix is not provided * * @param {string} connectUrl - The URL to which the termination message is posted. * @param {string} iframeSuffix - The suffix of the customviews iframe to be terminated. * @param {TerminateCustomViewOptions} - Options around controlling the iframe's resolution behavior. */ connect.core.terminateCustomView = function (connectUrl) { var _connect$agentApp$App; var iframeSuffix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$resolveIframe = _ref.resolveIframe, resolveIframe = _ref$resolveIframe === void 0 ? true : _ref$resolveIframe, _ref$timeout = _ref.timeout, timeout = _ref$timeout === void 0 ? 5000 : _ref$timeout, _ref$hideIframe = _ref.hideIframe, hideIframe = _ref$hideIframe === void 0 ? true : _ref$hideIframe; var appName; var getIframe = function getIframe(appName, containerDOM, iframeIdSelector) { return (containerDOM === null || containerDOM === void 0 ? void 0 : containerDOM.querySelector(iframeIdSelector)) || document.getElementById(appName) || window.top.document.getElementById(appName); }; if (!iframeSuffix) { appName = "".concat(APP.GUIDES); } else { appName = "".concat(APP.GUIDES).concat(iframeSuffix); } var containerDOM = (_connect$agentApp$App = connect.agentApp.AppRegistry.get(appName)) === null || _connect$agentApp$App === void 0 ? void 0 : _connect$agentApp$App.containerDOM; var iframeIdSelector = "iframe[id='".concat(appName, "']"); var iframe = getIframe(appName, containerDOM, iframeIdSelector); if (!iframe) { console.warn('[CustomViews] terminateCustomView operation failed due to iframe not found'); return; } try { var message = { topic: 'lifecycle.terminated' }; iframe.contentWindow.postMessage(message, connectUrl); if (resolveIframe) { if (hideIframe) { iframe.style.display = 'none'; } ; console.info('[CustomViews] customviews iframe hidden for resolution during termination'); setTimeout(function () { connect.agentApp.stopApp(appName); var iframe = getIframe(appName, containerDOM, iframeIdSelector); if (!iframe) { console.info('[CustomViews] customviews application successfully stopped'); } else { console.warn('[CustomViews] customviews application did not stop successfully in terminateCustomView operation'); } }, timeout); } } catch (error) { throw new Error('[CustomViews] Error in terminateCustomView: ', error); } }; //Initiate Disaster Recovery (This should only be called from customCCP that are DR enabled) connect.core.initDisasterRecovery = function (params, _suppressContacts, _forceOffline) { var log = connect.getLog(); connect.core.region = params.region; connect.core.suppressContacts = _suppressContacts || suppressContacts; connect.core.forceOffline = _forceOffline || _forceOffline2; //Register iframe listener to set native CCP offline connect.core.getUpstream().onDownstream(connect.DisasterRecoveryEvents.SET_OFFLINE, function (data) { connect.ifMaster(connect.MasterTopics.FAILOVER, function () { connect.core.forceOffline(data && data.softFailover); }); }); // Register Event listener to force the agent to be offline in a particular region connect.core.getUpstream().onUpstream(connect.DisasterRecoveryEvents.FORCE_OFFLINE, function (data) { connect.ifMaster(connect.MasterTopics.FAILOVER, function () { connect.core.forceOffline(data && data.softFailover, data && data.nextActiveArn); }); }); connect.ifMaster(connect.MasterTopics.FAILOVER, function () { log.info("[Disaster Recovery] Initializing region %s as part of a Disaster Recovery fleet", connect.core.region).sendInternalLogToServer(); }, function () { log.info("[Disaster Recovery] %s already part of a Disaster Recovery fleet", connect.core.region).sendInternalLogToServer(); }); if (params.pollForFailover && connect.DisasterRecoveryEvents.INIT_DR_POLLING) { connect.core.getUpstream().sendUpstream(connect.DisasterRecoveryEvents.INIT_DR_POLLING, { instanceArn: params.instanceArn, otherArn: params.otherArn, authToken: params.authToken }); } else if (!params.isPrimary) { connect.core.suppressContacts(true); connect.core.forceOffline(); log.info("[Disaster Recovery] %s instance is set to stand-by", connect.core.region).sendInternalLogToServer(); } else { connect.core.suppressContacts(false); log.info("[Disaster Recovery] %s instance is set to primary", connect.core.region).sendInternalLogToServer(); } }; /**------------------------------------------------------------------------- * Basic Connect client initialization. * Should be used only by the API Shared Worker. */ connect.core.init = function (params) { connect.core.eventBus = new connect.EventBus(); connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); connect.core.initClient(params); connect.core.initAgentAppClient(params); connect.core.initTaskTemplatesClient(params); connect.core.initialized = true; }; /**------------------------------------------------------------------------- * Initialized AWS client * Should be used by Shared Worker to update AWS client with new credentials * after refreshed authentication. */ connect.core.initClient = function (params) { connect.assertNotNull(params, 'params'); var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); var region = connect.assertNotNull(params.region, 'params.region'); var endpoint = params.endpoint || null; connect.core.client = new connect.AWSClient(authToken, region, endpoint); }; /**------------------------------------------------------------------------- * Initialized AgentApp client * Should be used by Shared Worker to update AgentApp client with new credentials * after refreshed authentication. */ connect.core.initAgentAppClient = function (params) { connect.assertNotNull(params, 'params'); var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); var authCookieName = connect.assertNotNull(params.authCookieName, 'params.authCookieName'); var endpoint = connect.assertNotNull(params.agentAppEndpoint, 'params.agentAppEndpoint'); connect.core.agentAppClient = new connect.AgentAppClient(authCookieName, authToken, endpoint); }; /**------------------------------------------------------------------------- * Initialized TaskTemplates client */ connect.core.initTaskTemplatesClient = function (params) { connect.assertNotNull(params, 'params'); var endpoint = params.taskTemplatesEndpoint || params.endpoint; connect.assertNotNull(endpoint, 'taskTemplatesEndpoint'); connect.core.taskTemplatesClient = new connect.TaskTemplatesClient(endpoint); }; /**------------------------------------------------------------------------- * Uninitialize Connect. */ connect.core.terminate = function () { connect.core.client = new connect.NullClient(); connect.core.apiProxyClient = new connect.NullClient(); connect.core.agentAppClient = new connect.NullClient(); connect.core.taskTemplatesClient = new connect.NullClient(); connect.core.masterClient = new connect.NullClient(); var bus = connect.core.getEventBus(); if (bus) bus.unsubscribeAll(); connect.core.bus = new connect.EventBus(); connect.core.agentDataProvider = null; connect.core.softphoneManager = null; connect.core.upstream = null; connect.core.keepaliveManager = null; connect.storageAccess.resetStorageAccessState(); connect.agent.initialized = false; connect.core.initialized = false; }; /**------------------------------------------------------------------------- * Setup the SoftphoneManager to be initialized when the agent * is determined to have softphone enabled. */ connect.core.softphoneUserMediaStream = null; connect.core.setSoftphoneUserMediaStream = function (stream) { connect.core.softphoneUserMediaStream = stream; }; connect.core.initRingtoneEngines = function (params, _setRingerDevice) { connect.getLog().info("[Ringtone Engine] initRingtoneEngine started").withObject({ params: params }).sendInternalLogToServer(); connect.assertNotNull(params, "params"); var setRingerDeviceFunc = _setRingerDevice || setRingerDevice; var setupRingtoneEngines = function setupRingtoneEngines(ringtoneSettings) { connect.assertNotNull(ringtoneSettings, "ringtoneSettings"); connect.assertNotNull(ringtoneSettings.voice, "ringtoneSettings.voice"); connect.assertTrue(ringtoneSettings.voice.ringtoneUrl || ringtoneSettings.voice.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.voice.disabled must be true"); connect.assertNotNull(ringtoneSettings.queue_callback, "ringtoneSettings.queue_callback"); connect.assertTrue(ringtoneSettings.queue_callback.ringtoneUrl || ringtoneSettings.queue_callback.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.queue_callback.disabled must be true"); connect.core.ringtoneEngines = {}; connect.agent(function (agent) { agent.onRefresh(function () { connect.ifMaster(connect.MasterTopics.RINGTONE, function () { var isInitializedAnyEngine = false; if (!ringtoneSettings.voice.disabled && !connect.core.ringtoneEngines.voice) { connect.core.ringtoneEngines.voice = new connect.VoiceRingtoneEngine(ringtoneSettings.voice); isInitializedAnyEngine = true; connect.getLog().info("VoiceRingtoneEngine initialized.").sendInternalLogToServer(); } if (!ringtoneSettings.chat.disabled && !connect.core.ringtoneEngines.chat) { connect.core.ringtoneEngines.chat = new connect.ChatRingtoneEngine(ringtoneSettings.chat); isInitializedAnyEngine = true; connect.getLog().info("ChatRingtoneEngine initialized.").sendInternalLogToServer(); } if (!ringtoneSettings.task.disabled && !connect.core.ringtoneEngines.task) { connect.core.ringtoneEngines.task = new connect.TaskRingtoneEngine(ringtoneSettings.task); isInitializedAnyEngine = true; connect.getLog().info("TaskRingtoneEngine initialized.").sendInternalLogToServer(); } if (!ringtoneSettings.email.disabled && !connect.core.ringtoneEngines.email) { connect.core.ringtoneEngines.email = new connect.EmailRingtoneEngine(ringtoneSettings.email); isInitializedAnyEngine = true; connect.getLog().info("EmailRingtoneEngine initialized.").sendInternalLogToServer(); } if (!ringtoneSettings.queue_callback.disabled && !connect.core.ringtoneEngines.queue_callback) { connect.core.ringtoneEngines.queue_callback = new connect.QueueCallbackRingtoneEngine(ringtoneSettings.queue_callback); isInitializedAnyEngine = true; connect.getLog().info("QueueCallbackRingtoneEngine initialized.").sendInternalLogToServer(); } // Once any of the Ringtone Engines are initialized, set ringer device with latest device id from _ringerDeviceId. if (isInitializedAnyEngine && connect.core._ringerDeviceId) { setRingerDeviceFunc({ deviceId: connect.core._ringerDeviceId }); } }); }); }); handleRingerDeviceChange(); }; var mergeParams = function mergeParams(params, otherParams) { // For backwards compatibility: support pulling disabled flag and ringtoneUrl // from softphone config if it exists from downstream into the ringtone config. params.ringtone = params.ringtone || {}; params.ringtone.voice = params.ringtone.voice || {}; params.ringtone.queue_callback = params.ringtone.queue_callback || {}; params.ringtone.chat = params.ringtone.chat || { disabled: true }; params.ringtone.task = params.ringtone.task || { disabled: true }; params.ringtone.email = params.ringtone.email || { disabled: true }; if (otherParams.softphone) { if (otherParams.softphone.disableRingtone) { params.ringtone.voice.disabled = true; params.ringtone.queue_callback.disabled = true; } if (otherParams.softphone.ringtoneUrl) { params.ringtone.voice.ringtoneUrl = otherParams.softphone.ringtoneUrl; params.ringtone.queue_callback.ringtoneUrl = otherParams.softphone.ringtoneUrl; } } if (otherParams.chat) { if (otherParams.chat.disableRingtone) { params.ringtone.chat.disabled = true; } if (otherParams.chat.ringtoneUrl) { params.ringtone.chat.ringtoneUrl = otherParams.chat.ringtoneUrl; } } if (otherParams.task) { if (otherParams.task.disableRingtone) { params.ringtone.task.disabled = true; } if (otherParams.task.ringtoneUrl) { params.ringtone.task.ringtoneUrl = otherParams.task.ringtoneUrl; } } if (otherParams.email) { if (otherParams.email.disableRingtone) { params.ringtone.email.disabled = true; } if (otherParams.email.ringtoneUrl) { params.ringtone.email.ringtoneUrl = otherParams.email.ringtoneUrl; } } // Merge in ringtone settings from downstream. if (otherParams.ringtone) { params.ringtone.voice = connect.merge(params.ringtone.voice, otherParams.ringtone.voice || {}); params.ringtone.queue_callback = connect.merge(params.ringtone.queue_callback, otherParams.ringtone.voice || {}); params.ringtone.chat = connect.merge(params.ringtone.chat, otherParams.ringtone.chat || {}); params.ringtone.task = connect.merge(params.ringtone.task, otherParams.ringtone.task || {}); params.ringtone.email = connect.merge(params.ringtone.email, otherParams.ringtone.email || {}); } }; // Merge params from params.softphone and params.chat and params.task into params.ringtone // for embedded and non-embedded use cases so that defaults are picked up. mergeParams(params, params); /** * If the window is iFramed, then we need to wait for a CONFIGURE message * from downstream, before we initialize the ringtone engine. * All other use cases don't wait for the CONFIGURE message. */ if (connect.isFramed()) { var configureMessageTimer; // used for re-initializing the ringtone engine var bus = connect.core.getEventBus(); // CONFIGURE handler triggers ringtone engine initialization // this event is propagated by initCCP call from the end customer bus.subscribe(connect.EventType.CONFIGURE, function (data) { global.clearTimeout(configureMessageTimer); // we don't need to re-init ringtone engine as we recieved configure event connect.getLog().info("[Ringtone Engine] Configure event handler executed").sendInternalLogToServer(); this.unsubscribe(); // Merge all params from data into params for any overridden // values in either legacy "softphone" or "ringtone" settings. mergeParams(params, data); // overwrite/store ringtone params on a configure event ringtoneParamsStorage.set(params.ringtone); setupRingtoneEngines(params.ringtone); }); /** * This is the case where CCP is just refreshed after it gets initialized via initCCP * This snippet needs at least one initCCP invocation which sets the params to the store * and waits for CCP to load succesfully to apply the same to setup ringtone engine */ var ringtoneParamsFromLocalStorage = ringtoneParamsStorage.get(); if (ringtoneParamsFromLocalStorage) { connect.core.getUpstream().onUpstream(connect.EventType.ACKNOWLEDGE, function (args) { // only care about shared worker ACK which indicates CCP successfull load var ackFromSharedWorker = args && args.id; if (ackFromSharedWorker) { connect.getLog().info("[RingtoneEngine] Embedded CCP is refreshed successfully and waiting for configure Message handler to execute").sendInternalLogToServer(); this.unsubscribe(); configureMessageTimer = global.setTimeout(function () { connect.getLog().info("[RingtoneEngine] Embedded CCP is refreshed without configure message & Initializing setupRingtoneEngines (Ringtone Engine) from localStorage ringtone params. ").withObject({ ringtone: ringtoneParamsFromLocalStorage }).sendInternalLogToServer(); setupRingtoneEngines(ringtoneParamsFromLocalStorage); // 100 ms is from the time it takes to execute few lines of JS code to trigger the configure event (this is done in initCCP) // which is in fraction of milisecond. so to be on the safer side we are keeping it to be 100 // this number is pulled from performance.now() calculations. }, 100); } }); } } else { setupRingtoneEngines(params.ringtone); } }; var handleRingerDeviceChange = function handleRingerDeviceChange() { var bus = connect.core.getEventBus(); bus.subscribe(connect.ConfigurationEvents.SET_RINGER_DEVICE, setRingerDevice); }; var setRingerDevice = function setRingerDevice() { var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var deviceId = data.deviceId || ''; connect.getLog().info("[Audio Device Settings] Attempting to set ringer device ".concat(deviceId)).sendInternalLogToServer(); if (connect.keys(connect.core.ringtoneEngines).length === 0) { connect.getLog().info("[Audio Device Settings] setRingerDevice called before ringtone engine is initialized").sendInternalLogToServer(); if (deviceId) { connect.core._ringerDeviceId = deviceId; connect.getLog().warn("[Audio Device Settings] stored device Id for later use, once ringtone engine is up.").sendInternalLogToServer(); connect.publishMetric({ name: CSM_SET_RINGER_DEVICE_BEFORE_INIT, data: { count: 1 } }); } return; } if (!deviceId) { connect.getLog().warn("[Audio Device Settings] Setting ringer device cancelled due to missing deviceId").sendInternalLogToServer(); return; } var _loop = function _loop(ringtoneType) { connect.core.ringtoneEngines[ringtoneType].setOutputDevice(deviceId).then(function (res) { connect.getLog().info("[Audio Device Settings] ringtoneType ".concat(ringtoneType, " successfully set to deviceid ").concat(res)).sendInternalLogToServer(); })["catch"](function (err) { connect.getLog().error(err); }); }; for (var ringtoneType in connect.core.ringtoneEngines) { _loop(ringtoneType); } connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, data: { deviceId: deviceId } }); }; connect.core.initSoftphoneManager = function (paramsIn) { var params = paramsIn || {}; connect.getLog().info("[Softphone Manager] initSoftphoneManager started").sendInternalLogToServer(); var competeForMasterOnAgentUpdate = function competeForMasterOnAgentUpdate(softphoneParamsIn) { var softphoneParams = connect.merge(params.softphone || {}, softphoneParamsIn); connect.getLog().info("[Softphone Manager] competeForMasterOnAgentUpdate executed").withObject({ softphoneParams: softphoneParams }).sendInternalLogToServer(); connect.agent(function (agent) { if (!agent.getChannelConcurrency(connect.ChannelType.VOICE)) { return; } if (agent.isSoftphoneEnabled()) { // get softphonePersostentConnection from agent configuration for softphone persistent connection softphoneParams.isSoftphonePersistentConnectionEnabled = agent.getConfiguration().softphonePersistentConnection; } agent.onRefresh(function () { var sub = this; connect.getLog().info("[Softphone Manager] agent refresh handler executed").sendInternalLogToServer(); connect.ifMaster(connect.MasterTopics.SOFTPHONE, function () { connect.getLog().info("[Softphone Manager] confirmed as softphone master topic").sendInternalLogToServer(); if (!connect.core.softphoneManager && agent.isSoftphoneEnabled()) { // Become master to send logs, since we need logs from softphone tab. connect.core.softphoneManager = new connect.SoftphoneManager(softphoneParams); sub.unsubscribe(); } }); }); }); }; /** * If the window is framed and if it's the CCP app then we need to wait for a CONFIGURE message from downstream before we initialize softphone manager. * All medialess softphone initialization cases goes to else check and doesn't wait for CONFIGURE message */ if (connect.isFramed() && connect.isCCP()) { var configureMessageTimer; // used for re-initing the softphone manager var bus = connect.core.getEventBus(); // Configure handler triggers the softphone manager initiation. // This event is propagted by initCCP call from the end customers bus.subscribe(connect.EventType.CONFIGURE, function (data) { global.clearTimeout(configureMessageTimer); // we don't need to re-init softphone manager as we recieved configure event connect.getLog().info("[Softphone Manager] Configure event handler executed").withObject({ data: data }).sendInternalLogToServer(); // always overwrite/store the softphone params value if there is a configure event softphoneParamsStorage.set(data.softphone); if (data.softphone && data.softphone.allowFramedSoftphone) { this.unsubscribe(); competeForMasterOnAgentUpdate(data.softphone); } setupEventListenersForMultiTabUseInFirefox(data.softphone); }); /** * This is the case where CCP is just refreshed after it gets initilaized via initCCP * This snippet needs at least one initCCP invocation which sets the params to the store * and waits for CCP to load successfully to apply the same to init Softphone manager */ var softphoneParamsFromLocalStorage = softphoneParamsStorage.get(); if (softphoneParamsFromLocalStorage) { connect.core.getUpstream().onUpstream(connect.EventType.ACKNOWLEDGE, function (args) { // only care about shared worker ACK which indicates CCP successfull load var ackFromSharedWorker = args && args.id; if (ackFromSharedWorker) { connect.getLog().info("[Softphone Manager] Embedded CCP is refreshed successfully and waiting for configure Message handler to execute").sendInternalLogToServer(); this.unsubscribe(); configureMessageTimer = global.setTimeout(function () { connect.getLog().info("[Softphone Manager] Embedded CCP is refreshed without configure message handler execution").withObject({ softphoneParamsFromLocalStorage: softphoneParamsFromLocalStorage }).sendInternalLogToServer(); connect.publishMetric({ name: "EmbeddedCCPRefreshedWithoutInitCCP", data: { count: 1 } }); setupEventListenersForMultiTabUseInFirefox(softphoneParamsFromLocalStorage); if (softphoneParamsFromLocalStorage.allowFramedSoftphone) { connect.getLog().info("[Softphone Manager] Embedded CCP is refreshed & Initializing competeForMasterOnAgentUpdate (Softphone manager) from localStorage softphone params").sendInternalLogToServer(); competeForMasterOnAgentUpdate(softphoneParamsFromLocalStorage); } // 100 ms is from the time it takes to execute few lines of JS code to trigger the configure event (this is done in initCCP) // which is in fraction of milisecond. so to be on the safer side we are keeping it to be 100 // this number is pulled from performance.now() calculations. }, 100); } }); } } else { competeForMasterOnAgentUpdate(params); setupEventListenersForMultiTabUseInFirefox(params); } connect.agent(function (agent) { // Sync mute across all tabs if (agent.isSoftphoneEnabled() && agent.getChannelConcurrency(connect.ChannelType.VOICE)) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.MUTE }); } }); function setupEventListenersForMultiTabUseInFirefox(softphoneParamsIn) { var softphoneParams = connect.merge(params.softphone || {}, softphoneParamsIn); // keep the softphone params for external use connect.core.softphoneParams = softphoneParams; if (connect.isFirefoxBrowser()) { // In Firefox, when a tab takes over another tab's softphone primary, // the previous primary tab should delete sofphone manager and stop microphone connect.core.getUpstream().onUpstream(connect.EventType.MASTER_RESPONSE, function (res) { if (res.data && res.data.topic === connect.MasterTopics.SOFTPHONE && res.data.takeOver && res.data.masterId !== connect.core.portStreamId) { if (connect.core.softphoneManager) { connect.core.softphoneManager.onInitContactSub.unsubscribe(); delete connect.core.softphoneManager; } } }); // In Firefox, when multiple tabs are open, // webrtc session is not started until READY_TO_START_SESSION event is triggered connect.core.getEventBus().subscribe(connect.ConnectionEvents.READY_TO_START_SESSION, function () { connect.ifMaster(connect.MasterTopics.SOFTPHONE, function () { if (connect.core.softphoneManager) { connect.core.softphoneManager.startSession(); } }, function () { connect.becomeMaster(connect.MasterTopics.SOFTPHONE, function () { connect.agent(function (agent) { if (!connect.core.softphoneManager && agent.isSoftphoneEnabled()) { connect.becomeMaster(connect.MasterTopics.SEND_LOGS); connect.core.softphoneManager = new connect.SoftphoneManager(softphoneParams); connect.core.softphoneManager.startSession(); } }); }); }); }); // handling outbound-call and auto-accept cases for pending session connect.contact(function (c) { connect.agent(function (agent) { c.onRefresh(function (contact) { if (connect.hasOtherConnectedCCPs() && document.visibilityState === 'visible' && (contact.getStatus().type === connect.ContactStatusType.CONNECTING || contact.getStatus().type === connect.ContactStatusType.INCOMING)) { var isOutBoundCall = contact.isSoftphoneCall() && !contact.isInbound(); var isAutoAcceptEnabled = contact.isSoftphoneCall() && agent.getConfiguration().softphoneAutoAccept; var isQueuedCallback = contact.getType() === connect.ContactType.QUEUE_CALLBACK; if (isOutBoundCall || isAutoAcceptEnabled || isQueuedCallback) { connect.core.triggerReadyToStartSessionEvent(); } } }); }); }); } } }; // trigger READY_TO_START_SESSION event in a context with Softphone Manager // internal use only connect.core.triggerReadyToStartSessionEvent = function () { var allowFramedSoftphone = connect.core.softphoneParams && connect.core.softphoneParams.allowFramedSoftphone; if (connect.isCCP()) { if (allowFramedSoftphone) { // the event is triggered in this iframed CCP context connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); } else { if (connect.isFramed()) { // if this is an iframed CCP, the event is send to downstream (CRM) connect.core.getUpstream().sendDownstream(connect.ConnectionEvents.READY_TO_START_SESSION); } else { // if this is a standalone CCP, trigger this event in this CCP context connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); } } } else { if (allowFramedSoftphone) { // the event is send to the upstream (iframed CCP) connect.core.getUpstream().sendUpstream(connect.ConnectionEvents.READY_TO_START_SESSION); } else { // the event is triggered in this CRM context connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); } } }; connect.core.initPageOptions = function (params) { connect.assertNotNull(params, "params"); if (connect.isFramed()) { // If the CCP is in a frame, wait for configuration from downstream. var bus = connect.core.getEventBus(); bus.subscribe(connect.EventType.CONFIGURE, function (data) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.CONFIGURE, data: data }); }); // Listen for iframe media devices request from CRM bus.subscribe(connect.EventType.MEDIA_DEVICE_REQUEST, function () { function sendDevices(devices) { connect.core.getUpstream().sendDownstream(connect.EventType.MEDIA_DEVICE_RESPONSE, devices); } if (navigator && navigator.mediaDevices) { navigator.mediaDevices.enumerateDevices().then(function (devicesIn) { devices = devicesIn || []; devices = devices.map(function (d) { return d.toJSON(); }); sendDevices(devices); })["catch"](function (err) { sendDevices({ error: err.message }); }); } else { sendDevices({ error: "No navigator or navigator.mediaDevices object found" }); } }); } }; //only used in CCP to initialize everything needed for Api Proxy connect.core.initApiProxyService = function () { connect.core.apiProxyClient = new connect.ApiProxyClient(); if (connect.isFramed()) { connect.core.handleApiProxyRequest = function (request) { if (!(request !== null && request !== void 0 && request.method)) return; var successCB = function successCB(data) { var response = { data: data, requestId: request.requestId }; connect.core.getUpstream().sendDownstream(connect.EventType.API_RESPONSE, response); }; var failureCB = function failureCB(err) { var response = { err: err, requestId: request.requestId }; connect.core.getUpstream().sendDownstream(connect.EventType.API_RESPONSE, response); }; var client = connect.core.getApiProxyClient(); client.call(request.method, request.params, { success: successCB, failure: failureCB }); }; } }; /**------------------------------------------------------------------------- * Get the list of media devices from iframed CCP * Timeout for the request is passed on an optional argument * The default timeout is 1000ms */ connect.core.getFrameMediaDevices = function (timeoutIn) { var sub = null; var timeout = timeoutIn || 1000; var timeoutPromise = new Promise(function (resolve, reject) { setTimeout(function () { reject(new Error("Timeout exceeded")); }, timeout); }); var mediaDevicesPromise = new Promise(function (resolve, reject) { if (connect.isCCP()) { if (navigator && navigator.mediaDevices) { navigator.mediaDevices.enumerateDevices().then(function (devicesIn) { devices = devicesIn || []; devices = devices.map(function (d) { return d.toJSON(); }); resolve(devices); }); } else { reject(new Error("No navigator or navigator.mediaDevices object found")); } } else { var bus = connect.core.getEventBus(); sub = bus.subscribe(connect.EventType.MEDIA_DEVICE_RESPONSE, function (data) { if (data.error) { reject(new Error(data.error)); } else { resolve(data); } }); connect.core.getUpstream().sendUpstream(connect.EventType.MEDIA_DEVICE_REQUEST); } }); return Promise.race([mediaDevicesPromise, timeoutPromise])["finally"](function () { if (sub) { sub.unsubscribe(); } }); }; //Internal use only. connect.core.authorize = function (endpoint) { var options = { credentials: 'include' }; var authorizeEndpoint = endpoint; if (!authorizeEndpoint) { authorizeEndpoint = connect.core.isLegacyDomain() ? LEGACY_AUTHORIZE_ENDPOINT : AUTHORIZE_ENDPOINT; } return connect.fetch(authorizeEndpoint, options, AUTHORIZE_RETRY_INTERVAL, AUTHORIZE_MAX_RETRY); }; /** * @deprecated * This used to be used internally, but is no longer needed. */ connect.core.verifyDomainAccess = function (authToken, endpoint) { connect.getLog().warn("This API will be deprecated in the next major version release"); if (!connect.isFramed()) { return Promise.resolve(); } var options = { headers: { 'X-Amz-Bearer': authToken } }; var whitelistedOriginsEndpoint = null; if (endpoint) { whitelistedOriginsEndpoint = endpoint; } else { whitelistedOriginsEndpoint = connect.core.isLegacyDomain() ? LEGACY_WHITELISTED_ORIGINS_ENDPOINT : WHITELISTED_ORIGINS_ENDPOINT; } return connect.fetch(whitelistedOriginsEndpoint, options, WHITELISTED_ORIGINS_RETRY_INTERVAL, WHITELISTED_ORIGINS_MAX_RETRY).then(function (response) { var topDomain = sanitizeDomain(window.document.referrer); var isAllowed = response.whitelistedOrigins.some(function (origin) { return topDomain === sanitizeDomain(origin); }); return isAllowed ? Promise.resolve() : Promise.reject(); }); }; /**------------------------------------------------------------------------- * Returns true if this window's href is on the legacy connect domain. * Only useful for internal use. */ connect.core.isLegacyDomain = function (url) { url = url || window.location.href; return url.includes('.awsapps.com'); }; /**------------------------------------------------------------------------- * Initializes Connect by creating or connecting to the API Shared Worker. * Used only by the CCP */ connect.core.initSharedWorker = function (params) { connect.core.checkNotInitialized(); if (connect.core.initialized) { return; } connect.assertNotNull(params, 'params'); var sharedWorkerUrl = connect.assertNotNull(params.sharedWorkerUrl, 'params.sharedWorkerUrl'); var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); var refreshToken = connect.assertNotNull(params.refreshToken, 'params.refreshToken'); var authTokenExpiration = connect.assertNotNull(params.authTokenExpiration, 'params.authTokenExpiration'); var region = connect.assertNotNull(params.region, 'params.region'); var endpoint = params.endpoint || null; var authorizeEndpoint = params.authorizeEndpoint; if (!authorizeEndpoint) { authorizeEndpoint = connect.core.isLegacyDomain() ? LEGACY_AUTHORIZE_ENDPOINT : AUTHORIZE_ENDPOINT; } var agentAppEndpoint = params.agentAppEndpoint || null; var taskTemplatesEndpoint = params.taskTemplatesEndpoint || null; var authCookieName = params.authCookieName || null; try { // Initialize the event bus and agent data providers. connect.core.eventBus = new connect.EventBus({ logEvents: true }); connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); connect.core.mediaFactory = new connect.MediaFactory(params); // Create the shared worker and upstream conduit. var worker = new SharedWorker(sharedWorkerUrl, "ConnectSharedWorker"); var conduit = new connect.Conduit("ConnectSharedWorkerConduit", new connect.PortStream(worker.port), new connect.WindowIOStream(window, parent)); // Set the global upstream conduit for external use. connect.core.upstream = conduit; connect.core.webSocketProvider = new WebSocketProvider(); // Close our port to the shared worker before the window closes. global.onunload = function () { conduit.sendUpstream(connect.EventType.CLOSE); worker.port.close(); }; connect.getLog().scheduleUpstreamLogPush(conduit); connect.getLog().scheduleDownstreamClientSideLogsPush(); // Bridge all messages from "upstream" into the event bus conduit.onAllUpstream(connect.core.getEventBus().bridge()); // Pass all messages from "upstream" to "downstream" conduit.onAllUpstream(conduit.passDownstream()); if (connect.isFramed()) { // Bridge all messages from "downstream" into the event bus conduit.onAllDownstream(connect.core.getEventBus().bridge()); // Pass all messages from "downstream" to "upstream" (except API Proxy Requests) conduit.onAllDownstream(function (data, eventName) { if (eventName === connect.EventType.API_REQUEST && connect.containsValue(connect.ApiProxyClientMethods, data === null || data === void 0 ? void 0 : data.method)) { connect.core.handleApiProxyRequest(data); } else conduit.passUpstream()(data, eventName); }); } // Send configuration up to the shared worker. conduit.sendUpstream(connect.EventType.CONFIGURE, { authToken: authToken, authTokenExpiration: authTokenExpiration, endpoint: endpoint, refreshToken: refreshToken, region: region, authorizeEndpoint: authorizeEndpoint, agentAppEndpoint: agentAppEndpoint, taskTemplatesEndpoint: taskTemplatesEndpoint, authCookieName: authCookieName, longPollingOptions: params.longPollingOptions || undefined }); conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { connect.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(); connect.core.initialized = true; connect.core._setTabId(); connect.core.portStreamId = data.id; this.unsubscribe(); }); // Add all upstream log entries to our own logger. conduit.onUpstream(connect.EventType.LOG, function (logEntry) { if (logEntry.loggerId !== connect.getLog().getLoggerId()) { connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); } }); // Get worker logs conduit.onUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, function (logEntry) { connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(logEntry)); }); // Get outer context logs conduit.onDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, function (logs) { if (connect.isFramed() && Array.isArray(logs)) { logs.forEach(function (log) { connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(log)); }); } }); // Get log from outer context conduit.onDownstream(connect.EventType.LOG, function (log) { if (connect.isFramed() && log.loggerId !== connect.getLog().getLoggerId()) { connect.getLog().addLogEntry(connect.LogEntry.fromObject(log)); } }); connect.core.onAuthFail(connect.hitch(connect.core, connect.core._handleAuthFail, params.loginEndpoint || null, authorizeEndpoint)); // For auth retry logic on 401s. connect.core.onAuthorizeSuccess(connect.hitch(connect.core, connect.core._handleAuthorizeSuccess)); // For auth retry logic on 401s. connect.getLog().info("User Agent: " + navigator.userAgent).sendInternalLogToServer(); connect.getLog().info("isCCPv2: " + true).sendInternalLogToServer(); connect.getLog().info("isFramed: " + connect.isFramed()).sendInternalLogToServer(); connect.core.upstream.onDownstream(connect.EventType.OUTER_CONTEXT_INFO, function (data) { var streamsVersion = data.streamsVersion || null; connect.getLog().info("StreamsJS Version: " + streamsVersion).sendInternalLogToServer(); connect.outerContextStreamsVersion = streamsVersion; }); conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { connect.getLog().info("Number of connected CCPs updated: " + data.length).sendInternalLogToServer(); connect.numberOfConnectedCCPs = data.length; if (data[connect.core.tabId] && !isNaN(data[connect.core.tabId].length)) { if (connect.numberOfConnectedCCPsInThisTab !== data[connect.core.tabId].length) { connect.numberOfConnectedCCPsInThisTab = data[connect.core.tabId].length; if (connect.numberOfConnectedCCPsInThisTab > 1) { connect.getLog().warn("There are " + connect.numberOfConnectedCCPsInThisTab + " connected CCPs in this tab. Please adjust your implementation to avoid complications. If you are embedding CCP, please do so exclusively with initCCP. InitCCP will not let you embed more than one CCP.").sendInternalLogToServer(); } connect.publishMetric({ name: CONNECTED_CCPS_SINGLE_TAB, data: { count: connect.numberOfConnectedCCPsInThisTab } }); } } if (data.tabId && data.streamsTabsAcrossBrowser) { connect.ifMaster(connect.MasterTopics.METRICS, function () { return connect.agent(function () { return connect.publishMetric({ name: CCP_TABS_ACROSS_BROWSER_COUNT, data: { tabId: data.tabId, count: data.streamsTabsAcrossBrowser } }); }); }); } }); connect.core.client = new connect.UpstreamConduitClient(conduit); connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); // Pass the TERMINATE request upstream to the shared worker. connect.core.getEventBus().subscribe(connect.EventType.TERMINATE, conduit.passUpstream()); // Refresh the page when we receive the TERMINATED response from the // shared worker. connect.core.getEventBus().subscribe(connect.EventType.TERMINATED, function () { window.location.reload(true); }); worker.port.start(); conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { if (data && data.domainId) { connect.core.voiceIdDomainId = data.domainId; } }); // try fetching voiceId's domainId once the agent is initialized connect.agent(function () { var voiceId = new connect.VoiceId(); voiceId.getDomainId().then(function (domainId) { connect.getLog().info("voiceId domainId successfully fetched at agent initialization: " + domainId).sendInternalLogToServer(); })["catch"](function (err) { connect.getLog().info("voiceId domainId not fetched at agent initialization").withObject({ err: err }).sendInternalLogToServer(); }); }); // Attempt to get permission to show notifications. var nm = connect.core.getNotificationManager(); nm.requestPermission(); conduit.onDownstream(connect.DisasterRecoveryEvents.INIT_DISASTER_RECOVERY, function (params) { connect.core.initDisasterRecovery(params); }); } catch (e) { connect.getLog().error("Failed to initialize the API shared worker, we're dead!").withException(e).sendInternalLogToServer(); } }; connect.core._setTabId = function () { try { connect.core.tabId = window.sessionStorage.getItem(connect.SessionStorageKeys.TAB_ID); if (!connect.core.tabId) { connect.core.tabId = connect.randomId(); window.sessionStorage.setItem(connect.SessionStorageKeys.TAB_ID, connect.core.tabId); } connect.core.upstream.sendUpstream(connect.EventType.TAB_ID, { tabId: connect.core.tabId }); } catch (e) { connect.getLog().error("[Tab Id] There was an issue setting the tab Id").withException(e).sendInternalLogToServer(); } }; connect.core.setupAuthenticationEventHandlers = function (params, containerDiv, conduit) { var _params$loginOptions; connect.core.loginAckTimeoutSub = connect.core.getEventBus().subscribe(connect.EventType.ACK_TIMEOUT, function () { connect.getLog().warn("ACK_TIMEOUT occurred. Attempting to authenticate.").sendInternalLogToServer(); connect.core.authenticate(params, containerDiv, conduit); }); if (!((_params$loginOptions = params.loginOptions) !== null && _params$loginOptions !== void 0 && _params$loginOptions.disableAuthPopupAfterLogout)) { connect.core.getEventBus().subscribe(connect.EventType.TERMINATED, function () { connect.getLog().warn("TERMINATED occurred. Attempting to authenticate.").sendInternalLogToServer(); var delay = params.ccpAckTimeout || CCP_ACK_TIMEOUT; // Adding a small delay to avoid immediately logging the agent back in setTimeout(function () { connect.core.authenticate(params, containerDiv, conduit); }, delay); }); connect.core.getEventBus().subscribe(connect.EventType.AUTH_FAIL, function () { connect.getLog().warn("AUTH_FAIL occurred. Attempting to authenticate.").sendInternalLogToServer(); var delay = params.ccpAckTimeout || CCP_ACK_TIMEOUT; // Adding a small delay to avoid immediately logging the agent back in setTimeout(function () { connect.core.authenticate(params, containerDiv, conduit); }, delay); }); } }; /**------------------------------------------------------------------------- * Initializes Connect by creating or connecting to the API Shared Worker. * Initializes Connect by loading the CCP in an iframe and connecting to it. */ connect.core.initCCP = function (containerDiv, paramsIn) { var _params$softphone, _params3; connect.core.checkNotInitialized(); if (connect.core.initialized) { return; } connect.getLog().info("Iframe initialization started").sendInternalLogToServer(); var initStartTime = Date.now(); // Check if CCP iframe has already been initialized through initCCP try { if (connect.core._getCCPIframe()) { connect.getLog().error('Attempted to call initCCP when an iframe generated by initCCP already exists').sendInternalLogToServer(); return; } } catch (e) { connect.getLog().error('Error while checking if initCCP has already been called').withException(e).sendInternalLogToServer(); } var params = {}; var existingProvider = undefined; var providerPlugins = undefined; // For backwards compatibility, when instead of taking a params object // as input we only accepted ccpUrl. if (typeof paramsIn === 'string') { params.ccpUrl = paramsIn; } else { params = paramsIn; if (params.provider) { // Provider must be removed from params as params are sent to CCP // and provider is not cloneable existingProvider = params.provider; delete params.provider; } if (params.plugins) { // Plugins must be removed from params as params are sent to CCP // and plugins are not cloneable providerPlugins = params.plugins; delete params.plugins; } } connect.initCCPParams = params; connect.containerDiv = containerDiv; connect.assertNotNull(containerDiv, 'containerDiv'); connect.assertNotNull(params.ccpUrl, 'params.ccpUrl'); // Add SDK via AmazonConnectStreamsSite if (!existingProvider) { try { var _params, _params2; var _require = __webpack_require__(275), AmazonConnectStreamsSite = _require.AmazonConnectStreamsSite, AmazonConnectGRStreamsSite = _require.AmazonConnectGRStreamsSite; var instanceUrl = new URL(params.ccpUrl).origin; if (((_params = params) === null || _params === void 0 ? void 0 : _params.enableGlobalResiliency) === true && (_params2 = params) !== null && _params2 !== void 0 && _params2.secondaryCCPUrl) { var config = { primaryInstanceUrl: instanceUrl, secondaryInstanceUrl: new URL(params.secondaryCCPUrl).origin }; connect.core._amazonConnectProviderData = _objectSpread(_objectSpread({}, AmazonConnectGRStreamsSite.init(config)), {}, { isStreamsProvider: true, isACGREnabled: true }); connect.getLog().info("[GR] Created AmazonConnectGRStreamsSite").withObject({ providerId: connect.core._amazonConnectProviderData.provider.id }).sendInternalLogToServer(); } else { var config = { instanceUrl: instanceUrl }; connect.core._amazonConnectProviderData = _objectSpread(_objectSpread({}, AmazonConnectStreamsSite.init(config)), {}, { isStreamsProvider: true }); connect.getLog().info("Created AmazonConnectStreamsSite").withObject({ providerId: connect.core._amazonConnectProviderData.provider.id }).sendInternalLogToServer(); } } catch (e) { connect.getLog().error("Error when setting up AmazonConnectStreamsSite").withException(e).sendInternalLogToServer(); } } else { try { connect.core._amazonConnectProviderData = { provider: existingProvider, isStreamsProvider: false }; connect.getLog().info("Using AmazonConnectProvider from params").withObject({ providerId: connect.core._amazonConnectProviderData.provider.id, providerType: connect.core._amazonConnectProviderData.provider.constructor.name }).sendInternalLogToServer(); } catch (e) { connect.getLog().error("Error when setting up AmazonConnectProvider from params").withException(e).sendInternalLogToServer(); } } if (providerPlugins) { try { providerPlugins = Array.isArray(providerPlugins) ? providerPlugins : [providerPlugins]; // Applying plugins providerPlugins.reduce(function (result, applyPlugin) { return applyPlugin(result); }, Object.getPrototypeOf(connect.core._amazonConnectProviderData.provider)); } catch (e) { connect.getLog().error("Error when setting plugins for provider").withException(e).sendInternalLogToServer(); } } connect.core.iframeStyle = params.style || "width: 100%; height: 100%;"; // Clean up the Softphone and Ringtone params store to make sure we always pull the latest params if (!((_params$softphone = params.softphone) !== null && _params$softphone !== void 0 && _params$softphone.disableStoringParamsInLocalStorage)) { softphoneParamsStorage.clean(); ringtoneParamsStorage.clean(); } // This is emitted further below as event bus and customer event callbacks are not created yet. var acgrParamError = null; if (((_params3 = params) === null || _params3 === void 0 ? void 0 : _params3.enableGlobalResiliency) === true) { var _params4, _params5, _params6, _params7; if (typeof ((_params4 = params) === null || _params4 === void 0 ? void 0 : _params4.secondaryCCPUrl) !== 'string' || ((_params5 = params) === null || _params5 === void 0 ? void 0 : _params5.secondaryCCPUrl) === '') { var _log = "enableGlobalResiliency flag was enabled, but secondaryCCPUrl was not provided. Global Resiliency will not be enabled"; connect.getLog().error(_log).sendInternalLogToServer(); acgrParamError = { event: connect.GlobalResiliencyEvents.CONFIGURE_ERROR, data: new Error(_log) }; } else if (typeof ((_params6 = params) === null || _params6 === void 0 ? void 0 : _params6.loginUrl) !== 'string' || ((_params7 = params) === null || _params7 === void 0 ? void 0 : _params7.loginUrl) === '') { var _log2 = "enableGlobalResiliency flag was enabled, but loginUrl was not provided. Global Resiliency will not be enabled"; connect.getLog().error(_log2).sendInternalLogToServer(); acgrParamError = { event: connect.GlobalResiliencyEvents.CONFIGURE_ERROR, data: new Error(_log2) }; } else { connect.getLog().info("enableGlobalResiliency flag was enabled and secondaryCCPUrl and loginUrl was provided. Global Resiliency will be enabled").sendInternalLogToServer(); return connect.globalResiliency.initGRCCP(containerDiv, paramsIn); } } // Placed after ACGR init since StorageAccess does not work with ACGR connect.storageAccess.init(params.ccpUrl, containerDiv, params.storageAccess || {}); var iframe = connect.core._createCCPIframe(containerDiv, params); // Build the upstream conduit communicating with the CCP iframe. var conduit = new connect.IFrameConduit(params.ccpUrl, window, iframe); // Set the global upstream conduit for external use. connect.core.upstream = conduit; // Initialize the event bus and agent data providers. // NOTE: Setting logEvents here to FALSE in order to avoid duplicating // events which are logged in CCP. connect.core.eventBus = new connect.EventBus({ logEvents: false }); if (connect.storageAccess.canRequest()) { // Create the Iframe and load the RSA banner and append it to the container div. connect.storageAccess.setupRequestHandlers({ onGrant: setupInitCCP }); } else { setupInitCCP(); } function setupInitCCP() { connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); connect.core.mediaFactory = new connect.MediaFactory(params); // Let CCP know if iframe is visible connect.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(iframe, conduit); // Init webSocketProvider connect.core.webSocketProvider = new WebSocketProvider(); conduit.onAllUpstream(connect.core.getEventBus().bridge()); // Initialize the keepalive manager. connect.core.keepaliveManager = new KeepaliveManager(conduit, connect.core.getEventBus(), params.ccpSynTimeout || CCP_SYN_TIMEOUT, params.ccpAckTimeout || CCP_ACK_TIMEOUT); connect.core.iframeRefreshTimeout = null; // Allow 5 sec (default) before receiving the first ACK from the CCP. connect.core.ccpLoadTimeoutInstance = global.setTimeout(function () { connect.core.ccpLoadTimeoutInstance = null; connect.core.getEventBus().trigger(connect.EventType.ACK_TIMEOUT); connect.getLog().info("CCP LoadTimeout triggered").sendInternalLogToServer(); }, params.ccpLoadTimeout || CCP_LOAD_TIMEOUT); connect.getLog().scheduleUpstreamOuterContextCCPLogsPush(conduit); connect.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(conduit); // Once we receive the first ACK, setup our upstream API client and establish // the SYN/ACK refresh flow. conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { var _params$loginOptions2; connect.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(); connect.core.client = new connect.UpstreamConduitClient(conduit); connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); connect.core.portStreamId = data.id; if (connect.core.loginAckTimeoutSub && (_params$loginOptions2 = params.loginOptions) !== null && _params$loginOptions2 !== void 0 && _params$loginOptions2.disableAuthPopupAfterLogout) { connect.core.loginAckTimeoutSub.unsubscribe(); connect.core.loginAckTimeoutSub = null; connect.getLog().info("ACK_TIMEOUT subscription unsubscribed after receiving ACKNOWLEDGE due to disableAuthPopupAfterLogout").sendInternalLogToServer(); } connect.core.sendConfigure(params, conduit, false); connect.core.listenForConfigureRequest(params, conduit, false); // failsafe for abnormal ccp refresh // If DR enabled, set this CCP instance as part of a Disaster Recovery fleet if (params.disasterRecoveryOn) { connect.core.region = params.region; connect.core.suppressContacts = suppressContacts; connect.core.forceOffline = function (data) { conduit.sendUpstream(connect.DisasterRecoveryEvents.SET_OFFLINE, data); }; conduit.sendUpstream(connect.DisasterRecoveryEvents.INIT_DISASTER_RECOVERY, params); } if (connect.core.ccpLoadTimeoutInstance) { global.clearTimeout(connect.core.ccpLoadTimeoutInstance); connect.core.ccpLoadTimeoutInstance = null; } conduit.sendUpstream(connect.EventType.OUTER_CONTEXT_INFO, { streamsVersion: connect.version }); var _ref2 = params.loginOptions || {}, enableAckTimeout = _ref2.enableAckTimeout; if (enableAckTimeout) { connect.core.keepaliveManager.enableAckTimeout(enableAckTimeout); } connect.core.keepaliveManager.start(); this.unsubscribe(); connect.core.initialized = true; connect.core.getEventBus().trigger(connect.EventType.INIT); if (acgrParamError) { connect.core.getEventBus().trigger(acgrParamError.event, acgrParamError.data); } if (initStartTime) { var initTime = Date.now() - initStartTime; var refreshAttempts = connect.core.iframeRefreshAttempt || 0; connect.getLog().info('Iframe initialization succeeded').sendInternalLogToServer(); connect.getLog().info("Iframe initialization time ".concat(initTime)).sendInternalLogToServer(); connect.getLog().info("Iframe refresh attempts ".concat(refreshAttempts)).sendInternalLogToServer(); setTimeout(function () { connect.publishMetric({ name: CSM_IFRAME_REFRESH_ATTEMPTS, data: { count: refreshAttempts } }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_SUCCESS, data: { count: 1 } }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_TIME, data: { count: initTime } }); if (params.disasterRecoveryOn) { connect.publishMetric({ name: CSM_IFRAME_REFRESH_ATTEMPTS_DR, data: { count: refreshAttempts } }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_SUCCESS_DR, data: { count: 1 } }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_TIME_DR, data: { count: initTime } }); } //to avoid metric emission after initialization initStartTime = null; }, 1000); } }); // Add any logs from the upstream to our own logger. conduit.onUpstream(connect.EventType.LOG, function (logEntry) { if (logEntry.loggerId !== connect.getLog().getLoggerId()) { connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); } }); connect.core.setupAuthenticationEventHandlers(params, containerDiv, conduit); if (params.onViewContact) { connect.core.onViewContact(params.onViewContact); } conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { connect.numberOfConnectedCCPs = data.length; }); conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { if (data && data.domainId) { connect.core.voiceIdDomainId = data.domainId; } }); connect.core.getEventBus().subscribe(connect.EventType.IFRAME_RETRIES_EXHAUSTED, function () { if (initStartTime) { var refreshAttempts = connect.core.iframeRefreshAttempt - 1; connect.getLog().info('Iframe initialization failed').sendInternalLogToServer(); connect.getLog().info("Time after iframe initialization started ".concat(Date.now() - initStartTime)).sendInternalLogToServer(); connect.getLog().info("Iframe refresh attempts ".concat(refreshAttempts)).sendInternalLogToServer(); connect.publishMetric({ name: CSM_IFRAME_REFRESH_ATTEMPTS, data: { count: refreshAttempts } }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_SUCCESS, data: { count: 0 } }); if (params.disasterRecoveryOn) { connect.publishMetric({ name: CSM_IFRAME_REFRESH_ATTEMPTS_DR, data: { count: refreshAttempts } }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_SUCCESS_DR, data: { count: 0 } }); } initStartTime = null; } }); // keep the softphone params for external use connect.core.softphoneParams = params.softphone; } ; }; connect.core._openPopupWithLock = function (loginUrl, loginOptions) { var lockName = "connect-login-popup-lock" + loginUrl; try { navigator.locks.request(lockName, { mode: 'exclusive', ifAvailable: true }, /*#__PURE__*/function () { var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(lock) { var checkPopupInterval; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (lock) { _context.next = 3; break; } connect.getLog().info("Popup already opened by another tab.").sendInternalLogToServer(); return _context.abrupt("return"); case 3: connect.getLog().info("Opening popup window with weblock.").sendInternalLogToServer(); connect.core.loginWindow = connect.core.getPopupManager().open(loginUrl, connect.MasterTopics.LOGIN_POPUP, loginOptions); connect.core._shouldHoldPopupLock = true; checkPopupInterval = setInterval(function () { var _connect$core$loginWi; if (!connect.core.loginWindow || (_connect$core$loginWi = connect.core.loginWindow) !== null && _connect$core$loginWi !== void 0 && _connect$core$loginWi.closed) { clearInterval(checkPopupInterval); connect.core._shouldHoldPopupLock = false; connect.getLog().info("Cleared check popup interval.").sendInternalLogToServer(); } }, CHECK_LOGIN_POPUP_INTERVAL_MS); // hold the lock until the popup is closed case 7: if (!connect.core._shouldHoldPopupLock) { _context.next = 12; break; } _context.next = 10; return new Promise(function (resolve) { return setTimeout(resolve, 1000); }); case 10: _context.next = 7; break; case 12: connect.getLog().info("Releasing weblock for opening login popup.").sendInternalLogToServer(); case 13: case "end": return _context.stop(); } }, _callee); })); return function (_x) { return _ref3.apply(this, arguments); }; }()); } catch (e) { connect.getLog().error("Failed to use weblock to open popup. Your browser may be out of date.").withException(e).sendInternalLogToServer(); if (!connect.core.loginWindow) { connect.core.loginWindow = connect.core.getPopupManager().open(loginUrl, connect.MasterTopics.LOGIN_POPUP, loginOptions); } } }; connect.core.onIframeRetriesExhausted = function (f) { return connect.core.getEventBus().subscribe(connect.EventType.IFRAME_RETRIES_EXHAUSTED, f); }; connect.core._refreshIframeOnTimeout = function (initCCPParams, containerDiv, timerContainer, identifier) { connect.assertNotNull(initCCPParams, 'initCCPParams'); connect.assertNotNull(containerDiv, 'containerDiv'); var obj = timerContainer || connect.core; // ccpIframeRefreshInterval is the ccpLoadTimeout passed into initCCP // if no ccpLoadTimeout is passed in, the interval is the default, which depends on if disaster recovery is on var ccpIframeRefreshInterval = initCCPParams.ccpLoadTimeout ? initCCPParams.ccpLoadTimeout : initCCPParams.disasterRecoveryOn ? CCP_DR_IFRAME_REFRESH_INTERVAL : CCP_IFRAME_REFRESH_INTERVAL; global.clearTimeout(obj.iframeRefreshTimeout); obj.iframeRefreshTimeout = global.setTimeout(function () { obj.iframeRefreshAttempt = (obj.iframeRefreshAttempt || 0) + 1; if (obj.iframeRefreshAttempt <= CCP_IFRAME_REFRESH_LIMIT) { connect.getLog().info("Refreshing the CCP IFrame for ".concat(initCCPParams.ccpUrl, " on attempt ").concat(obj.iframeRefreshAttempt)).sendInternalLogToServer(); connect.core._replaceCCPIframe(containerDiv, initCCPParams, identifier); connect.core._refreshIframeOnTimeout(initCCPParams, containerDiv, timerContainer, identifier); } else { connect.core.getEventBus().trigger(connect.EventType.IFRAME_RETRIES_EXHAUSTED, identifier); global.clearTimeout(obj.iframeRefreshTimeout); } }, ccpIframeRefreshInterval); }; connect.core._replaceCCPIframe = function (containerDiv, initCCPParams, identifier) { try { var iframe = connect.core._getCCPIframe(identifier); // Needed because in Global Resiliency, iframe may have been hidden and needs to remain hidden. var iframeStyle = null; if (iframe) { iframeStyle = iframe.style; iframe.parentNode.removeChild(iframe); // The only way to force a synchronous reload of the iframe without the old iframe continuing to function is to remove the old iframe entirely. } var newIframe = connect.core._createCCPIframe(containerDiv, initCCPParams, identifier); // Needed as show and hide iframe functions may modify iframe style if (iframeStyle) { newIframe.style = iframeStyle.cssText; } if (connect.core.getUpstream() instanceof connect.GRProxyIframeConduit) { var grProxyConduit = connect.core.upstream; grProxyConduit.getAllConduits().forEach(function (conduit) { if (conduit.iframe.dataset.identifier === identifier) { conduit.upstream.output = newIframe.contentWindow; conduit.iframe = newIframe; } }); } else { connect.core.getUpstream().upstream.output = newIframe.contentWindow; //replaces the output window (old iframe's contentWindow) of the WindowIOStream (within the IFrameConduit) with the new iframe's contentWindow. } connect.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(newIframe, connect.core.upstream); } catch (e) { connect.getLog().error('Error while checking for, and recreating, the CCP IFrame').withException(e).sendInternalLogToServer(); } }; connect.core._getCCPIframe = function (identifier) { var _iterator2 = _createForOfIteratorHelper(window.document.getElementsByTagName('iframe')), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var iframe = _step2.value; if (iframe.name === CCP_IFRAME_NAME) { var _iframe$dataset; if (!identifier || ((_iframe$dataset = iframe.dataset) === null || _iframe$dataset === void 0 ? void 0 : _iframe$dataset.identifier) === identifier) { // For global resiliency, there can be multiple CCP iframes with the same name. // Return iframe only if the iframe's data-region value matches the specified region. return iframe; } } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return null; }; connect.core._createCCPIframe = function (containerDiv, initCCPParams, identifier) { var _connect$core$_amazon; connect.assertNotNull(initCCPParams, 'initCCPParams'); connect.assertNotNull(containerDiv, 'containerDiv'); var iframe = document.createElement('iframe'); iframe.src = initCCPParams.ccpUrl; iframe.allow = "microphone; camera; autoplay; clipboard-write; identity-credentials-get"; iframe.style = initCCPParams.style || connect.core.iframeStyle; iframe.title = initCCPParams.iframeTitle || CCP_IFRAME_NAME; iframe.name = CCP_IFRAME_NAME; if (identifier) { iframe.dataset.identifier = identifier; } if (connect.storageAccess.canRequest()) { //for Storage Access follow the rsa path iframe.src = connect.storageAccess.getRequestStorageAccessUrl(); iframe.addEventListener('load', connect.storageAccess.request); } // When provider is Streams provider, sets iframe for verification when configuring Message Channel if ((_connect$core$_amazon = connect.core._amazonConnectProviderData) !== null && _connect$core$_amazon !== void 0 && _connect$core$_amazon.isStreamsProvider) { try { var _connect$core$_amazon2; (_connect$core$_amazon2 = connect.core._amazonConnectProviderData) !== null && _connect$core$_amazon2 !== void 0 && _connect$core$_amazon2.isACGREnabled ? connect.core._amazonConnectProviderData.provider.setCCPIframe({ iframe: iframe, region: initCCPParams.globalResiliencyRegion }) : connect.core._amazonConnectProviderData.provider.setCCPIframe(iframe); } catch (error) { connect.getLog().error("Error occurred when setting CCP iframe to provider").withException(error).sendInternalLogToServer(); } } containerDiv.appendChild(iframe); return iframe; }; connect.core._hideIframe = function (iframe) { iframe.style = connect.core.iframeStyle + "display: none;"; }; connect.core._showIframe = function (iframe) { iframe.style = connect.core.iframeStyle; }; connect.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime = function (iframe, conduit) { connect.assertNotNull(iframe, 'iframe'); connect.assertNotNull(conduit, 'conduit'); setTimeout(function () { var style = window.getComputedStyle(iframe, null); var data = { display: style.display, offsetWidth: iframe.offsetWidth, offsetHeight: iframe.offsetHeight, clientRectsLength: iframe.getClientRects().length }; conduit.sendUpstream(connect.EventType.IFRAME_STYLE, data); }, 10000); }; // Open login popup and refresh the iframe until the user is logged in. connect.core.reauthenticateAfterLogout = function () { var _connect$initCCPParam; // Verify that the params needed for authenticate exists if (!connect.initCCPParams || !connect.containerDiv || !connect.core.upstream) { connect.getLog().error("Cannot refresh CCP, missing initCCPParams, container div, and or upstream").withObject({ initCCPParams: connect.initCCPParams, containerDiv: connect.containerDiv, upstream: connect.core.upstream }).sendInternalLogToServer(); throw new Error("Missing parameters to refresh CCP iframe"); } if ((_connect$initCCPParam = connect.initCCPParams) !== null && _connect$initCCPParam !== void 0 && _connect$initCCPParam.enableGlobalResiliency) { connect.getLog().error("Refresh CCP does not support ACGR at the moment").sendInternalLogToServer(); throw new Error("Not supported in ACGR instance"); } else { connect.core.authenticate(connect.initCCPParams, connect.containerDiv, connect.core.upstream); } }; connect.core.authenticate = function (params, containerDiv, conduit) { if (params.loginPopup !== false) { try { var loginUrl = getLoginUrl(params); connect.getLog().warn("Attempting to pop the login page if not already open.").sendInternalLogToServer(); // clear out last opened timestamp for SAML authentication when there is ACK_TIMEOUT if (params.loginUrl) { connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); } connect.core._openPopupWithLock(loginUrl, params.loginOptions); } catch (e) { connect.getLog().error("Unable to open the login popup.").withException(e).sendInternalLogToServer(); } } if (connect.core.iframeRefreshTimeout == null) { try { conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { this.unsubscribe(); global.clearTimeout(connect.core.iframeRefreshTimeout); connect.core.iframeRefreshTimeout = null; connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); if ((params.loginPopupAutoClose || params.loginOptions && params.loginOptions.autoClose) && connect.core.loginWindow) { connect.core.loginWindow.close(); connect.core.loginWindow = null; } }); connect.core.iframeRefreshAttempt = 0; connect.core._refreshIframeOnTimeout(params, containerDiv); } catch (e) { connect.getLog().error("Error occurred while refreshing iframe").withException(e).sendInternalLogToServer(); } } }; connect.core.getSDKClientConfig = function () { var _connect$core$_amazon3; if (!connect.core._amazonConnectProviderData) { throw new Error("Provider is not initialized"); } return { provider: (_connect$core$_amazon3 = connect.core._amazonConnectProviderData) === null || _connect$core$_amazon3 === void 0 ? void 0 : _connect$core$_amazon3.provider }; }; /**-----------------------------------------------------------------------*/ var KeepaliveManager = function KeepaliveManager(conduit, eventBus, synTimeout, ackTimeout) { this.conduit = conduit; this.eventBus = eventBus; this.synTimeout = synTimeout; this.ackTimeout = ackTimeout; this.ackTimer = null; this.synTimer = null; this.ackSub = null; this._enableAckTimeout = false; }; KeepaliveManager.prototype.start = function () { var self = this; this.conduit.sendUpstream(connect.EventType.SYNCHRONIZE); this.ackSub = this.conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { this.unsubscribe(); global.clearTimeout(self.ackTimer); self._deferStart(); }); this.ackTimer = global.setTimeout(function () { self.ackSub.unsubscribe(); if (connect.isActiveConduit(self.conduit) && self._enableAckTimeout) { connect.getLog().info("ACK_TIMEOUT event is detected from the KeepaliveManager. ".concat(self.conduit.name)).sendInternalLogToServer(); self.eventBus.trigger(connect.EventType.ACK_TIMEOUT); } else if (self._enableAckTimeout) { connect.getLog().warn("ACK_TIMEOUT event is detected from the KeepaliveManager but suppressed as it is from an inactive region. ".concat(self.conduit.name)).sendInternalLogToServer(); } self._deferStart(); }, this.ackTimeout); }; //Fixes the keepalivemanager. KeepaliveManager.prototype._deferStart = function () { this.synTimer = global.setTimeout(connect.hitch(this, this.start), this.synTimeout); }; // For backwards compatibility only, in case customers are using this to start the keepalivemanager for some reason. KeepaliveManager.prototype.deferStart = function () { if (this.synTimer == null) { this.synTimer = global.setTimeout(connect.hitch(this, this.start), this.synTimeout); } }; KeepaliveManager.prototype.enableAckTimeout = function (enable) { this._enableAckTimeout = enable; }; /**-----------------------------------------------------------------------*/ var WebSocketProvider = function WebSocketProvider() { var callbacks = { initFailure: new Set(), subscriptionUpdate: new Set(), subscriptionFailure: new Set(), topic: new Map(), allMessage: new Set(), connectionGain: new Set(), connectionLost: new Set(), connectionOpen: new Set(), connectionClose: new Set(), deepHeartbeatSuccess: new Set(), deepHeartbeatFailure: new Set(), topicFailure: new Set() }; var invokeCallbacks = function invokeCallbacks(callbacks, response) { callbacks.forEach(function (callback) { callback(response); }); }; connect.core.getUpstream().onUpstream(connect.WebSocketEvents.INIT_FAILURE, function () { invokeCallbacks(callbacks.initFailure); }); connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_OPEN, function (response) { invokeCallbacks(callbacks.connectionOpen, response); }); connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_CLOSE, function (response) { invokeCallbacks(callbacks.connectionClose, response); }); connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_GAIN, function () { invokeCallbacks(callbacks.connectionGain); }); connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_LOST, function (response) { invokeCallbacks(callbacks.connectionLost, response); }); connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, function (response) { invokeCallbacks(callbacks.subscriptionUpdate, response); }); connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, function (response) { invokeCallbacks(callbacks.subscriptionFailure, response); }); connect.core.getUpstream().onUpstream(connect.WebSocketEvents.ALL_MESSAGE, function (response) { invokeCallbacks(callbacks.allMessage, response); if (callbacks.topic.has(response.topic)) { invokeCallbacks(callbacks.topic.get(response.topic), response); } }); this.sendMessage = function (webSocketPayload) { connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SEND, webSocketPayload); }; this.onInitFailure = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.initFailure.add(cb); return function () { return callbacks.initFailure["delete"](cb); }; }; this.onConnectionOpen = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.connectionOpen.add(cb); return function () { return callbacks.connectionOpen["delete"](cb); }; }; this.onConnectionClose = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.connectionClose.add(cb); return function () { return callbacks.connectionClose["delete"](cb); }; }; this.onConnectionGain = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.connectionGain.add(cb); return function () { return callbacks.connectionGain["delete"](cb); }; }; this.onConnectionLost = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.connectionLost.add(cb); return function () { return callbacks.connectionLost["delete"](cb); }; }; this.onSubscriptionUpdate = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.subscriptionUpdate.add(cb); return function () { return callbacks.subscriptionUpdate["delete"](cb); }; }; this.onSubscriptionFailure = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.subscriptionFailure.add(cb); return function () { return callbacks.subscriptionFailure["delete"](cb); }; }; this.subscribeTopics = function (topics) { connect.assertNotNull(topics, 'topics'); connect.assertTrue(connect.isArray(topics), 'topics must be a array'); connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SUBSCRIBE, topics); }; this.onMessage = function (topicName, cb) { connect.assertNotNull(topicName, 'topicName'); connect.assertTrue(connect.isFunction(cb), 'method must be a function'); if (callbacks.topic.has(topicName)) { callbacks.topic.get(topicName).add(cb); } else { callbacks.topic.set(topicName, new Set([cb])); } return function () { return callbacks.topic.get(topicName)["delete"](cb); }; }; this.onAllMessage = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.allMessage.add(cb); return function () { return callbacks.allMessage["delete"](cb); }; }; this.onDeepHeartbeatSuccess = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.deepHeartbeatSuccess.add(cb); return function () { return callbacks.deepHeartbeatSuccess["delete"](cb); }; }; this.onDeepHeartbeatFailure = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.deepHeartbeatFailure.add(cb); return function () { return callbacks.deepHeartbeatFailure["delete"](cb); }; }; this.onTopicFailure = function (cb) { connect.assertTrue(connect.isFunction(cb), 'method must be a function'); callbacks.topicFailure.add(cb); return function () { return callbacks.topicFailure["delete"](cb); }; }; }; connect.core._removeContactFromEndedSet = function (contactId) { try { connect.getLog().info("[ContactEvent] Removing contact from ENDED event tracker").withObject({ contactId: contactId }).sendInternalLogToServer(); connect.core.endedEventTracker["delete"](contactId); connect.getLog().info("[ContactEvent] Removed contact from ENDED event tracker").withObject(connect.core.endedEventTracker.entries()).sendInternalLogToServer(); } catch (e) { connect.getLog().error("[ContactEvent] Failed to remove contact from ENDED event tracker").withObject({ contactId: contactId || 'unknown' }).withException(e).sendInternalLogToServer(); } }; connect.core._handleEndedEvent = function (contactId, newContactState) { try { // if the event being triggered is ENDED, remove the contactId from the set // we want to check for all inactive contact states because active state -> inactive state = ENDED event if (connect.core.endedEventTracker.has(contactId) && inactiveContactState.includes(newContactState)) { connect.getLog().info("[ContactEvent] ENDED was triggered").withObject({ contactId: contactId }).sendInternalLogToServer(); connect.core._removeContactFromEndedSet(contactId); } } catch (e) { connect.getLog().error("[ContactEvent] Failed to handle proper ENDED event being triggered").withException(e).sendInternalLogToServer(); } }; connect.core._shouldTriggerInvalidStateTransition = function (contactData) { if (connect.core.endedEventTracker.has(contactData.contactId)) { try { connect.getLog().info("[ContactEvent] Contact did not transition to the ENDED state prior to DESTROYED").withObject(contactData).sendInternalLogToServer(); connect.core._removeContactFromEndedSet(contactData.contactId); return true; } catch (e) { connect.getLog().error("[ContactEvent] Failed to handle invalid state transition error handling").withException(e).sendInternalLogToServer(); } } return false; }; /**-----------------------------------------------------------------------*/ var AgentDataProvider = function AgentDataProvider(bus) { var agentData = null; this.bus = bus; this.agentUpdateSubscriber = this.bus.subscribe(connect.AgentEvents.UPDATE, connect.hitch(this, this.updateAgentData)); }; AgentDataProvider.prototype.updateAgentData = function (agentData) { var _connect$agent; var oldAgentData = this.agentData; this.agentData = agentData; if (!((_connect$agent = connect.agent) !== null && _connect$agent !== void 0 && _connect$agent.initialized)) { connect.agent.initialized = true; this.bus.trigger(connect.AgentEvents.INIT, new connect.Agent()); } this.bus.trigger(connect.AgentEvents.REFRESH, new connect.Agent()); this._fireAgentUpdateEvents(oldAgentData); }; AgentDataProvider.prototype.getAgentData = function () { if (this.agentData == null) { throw new connect.StateError('No agent data is available yet!'); } return this.agentData; }; AgentDataProvider.prototype.getContactData = function (contactId) { var agentData = this.getAgentData(); var contactData = connect.find(agentData.snapshot.contacts, function (ctdata) { return ctdata.contactId === contactId; }); if (contactData == null) { throw new connect.StateError('Contact %s no longer exists.', contactId); } return contactData; }; AgentDataProvider.prototype.getConnectionData = function (contactId, connectionId) { var contactData = this.getContactData(contactId); var connectionData = connect.find(contactData.connections, function (cdata) { return cdata.connectionId === connectionId; }); if (connectionData == null) { throw new connect.StateError('Connection %s for contact %s no longer exists.', connectionId, contactId); } return connectionData; }; AgentDataProvider.prototype.getInstanceId = function () { return this.getAgentData().configuration.routingProfile.routingProfileId.match(/instance\/([0-9a-fA-F|-]+)\//)[1]; }; AgentDataProvider.prototype.getAWSAccountId = function () { return this.getAgentData().configuration.routingProfile.routingProfileId.match(/:([0-9]+):instance/)[1]; }; AgentDataProvider.prototype._diffContacts = function (oldAgentData) { var diff = { added: {}, removed: {}, common: {}, oldMap: connect.index(oldAgentData == null ? [] : oldAgentData.snapshot.contacts, function (contact) { return contact.contactId; }), newMap: connect.index(this.agentData.snapshot.contacts, function (contact) { return contact.contactId; }), endTime: 0 }; connect.keys(diff.oldMap).forEach(function (contactId) { if (connect.contains(diff.newMap, contactId)) { diff.common[contactId] = diff.newMap[contactId]; } else { diff.removed[contactId] = diff.oldMap[contactId]; } }); connect.keys(diff.newMap).forEach(function (contactId) { if (!connect.contains(diff.oldMap, contactId)) { diff.added[contactId] = diff.newMap[contactId]; } }); diff.endTime = performance.now(); return diff; }; AgentDataProvider.prototype._fireAgentUpdateEvents = function (oldAgentData) { var self = this; var diff = null; var oldAgentState = oldAgentData == null ? connect.AgentAvailStates.INIT : oldAgentData.snapshot.state.name; var newAgentState = this.agentData.snapshot.state.name; var oldRoutingState = oldAgentData == null ? connect.AgentStateType.INIT : oldAgentData.snapshot.state.type; var newRoutingState = this.agentData.snapshot.state.type; if (oldRoutingState !== newRoutingState) { connect.core.getAgentRoutingEventGraph().getAssociations(this, oldRoutingState, newRoutingState).forEach(function (event) { self.bus.trigger(event, new connect.Agent()); }); } if (oldAgentState !== newAgentState) { this.bus.trigger(connect.AgentEvents.STATE_CHANGE, { agent: new connect.Agent(), oldState: oldAgentState, newState: newAgentState }); connect.core.getAgentStateEventGraph().getAssociations(this, oldAgentState, newAgentState).forEach(function (event) { self.bus.trigger(event, new connect.Agent()); }); } var oldNextState = oldAgentData && oldAgentData.snapshot.nextState ? oldAgentData.snapshot.nextState.name : null; var newNextState = this.agentData.snapshot.nextState ? this.agentData.snapshot.nextState.name : null; if (oldNextState !== newNextState && newNextState) { self.bus.trigger(connect.AgentEvents.ENQUEUED_NEXT_STATE, new connect.Agent()); } if (oldAgentData !== null) { diff = this._diffContacts(oldAgentData); } else { diff = { added: connect.index(this.agentData.snapshot.contacts, function (contact) { return contact.contactId; }), removed: {}, common: {}, oldMap: {}, newMap: connect.index(this.agentData.snapshot.contacts, function (contact) { return contact.contactId; }), endTime: performance.now() }; } connect.values(diff.added).forEach(function (contactData) { self.bus.trigger(connect.ContactEvents.INIT, new connect.Contact(contactData.contactId)); self._fireContactUpdateEvents(contactData.contactId, connect.ContactStateType.INIT, contactData.state.type); }); connect.values(diff.removed).forEach(function (contactData) { self.bus.trigger(connect.ContactEvents.DESTROYED, new connect.ContactSnapshot(contactData)); self.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.DESTROYED, contactData.contactId), new connect.ContactSnapshot(contactData)); self._unsubAllContactEventsForContact(contactData.contactId); }); connect.keys(diff.common).forEach(function (contactId) { self._fireContactUpdateEvents(contactId, diff.oldMap[contactId].state.type, diff.newMap[contactId].state.type); }); }; AgentDataProvider.prototype._fireContactUpdateEvents = function (contactId, oldContactState, newContactState) { var self = this; if (oldContactState !== newContactState) { connect.core.getContactEventGraph().getAssociations(this, oldContactState, newContactState).forEach(function (event) { self.bus.trigger(event, new connect.Contact(contactId)); self.bus.trigger(connect.core.getContactEventName(event, contactId), new connect.Contact(contactId)); }); } self.bus.trigger(connect.ContactEvents.REFRESH, new connect.Contact(contactId)); self.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.REFRESH, contactId), new connect.Contact(contactId)); }; AgentDataProvider.prototype._unsubAllContactEventsForContact = function (contactId) { var self = this; connect.values(connect.ContactEvents).forEach(function (eventName) { self.bus.getSubscriptions(connect.core.getContactEventName(eventName, contactId)).map(function (sub) { sub.unsubscribe(); }); }); }; AgentDataProvider.prototype.destroy = function () { var self = this; self.agentUpdateSubscriber.unsubscribe(); }; /** ----- minimal view layer event handling **/ connect.core.onViewContact = function (f) { return connect.core.getEventBus().subscribe(connect.ContactEvents.VIEW, f); }; /** * Used of agent interface control. * connect.core.viewContact("contactId") -> this is currently programmed to get the contact into view. */ connect.core.viewContact = function (contactId) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ContactEvents.VIEW, data: { contactId: contactId } }); }; /** ----- minimal view layer event handling **/ connect.core.onActivateChannelWithViewType = function (f) { return connect.core.getEventBus().subscribe(connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, f); }; /** * Used of agent interface control. * connect.core.activateChannelWithViewType() -> this is currently programmed to get either the number pad, quick connects, or create task into view. * the valid combinations are ("create_task", "task"), ("number_pad", "softphone"), ("create_task", "softphone"), ("quick_connects", "softphone") * the softphone with create_task combo is a special case in the channel view to allow all three view type buttons to appear on the softphone screen * * The 'source' is an optional parameter which indicates the requester. For example, if invoked with ("create_task", "task", "agentapp") we would know agentapp requested open task view. * * "caseId" is an optional parameter which is passed when a task is created from a Kesytone case * * clientToken - optional parameter used for deduping the incoming requests (idempotent token). * as we use broadcast mechanisms, every browser tab gets this request and we need a way to prevent processing the same request accross all browesrs tabs. * This is being used for emails today where we have a weblock serving this request and tracks the client token to process it once and dedupes the rest * */ connect.core.activateChannelWithViewType = function (viewType, mediaType, source, caseId, clientToken) { var data = { viewType: viewType, mediaType: mediaType }; if (source) { data.source = source; } if (caseId) { data.caseId = caseId; } if (clientToken) { data.clientToken = clientToken; } else { data.clientToken = connect.randomId(); // Create a random token } connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, data: data }); }; /** * Used to publish 'task created' event */ connect.core.triggerTaskCreated = function (data) { connect.core.getUpstream().upstreamBus.trigger(connect.TaskEvents.CREATED, data); }; /** * Used to publish 'email created' event */ connect.core.triggerEmailCreated = function (data) { connect.core.getUpstream().upstreamBus.trigger(connect.EmailEvents.CREATED, data); }; /** ------------------------------------------------- */ /** * This will be helpful for the custom and embedded CCPs * to handle the access denied use case. */ connect.core.onAccessDenied = function (f) { return connect.core.getEventBus().subscribe(connect.EventType.ACCESS_DENIED, f); }; /** * This will be helpful for SAML use cases to handle the custom logins. */ connect.core.onAuthFail = function (f) { return connect.core.getEventBus().subscribe(connect.EventType.AUTH_FAIL, f); }; connect.core.onAuthorizeSuccess = function (f) { return connect.core.getEventBus().subscribe(connect.EventType.AUTHORIZE_SUCCESS, f); }; connect.core._handleAuthorizeSuccess = function () { window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, 0); }; connect.core._handleAuthFail = function (loginUrl, authorizeEndpoint, authFailData) { if (authFailData && authFailData.authorize) { connect.core._handleAuthorizeFail(loginUrl); } else { connect.core._handleCTIAuthFail(authorizeEndpoint); } }; connect.core._handleAuthorizeFail = function (loginUrl) { var authRetryCount = connect.core._getAuthRetryCount(); if (!connect.core.authorizeTimeoutId) { if (authRetryCount < connect.core.MAX_AUTHORIZE_RETRY_COUNT_FOR_SESSION) { connect.core._incrementAuthRetryCount(); var retryDelay = AWS.util.calculateRetryDelay(authRetryCount + 1 || 0, { base: 2000 }); connect.core.authorizeTimeoutId = setTimeout(function () { connect.core._redirectToLogin(loginUrl); }, retryDelay); //We don't have to clear the timeoutId because we are redirecting away from this origin once the timeout completes. } else { connect.getLog().warn("We have exhausted our authorization retries due to 401s from the authorize api. No more retries will be attempted in this session until the authorize api returns 200.").sendInternalLogToServer(); connect.core.getEventBus().trigger(connect.EventType.AUTHORIZE_RETRIES_EXHAUSTED); } } }; connect.core._redirectToLogin = function (loginUrl) { if (typeof loginUrl === 'string') { location.assign(loginUrl); } else { location.reload(); } }; connect.core._handleCTIAuthFail = function (authorizeEndpoint) { if (!connect.core.ctiTimeoutId) { if (connect.core.ctiAuthRetryCount < connect.core.MAX_CTI_AUTH_RETRY_COUNT) { connect.core.ctiAuthRetryCount++; var retryDelay = AWS.util.calculateRetryDelay(connect.core.ctiAuthRetryCount || 0, { base: 500 }); connect.core.ctiTimeoutId = setTimeout(function () { connect.core.authorize(authorizeEndpoint).then(connect.core._triggerAuthorizeSuccess.bind(connect.core))["catch"](connect.core._triggerAuthFail.bind(connect.core, { authorize: true })); connect.core.ctiTimeoutId = null; }, retryDelay); } else { connect.getLog().warn("We have exhausted our authorization retries due to 401s from the CTI service. No more retries will be attempted until the page is refreshed.").sendInternalLogToServer(); connect.core.getEventBus().trigger(connect.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED); } } }; connect.core._triggerAuthorizeSuccess = function () { connect.core.getUpstream().upstreamBus.trigger(connect.EventType.AUTHORIZE_SUCCESS); }; connect.core._triggerAuthFail = function (data) { connect.core.getUpstream().upstreamBus.trigger(connect.EventType.AUTH_FAIL, data); }; connect.core._getAuthRetryCount = function () { var item = window.sessionStorage.getItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT); if (item !== null) { if (!isNaN(parseInt(item))) { return parseInt(item); } else { throw new connect.StateError("The session storage value for auth retry count was NaN"); } } else { window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, 0); return 0; } }; connect.core._incrementAuthRetryCount = function () { window.sessionStorage.setItem(connect.SessionStorageKeys.AUTHORIZE_RETRY_COUNT, (connect.core._getAuthRetryCount() + 1).toString()); }; connect.core.onAuthorizeRetriesExhausted = function (f) { return connect.core.getEventBus().subscribe(connect.EventType.AUTHORIZE_RETRIES_EXHAUSTED, f); }; connect.core.onCTIAuthorizeRetriesExhausted = function (f) { return connect.core.getEventBus().subscribe(connect.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED, f); }; /** ------------------------------------------------- */ /** * Used for handling the rtc session stats. * Usage * connect.core.onSoftphoneSessionInit(function({ connectionId }) { * var softphoneManager = connect.core.getSoftphoneManager(); * if(softphoneManager){ * // access session * var session = softphoneManager.getSession(connectionId); * } * }); */ connect.core.onSoftphoneSessionInit = function (f) { return connect.core.getEventBus().subscribe(connect.ConnectionEvents.SESSION_INIT, f); }; /**-----------------------------------------------------------------------*/ connect.core.onConfigure = function (f) { return connect.core.getEventBus().subscribe(connect.ConfigurationEvents.CONFIGURE, f); }; /**-----------------------------------------------------------------------*/ connect.core.onInitialized = function (f) { return connect.core.getEventBus().subscribe(connect.EventType.INIT, f); }; /**-----------------------------------------------------------------------*/ connect.core.sendConfigure = function (params, conduit, isACGR) { if (params.softphone || params.chat || params.task || params.pageOptions || params.shouldAddNamespaceToLogs || params.disasterRecoveryOn) { var _params$pageOptions; var config = { softphone: params.softphone, chat: params.chat, task: params.task, pageOptions: params.pageOptions, shouldAddNamespaceToLogs: params.shouldAddNamespaceToLogs, showInactivityModal: (_params$pageOptions = params.pageOptions) === null || _params$pageOptions === void 0 ? void 0 : _params$pageOptions.showInactivityModal }; if (isACGR) { // ACGR mode: add ACGR-specific params, exclude disasterRecoveryOn config.enableGlobalResiliency = params.enableGlobalResiliency; config.instanceState = connect.isActiveConduit(conduit) ? 'active' : 'inactive'; } else { // Legacy mode: include disasterRecoveryOn param config.disasterRecoveryOn = params.disasterRecoveryOn; } conduit.sendUpstream(connect.EventType.CONFIGURE, config); } ; }; /**-----------------------------------------------------------------------*/ connect.core.listenForConfigureRequest = function (params, conduit, isACGR) { conduit.onUpstream(connect.EventType.REQUEST_CONFIGURE, function () { connect.core.sendConfigure(params, conduit, isACGR); }); }; /**-----------------------------------------------------------------------*/ // If the CRM hasn't sent a configure message, we send a request to receive configure // This is in case iframed CCP is refreshed abnormally connect.core.checkIfConfigureReceived = function (conduit) { if (connect.isFramed()) { global.setTimeout(function () { if (!connect.core.hasReceivedCRMConfigure) { connect.getLog().warn("CCP has not received a configure message. Sending request to CRM for configuration.").sendInternalLogToServer(); conduit.sendDownstream(connect.EventType.REQUEST_CONFIGURE); } }, 1000); } }; /**-----------------------------------------------------------------------*/ connect.core.getContactEventName = function (eventName, contactId) { connect.assertNotNull(eventName, 'eventName'); connect.assertNotNull(contactId, 'contactId'); if (!connect.contains(connect.values(connect.ContactEvents), eventName)) { throw new connect.ValueError('%s is not a valid contact event.', eventName); } return connect.sprintf('%s::%s', eventName, contactId); }; /**-----------------------------------------------------------------------*/ connect.core.getEventBus = function () { return connect.core.eventBus; }; /**-----------------------------------------------------------------------*/ connect.core.getWebSocketManager = function () { return connect.core.webSocketProvider; }; /**-----------------------------------------------------------------------*/ connect.core.getAgentDataProvider = function () { return connect.core.agentDataProvider; }; /**-----------------------------------------------------------------------*/ connect.core.getLocalTimestamp = function () { return connect.core.getAgentDataProvider().getAgentData().snapshot.localTimestamp; }; /**-----------------------------------------------------------------------*/ connect.core.getSkew = function () { return connect.core.getAgentDataProvider().getAgentData().snapshot.skew; }; /**-----------------------------------------------------------------------*/ connect.core.getAgentRoutingEventGraph = function () { return connect.core.agentRoutingEventGraph; }; connect.core.agentRoutingEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.AgentStateType.ROUTABLE, connect.AgentEvents.ROUTABLE).assoc(connect.EventGraph.ANY, connect.AgentStateType.NOT_ROUTABLE, connect.AgentEvents.NOT_ROUTABLE).assoc(connect.EventGraph.ANY, connect.AgentStateType.OFFLINE, connect.AgentEvents.OFFLINE); /**-----------------------------------------------------------------------*/ connect.core.getAgentStateEventGraph = function () { return connect.core.agentStateEventGraph; }; connect.core.agentStateEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.values(connect.AgentErrorStates), connect.AgentEvents.ERROR).assoc(connect.EventGraph.ANY, connect.AgentAvailStates.AFTER_CALL_WORK, connect.AgentEvents.ACW); /**-----------------------------------------------------------------------*/ connect.core.getContactEventGraph = function () { return connect.core.contactEventGraph; }; connect.core.contactEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.ContactStateType.INCOMING, connect.ContactEvents.INCOMING).assoc(connect.EventGraph.ANY, connect.ContactStateType.PENDING, connect.ContactEvents.PENDING).assoc(connect.EventGraph.ANY, connect.ContactStateType.CONNECTING, connect.ContactEvents.CONNECTING).assoc(connect.EventGraph.ANY, connect.ContactStateType.CONNECTED, connect.ContactEvents.CONNECTED).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.ERROR, connect.ContactEvents.MISSED).assoc(connect.ContactStateType.INCOMING, connect.ContactStateType.ERROR, connect.ContactEvents.MISSED).assoc(connect.EventGraph.ANY, connect.ContactStateType.ENDED, connect.ContactEvents.ACW).assoc(connect.values(connect.CONTACT_ACTIVE_STATES), connect.values(connect.relativeComplement(connect.CONTACT_ACTIVE_STATES, connect.ContactStateType)), connect.ContactEvents.ENDED).assoc(connect.EventGraph.ANY, connect.ContactStateType.ERROR, connect.ContactEvents.ERROR).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.MISSED, connect.ContactEvents.MISSED).assoc(connect.ContactStateType.INCOMING, connect.ContactStateType.MISSED, connect.ContactEvents.MISSED).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.REJECTED, connect.ContactEvents.MISSED).assoc(connect.ContactStateType.INCOMING, connect.ContactStateType.REJECTED, connect.ContactEvents.MISSED); /**-----------------------------------------------------------------------*/ connect.core.getClient = function () { if (!connect.core.client) { throw new connect.StateError('The connect core has not been initialized!'); } return connect.core.client; }; connect.core.client = null; /**-----------------------------------------------------------------------*/ connect.core.getApiProxyClient = function () { if (!connect.core.apiProxyClient) { throw new connect.StateError('The connect apiProxy Client has not been initialized!'); } return connect.core.apiProxyClient; }; connect.core.apiProxyClient = null; /**-----------------------------------------------------------------------*/ connect.core.getAgentAppClient = function () { if (!connect.core.agentAppClient) { throw new connect.StateError('The connect AgentApp Client has not been initialized!'); } return connect.core.agentAppClient; }; connect.core.agentAppClient = null; /**-----------------------------------------------------------------------*/ connect.core.getTaskTemplatesClient = function () { if (!connect.core.taskTemplatesClient) { throw new connect.StateError('The connect TaskTemplates Client has not been initialized!'); } return connect.core.taskTemplatesClient; }; connect.core.taskTemplatesClient = null; /**-----------------------------------------------------------------------*/ connect.core.getMasterClient = function () { if (!connect.core.masterClient) { throw new connect.StateError('The connect master client has not been initialized!'); } return connect.core.masterClient; }; connect.core.masterClient = null; /**-----------------------------------------------------------------------*/ connect.core.getSoftphoneManager = function () { return connect.core.softphoneManager; }; connect.core.softphoneManager = null; /**-----------------------------------------------------------------------*/ connect.core.getNotificationManager = function () { if (!connect.core.notificationManager) { connect.core.notificationManager = new connect.NotificationManager(); } return connect.core.notificationManager; }; connect.core.notificationManager = null; /**-----------------------------------------------------------------------*/ connect.core.getPopupManager = function () { return connect.core.popupManager; }; connect.core.popupManager = new connect.PopupManager(); /**-----------------------------------------------------------------------*/ connect.core.getUpstream = function () { if (!connect.core.upstream) { throw new connect.StateError('There is no upstream conduit!'); } return connect.core.upstream; }; connect.core.upstream = null; /**-----------------------------------------------------------------------*/ connect.globalResiliency.onFailoverPending = function (f) { return connect.core.getEventBus().subscribe(connect.GlobalResiliencyEvents.FAILOVER_PENDING_CRM, f); }; /**-----------------------------------------------------------------------*/ connect.globalResiliency.onFailoverCompleted = function (f) { return connect.core.getEventBus().subscribe(connect.GlobalResiliencyEvents.FAILOVER_COMPLETE, f); }; /**-----------------------------------------------------------------------*/ connect.globalResiliency.onConfigureError = function (f) { return connect.core.getEventBus().subscribe(connect.GlobalResiliencyEvents.CONFIGURE_ERROR, f); }; /**-----------------------------------------------------------------------*/ connect.globalResiliency.getActiveRegion = function () { return connect.globalResiliency._activeRegion; }; /**-----------------------------------------------------------------------*/ connect.core.AgentDataProvider = AgentDataProvider; connect.WebSocketProvider = WebSocketProvider; connect.KeepaliveManager = KeepaliveManager; })(); /***/ }), /***/ 682: /***/ (() => { /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; var ALL_EVENTS = '<>'; /**--------------------------------------------------------------- * enum EventType */ var EventType = connect.makeEnum(['acknowledge', 'ack_timeout', 'init', 'api_request', 'api_response', 'auth_fail', 'access_denied', 'close', 'configure', 'log', 'download_log_from_ccp', 'master_request', 'master_response', 'synchronize', 'terminate', 'terminated', 'send_logs', 'reload_agent_configuration', 'broadcast', 'api_metric', 'client_metric', 'softphone_stats', 'softphone_report', 'client_side_logs', 'server_bound_internal_log', 'mute', "iframe_style", "iframe_retries_exhausted", "update_connected_ccps", "outer_context_info", "media_device_request", "media_device_response", "tab_id", 'authorize_success', 'authorize_retries_exhausted', 'cti_authorize_retries_exhausted', 'click_stream_data', 'set_quick_get_agent_snapshot_flag', 'api_proxy_request', 'api_proxy_response', 'request_configure']); /**--------------------------------------------------------------- * enum MasterTopics */ var MasterTopics = connect.makeNamespacedEnum('connect', ['loginPopup', 'sendLogs', 'softphone', 'ringtone', 'metrics', 'failover']); /**--------------------------------------------------------------- * enum AgentEvents */ var AgentEvents = connect.makeNamespacedEnum('agent', ['init', 'update', 'refresh', 'routable', 'not_routable', 'pending', 'contact_pending', 'offline', 'error', 'softphone_error', 'websocket_connection_lost', 'websocket_connection_gained', 'state_change', 'acw', 'mute_toggle', 'local_media_stream_created', 'enqueued_next_state', 'fetch_agent_data_from_ccp']); /**--------------------------------------------------------------- * enum WebSocketEvents */ var WebSocketEvents = connect.makeNamespacedEnum('webSocket', ['init_failure', 'connection_open', 'connection_close', 'connection_error', 'connection_gain', 'connection_lost', 'subscription_update', 'subscription_failure', 'all_message', 'send', 'subscribe']); /**--------------------------------------------------------------- * enum ContactEvents */ var ContactEvents = connect.makeNamespacedEnum('contact', ['init', 'refresh', 'destroyed', 'incoming', 'pending', 'connecting', 'connected', 'missed', 'acw', 'view', 'ended', 'error', 'accepted', 'invalid_state_transition', 'screen_sharing_started', 'screen_sharing_stopped', 'screen_sharing_error']); var ChannelViewEvents = connect.makeNamespacedEnum('taskList', ['activate_channel_with_view_type']); var TaskEvents = connect.makeNamespacedEnum('task', ['created']); var EmailEvents = connect.makeNamespacedEnum('email', ['created']); /**--------------------------------------------------------------- * enum ConnectionEvents */ var ConnectionEvents = connect.makeNamespacedEnum('connection', ['session_init', 'ready_to_start_session']); /**--------------------------------------------------------------- * enum Configuration Events */ var ConfigurationEvents = connect.makeNamespacedEnum('configuration', ['configure', 'set_speaker_device', 'set_microphone_device', 'set_ringer_device', 'speaker_device_changed', 'microphone_device_changed', 'ringer_device_changed', 'camera_device_changed', 'background_blur_changed']); /**--------------------------------------------------------------- * enum Disaster Recovery Events */ var DisasterRecoveryEvents = connect.makeNamespacedEnum('disasterRecovery', ['suppress', 'force_offline', // letting the sharedworker know to force offline 'set_offline', // iframe letting the native ccp to set offline 'init_disaster_recovery', 'failover', // used to propagate failover state to other windows 'failover_pending', // signals that a soft failover will occur when current voice contact ends 'init_dr_polling']); // New Global Resiliency implementation var GlobalResiliencyEvents = connect.makeNamespacedEnum('globalResiliency', ['configure', 'configure_ccp_conduit', 'init', 'configure_error', 'failover_initiated', 'failover_pending', 'failover_pending_crm', 'failover_complete', 'heartbeat_syn', 'heartbeat_ack']); /**--------------------------------------------------------------- * enum VoiceId Events */ var VoiceIdEvents = connect.makeNamespacedEnum('voiceId', ['update_domain_id']); /**--------------------------------------------------------------- * class EventFactory */ var EventFactory = function EventFactory() {}; EventFactory.createRequest = function (type, method, params) { return { event: type, requestId: connect.randomId(), method: method, params: params }; }; EventFactory.createResponse = function (type, request, data, err) { return { event: type, requestId: request.requestId, data: data, err: err || null }; }; /** * An object representing an event subscription in an EventBus. */ var Subscription = function Subscription(subMap, eventName, f) { this.subMap = subMap; this.id = connect.randomId(); this.eventName = eventName; this.f = f; }; /** * Unsubscribe the handler of this subscription from the EventBus * from which it was created. */ Subscription.prototype.unsubscribe = function () { this.subMap.unsubscribe(this.eventName, this.id); }; /** * A map of event subscriptions, used by the EventBus. */ var SubscriptionMap = function SubscriptionMap() { this.subIdMap = {}; this.subEventNameMap = {}; }; /** * Add a subscription for the named event. Creates a new Subscription * object and returns it. This object can be used to unsubscribe. */ SubscriptionMap.prototype.subscribe = function (eventName, f) { var sub = new Subscription(this, eventName, f); this.subIdMap[sub.id] = sub; var subList = this.subEventNameMap[eventName] || []; subList.push(sub); this.subEventNameMap[eventName] = subList; return sub; }; /** * Unsubscribe a subscription matching the given event name and id. */ SubscriptionMap.prototype.unsubscribe = function (eventName, subId) { if (connect.contains(this.subEventNameMap, eventName)) { this.subEventNameMap[eventName] = this.subEventNameMap[eventName].filter(function (s) { return s.id !== subId; }); if (this.subEventNameMap[eventName].length < 1) { delete this.subEventNameMap[eventName]; } } if (connect.contains(this.subIdMap, subId)) { delete this.subIdMap[subId]; } }; /** * Get a list of all subscriptions in the subscription map. */ SubscriptionMap.prototype.getAllSubscriptions = function () { return connect.values(this.subEventNameMap).reduce(function (a, b) { return a.concat(b); }, []); }; /** * Get a list of subscriptions for the given event name, or an empty * list if there are no subscriptions. */ SubscriptionMap.prototype.getSubscriptions = function (eventName) { return this.subEventNameMap[eventName] || []; }; /** * An object which maintains a map of subscriptions and serves as the * mechanism for triggering events to be handled by subscribers. */ var EventBus = function EventBus(paramsIn) { var params = paramsIn || {}; this.subMap = new SubscriptionMap(); this.logEvents = params.logEvents || false; }; /** * Subscribe to the named event. Returns a new Subscription object * which can be used to unsubscribe. */ EventBus.prototype.subscribe = function (eventName, f) { connect.assertNotNull(eventName, 'eventName'); connect.assertNotNull(f, 'f'); connect.assertTrue(connect.isFunction(f), 'f must be a function'); return this.subMap.subscribe(eventName, f); }; /** * Subscribe a function to be called on all events. */ EventBus.prototype.subscribeAll = function (f) { connect.assertNotNull(f, 'f'); connect.assertTrue(connect.isFunction(f), 'f must be a function'); return this.subMap.subscribe(ALL_EVENTS, f); }; /** * Get a list of subscriptions for the given event name, or an empty * list if there are no subscriptions. */ EventBus.prototype.getSubscriptions = function (eventName) { return this.subMap.getSubscriptions(eventName); }; /** * Trigger the given event with the given data. All methods subscribed * to this event will be called and are provided with the given arbitrary * data object and the name of the event, in that order. */ EventBus.prototype.trigger = function (eventName, data) { connect.assertNotNull(eventName, 'eventName'); var self = this; var allEventSubs = this.subMap.getSubscriptions(ALL_EVENTS); var eventSubs = this.subMap.getSubscriptions(eventName); if (this.logEvents && eventName !== connect.EventType.LOG && eventName !== connect.EventType.MASTER_RESPONSE && eventName !== connect.EventType.API_METRIC && eventName !== connect.EventType.SERVER_BOUND_INTERNAL_LOG) { connect.getLog().trace("Publishing event: %s", eventName).sendInternalLogToServer(); } if (eventName.startsWith(connect.ContactEvents.ACCEPTED) && data && data.contactId && !(data instanceof connect.Contact)) { data = new connect.Contact(data.contactId); } allEventSubs.concat(eventSubs).forEach(function (sub) { try { sub.f(data || null, eventName, self); } catch (e) { connect.getLog().error("'%s' event handler failed.", eventName).withException(e).sendInternalLogToServer(); } }); }; /** * Returns a closure which bridges an event from another EventBus to this bus. * * Usage: * conduit.onUpstream("MyEvent", bus.bridge()); */ EventBus.prototype.bridge = function () { var self = this; return function (data, event) { self.trigger(event, data); }; }; /** * Unsubscribe all events in the event bus. */ EventBus.prototype.unsubscribeAll = function () { this.subMap.getAllSubscriptions().forEach(function (sub) { sub.unsubscribe(); }); }; connect.EventBus = EventBus; connect.EventFactory = EventFactory; connect.EventType = EventType; connect.AgentEvents = AgentEvents; connect.ConfigurationEvents = ConfigurationEvents; connect.ConnectionEvents = ConnectionEvents; connect.ConnnectionEvents = ConnectionEvents; //deprecate on next major version release. connect.ContactEvents = ContactEvents; connect.ChannelViewEvents = ChannelViewEvents; connect.TaskEvents = TaskEvents; connect.EmailEvents = EmailEvents; connect.VoiceIdEvents = VoiceIdEvents; connect.WebSocketEvents = WebSocketEvents; connect.MasterTopics = MasterTopics; connect.DisasterRecoveryEvents = DisasterRecoveryEvents; connect.GlobalResiliencyEvents = GlobalResiliencyEvents; })(); /***/ }), /***/ 949: /***/ (() => { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; var CCP_SYN_TIMEOUT = 1000; // 1 sec var CCP_ACK_TIMEOUT = 3000; // 3 sec var CCP_LOAD_TIMEOUT = 5000; // 5 sec var CSM_IFRAME_REFRESH_ATTEMPTS = 'IframeRefreshAttempts'; var CSM_IFRAME_INITIALIZATION_SUCCESS = 'IframeInitializationSuccess'; var CSM_IFRAME_INITIALIZATION_TIME = 'IframeInitializationTime'; connect.globalResiliency._downloadCCPLogs = function () { connect.core.getEventBus().trigger(connect.EventType.DOWNLOAD_LOG_FROM_CCP); }; connect.globalResiliency._initializeActiveRegion = function (grProxyConduit, region) { // agentDataProvider needs to be reinitialized in order to avoid side effects from the drastic agent snapshot change try { if (region) { var _connect$core$agentDa; (_connect$core$agentDa = connect.core.agentDataProvider) === null || _connect$core$agentDa === void 0 || _connect$core$agentDa.destroy(); if (!connect.core.agentDataProvider) connect.core.agentDataProvider = new connect.core.AgentDataProvider(connect.core.getEventBus());else connect.core.agentDataProviderBackup = new connect.core.AgentDataProvider(connect.core.getEventBus()); grProxyConduit.getActiveConduit().sendUpstream(connect.AgentEvents.FETCH_AGENT_DATA_FROM_CCP); } } catch (e) { connect.getLog().error('[GR] There was an error reinitializing the agent data provider.').withException(e).sendInternalLogToServer(); connect.publishMetric({ name: 'GlobalResiliencySwitchRegionAgentDataProviderFailure', data: { count: 1 } }); } // Set one to the connect.core.keepaliveManager just in case for backward compatibility, but most likely it won't be used. connect.core.keepaliveManager = grProxyConduit.getActiveConduit().keepaliveManager; connect.core.client = new connect.UpstreamConduitClient(grProxyConduit.getActiveConduit()); connect.core.masterClient = new connect.UpstreamConduitMasterClient(grProxyConduit.getActiveConduit()); connect.core.mediaFactory = new connect.MediaFactory(_objectSpread(_objectSpread({}, connect.globalResiliency.params), {}, { ccpUrl: grProxyConduit.getActiveConduit().name })); // Because normal flow is initCCP > init softphone manager, // it is possible the softphone manager was not yet initialized try { var _connect$core; if ((_connect$core = connect.core) !== null && _connect$core !== void 0 && _connect$core.softphoneManager) { connect.getLog().info('[GR] Refreshing softphone manager RTC peer connection manager.').sendInternalLogToServer(); connect.core.softphoneManager._initiateRtcPeerConnectionManager(); } else { connect.getLog().info('[GR] Softphone manager not initialized or not used, not refreshing softphone manager.').sendInternalLogToServer(); } } catch (e) { connect.getLog().error('[GR] There was an error refreshing the softphone manager.').withException(e).sendInternalLogToServer(); connect.publishMetric({ name: 'GlobalResiliencySwitchRegionWebRTCFailure', data: { count: 1 } }); } if (region) { connect.globalResiliency._activeRegion = region; if (connect.ChatSession) { if (connect.ChatSession.setRegionOverride) { connect.getLog().info("[GR] Updating ChatJS region to ".concat(region)).sendInternalLogToServer(); connect.ChatSession.setRegionOverride(region); } else { connect.getLog().warn("[GR] ChatJS present, but setRegionOverride not found. Consider updating to latest ChatJS version").sendInternalLogToServer(); } } else { connect.getLog().info('[GR] ChatJS not present, not updating ChatSession region.').sendInternalLogToServer(); } } grProxyConduit.getActiveConduit().sendUpstream(connect.GlobalResiliencyEvents.CONFIGURE_CCP_CONDUIT, { instanceState: 'active' }); grProxyConduit.getInactiveConduit().sendUpstream(connect.GlobalResiliencyEvents.CONFIGURE_CCP_CONDUIT, { instanceState: 'inactive' }); try { connect.core._showIframe(grProxyConduit.getActiveConduit().iframe); connect.core._hideIframe(grProxyConduit.getInactiveConduit().iframe); } catch (e) { connect.getLog().error('[GR] There was an error updating the IFrame visibility.').withException(e).sendInternalLogToServer(); connect.publishMetric({ name: 'GlobalResiliencySwitchRegionIFrameSwapFailure', data: { count: 1 } }); } try { var label = grProxyConduit.iframeLabelMap[grProxyConduit.getActiveConduit().name]; connect.getLog().info("[GR] Setting provider active region to ".concat(label)).sendInternalLogToServer(); connect.core._amazonConnectProviderData.provider.setActiveRegion(label); } catch (err) { connect.getLog().error('[GR] Setting active region for provider failed.').withException(err).sendInternalLogToServer(); } }; connect.globalResiliency._switchActiveRegion = function (grProxyConduit, newActiveConduitName) { var _grProxyConduit$getAc, _grProxyConduit$getAc2, _connect$core2, _grProxyConduit$getAc3, _grProxyConduit$getAc4; if (!(grProxyConduit instanceof connect.GRProxyIframeConduit)) { connect.getLog().error('[GR] Tried to switch over active region, but proxy conduit was not of expected type.').withObject({ type: _typeof(grProxyConduit) }).sendInternalLogToServer(); return false; } var newActiveConduit = grProxyConduit.getConduitByName(newActiveConduitName); if (!(newActiveConduit instanceof connect.IFrameConduit)) { connect.getLog().error('[GR] Tried to switch over active region, but conduit name was invalid').withObject({ newActiveConduitName: newActiveConduitName }).sendInternalLogToServer(); return false; } if (grProxyConduit.getActiveConduit().name === newActiveConduit.name && connect.globalResiliency._activeRegion === newActiveConduit.region) { connect.getLog().info('[GR] Not switching over active region as we are already on active region.').sendInternalLogToServer(); return false; } connect.getLog().info("[GR] Switching active region from ".concat((_grProxyConduit$getAc = grProxyConduit.getActiveConduit()) === null || _grProxyConduit$getAc === void 0 ? void 0 : _grProxyConduit$getAc.region, " / ").concat((_grProxyConduit$getAc2 = grProxyConduit.getActiveConduit()) === null || _grProxyConduit$getAc2 === void 0 ? void 0 : _grProxyConduit$getAc2.name, " to ").concat(newActiveConduit === null || newActiveConduit === void 0 ? void 0 : newActiveConduit.region, " / ").concat(newActiveConduit === null || newActiveConduit === void 0 ? void 0 : newActiveConduit.name)).sendInternalLogToServer(); // We need to clear all sessions now as it is not guarenteed that a snapshot informing // the softphone manager that the contact is ended will be received before the failover occurrs (_connect$core2 = connect.core) === null || _connect$core2 === void 0 || (_connect$core2 = _connect$core2.softphoneManager) === null || _connect$core2 === void 0 || _connect$core2._clearAllSessions(); grProxyConduit.setActiveConduit(newActiveConduit.name); connect.globalResiliency._initializeActiveRegion(grProxyConduit, newActiveConduit.region); connect.getLog().info("[GR] Switched active region to ".concat((_grProxyConduit$getAc3 = grProxyConduit.getActiveConduit()) === null || _grProxyConduit$getAc3 === void 0 ? void 0 : _grProxyConduit$getAc3.region, " / ").concat((_grProxyConduit$getAc4 = grProxyConduit.getActiveConduit()) === null || _grProxyConduit$getAc4 === void 0 ? void 0 : _grProxyConduit$getAc4.name)).sendInternalLogToServer(); connect.publishMetric({ name: 'CalledInternalSwitchActiveRegionSuccessful', data: { count: 1 } }); return true; }; connect.globalResiliency.initGRCCP = function (containerDiv, paramsIn) { // Legacy auth flow must be enabled for now to allow GR to work var params = _objectSpread({}, paramsIn); connect.globalResiliency.params = params; var conduitTimerContainerMap = {}; var hasSentFailoverPending = false; connect.globalResiliency._activeRegion = null; connect.globalResiliency.globalResiliencyEnabled = true; var LAST_FAILOVER_PENDING_TIME; var LAST_FAILOVER_INITIATED_TIME; var LAST_FAILOVER_COMPLETED_TIME; connect.core.checkNotInitialized(); if (connect.core.initialized) { return; } // The initialization metric works only for the active region connect.getLog().info('[GR] Iframe initialization started').sendInternalLogToServer(); var initStartTime = Date.now(); connect.assertNotNull(containerDiv, 'containerDiv'); var primaryURLOrigin = new URL(params.ccpUrl).origin; var secondaryURLOrigin = new URL(params.secondaryCCPUrl).origin; var primaryIframe = connect.core._createCCPIframe(containerDiv, _objectSpread(_objectSpread({}, params), {}, { globalResiliencyRegion: 'primary' }), primaryURLOrigin); var secondaryIframe = connect.core._createCCPIframe(containerDiv, _objectSpread(_objectSpread({}, params), {}, { ccpUrl: params.secondaryCCPUrl, globalResiliencyRegion: 'secondary' }), secondaryURLOrigin); // Create an upstream conduit communicating with all the CCP iframes. // This is a sort of a multiplexer of all upstream conduits, i.e. // - connect.core.upstream.sendUpstream(msg) will postMessage to all iframes // - connect.core.upstream.onUpstream(event, f) will register a callback to be invoked when one of the iframes postMessages us var grProxyConduit = new connect.GRProxyIframeConduit(window, [{ iframe: primaryIframe, label: 'primary' }, { iframe: secondaryIframe, label: 'secondary' }], primaryIframe.src); connect.core.upstream = grProxyConduit; // Initialize the core event bus. The event subscriptions never get lost after failover connect.core.eventBus = new connect.EventBus({ logEvents: false }); connect.globalResiliency._initializeActiveRegion(grProxyConduit); connect.publishMetric({ name: 'InitGlobalResiliencyCCPCalled', data: { count: 1 } }); // Let each CCP know if the iframe is visible to users or not grProxyConduit.getAllConduits().forEach(function (conduit) { connect.core._sendIframeStyleDataUpstreamAfterReasonableWaitTime(conduit.iframe, conduit); }); // Initialize websocket provider that exchanges websocket specific events with the shared worker. // It receives messages only from the active conduit. // It sends messages only to active condit, except for topic subscription so that inactive regions' media channels can be initialized. connect.core.webSocketProvider = new connect.WebSocketProvider(); // Bridge all events sent from upstream to the core event bus. // However most of events from inactive conduits are ignored. grProxyConduit.onAllUpstream(connect.core.getEventBus().bridge()); // Initialize a keep alive manager for each conduit, that sends back a SYN event in response to ACK event from its shared worker grProxyConduit.getAllConduits().forEach(function (conduit) { // set it to conduit for later use conduit.keepaliveManager = new connect.KeepaliveManager(conduit, connect.core.getEventBus(), params.ccpSynTimeout || CCP_SYN_TIMEOUT, params.ccpAckTimeout || CCP_ACK_TIMEOUT); }); // The CRM layer CCP logs are sent to each CCP connect.getLog().scheduleUpstreamOuterContextCCPLogsPush(grProxyConduit); connect.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(grProxyConduit); // After switching over, we need to grab the agent data of the new CCP grProxyConduit.onUpstream(connect.AgentEvents.FETCH_AGENT_DATA_FROM_CCP, function (agentData) { if (connect.core.agentDataProviderBackup) { connect.core.agentDataProviderBackup.updateAgentData(agentData); connect.core.agentDataProvider = connect.core.agentDataProviderBackup; connect.core.agentDataProviderBackup = null; } else { connect.core.agentDataProvider.updateAgentData(agentData); } connect.getLog().info('[GR] Fetched agent data from CCP.').sendInternalLogToServer(); }); // Trigger ACK_TIMEOUT event if there's no ACK from the primary CCP for 5 sec. // Ignore and just emit a log for non-primary CCPs. grProxyConduit.getAllConduits().forEach(function (conduit) { conduitTimerContainerMap[conduit.name] = { iframeRefreshTimeout: null }; conduitTimerContainerMap[conduit.name].ccpLoadTimeoutInstance = setTimeout(function () { conduitTimerContainerMap[conduit.name].ccpLoadTimeoutInstance = null; if (connect.isActiveConduit(conduit)) { connect.core.getEventBus().trigger(connect.EventType.ACK_TIMEOUT); connect.getLog().info("CCP LoadTimeout triggered. ".concat(conduit.name)).sendInternalLogToServer(); } else { connect.getLog().error("CCP LoadTimeout detected but ignored for non-primary regions. ".concat(conduit.name)).sendInternalLogToServer(); } }, params.ccpLoadTimeout || CCP_LOAD_TIMEOUT); }); // Listen to the first ACK event sent from each conduit. grProxyConduit.getAllConduits().forEach(function (conduit) { conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { connect.getLog().info("Acknowledged by the CCP! ".concat(conduit.name)).sendInternalLogToServer(); var isACGR = true; connect.core.sendConfigure(params, conduit, isACGR); connect.core.listenForConfigureRequest(params, conduit, isACGR); // fallback in case of abnormal CCP refresh // Clear the load timeout timer if (conduitTimerContainerMap[conduit.name].ccpLoadTimeoutInstance) { global.clearTimeout(conduitTimerContainerMap[conduit.name].ccpLoadTimeoutInstance); conduitTimerContainerMap[conduit.name].ccpLoadTimeoutInstance = null; } // Send outer context info to each CCP conduit.sendUpstream(connect.EventType.OUTER_CONTEXT_INFO, { streamsVersion: connect.version, initCCPParams: params }); var _ref = params.loginOptions || {}, enableAckTimeout = _ref.enableAckTimeout; if (enableAckTimeout) { conduit.keepaliveManager.enableAckTimeout(enableAckTimeout); } conduit.keepaliveManager.start(); if (connect.isActiveConduit(conduit)) { // Only active conduit initialize these since we only need one instance connect.core.client = new connect.UpstreamConduitClient(conduit); connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); connect.core.portStreamId = data.id; // We should update this at failover // Only active conduit emits these metircs since we don't allow non-active conduits to broadcast events if (initStartTime) { var initTime = Date.now() - initStartTime; var refreshAttempts = conduitTimerContainerMap[conduit.name].iframeRefreshAttempt || 0; connect.getLog().info('Iframe initialization succeeded').sendInternalLogToServer(); connect.getLog().info("Iframe initialization time ".concat(initTime)).sendInternalLogToServer(); connect.getLog().info("Iframe refresh attempts ".concat(refreshAttempts)).sendInternalLogToServer(); setTimeout(function () { connect.publishMetric({ name: CSM_IFRAME_REFRESH_ATTEMPTS, data: { count: refreshAttempts } }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_SUCCESS, data: { count: 1 } }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_TIME, data: { count: initTime } }); // to avoid metric emission after initialization initStartTime = null; }, 1000); } } conduit.portStreamId = data.id; // keep this id for future failover this.unsubscribe(); }); }); // Add logs from the active upstream conduit to our own logger. grProxyConduit.onUpstream(connect.EventType.LOG, function (logEntry) { if (logEntry.loggerId !== connect.getLog().getLoggerId()) { connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); } }); // Pop a login page when we encounter an ACK_TIMEOUT event. // The event can only be triggered from active region. connect.core.getEventBus().subscribe(connect.EventType.ACK_TIMEOUT, function () { // loginPopup is true by default, only false if explicitly set to false. if (params.loginPopup !== false) { try { // For GR, we assume getLoginUrl() always returns the loginUrl for global sign-in page. // LoginUrl existence was checked before calling initGRCCP var loginUrl = params.loginUrl; connect.getLog().warn('ACK_TIMEOUT occurred, attempting to pop the login page if not already open.').sendInternalLogToServer(); // clear out last opened timestamp for SAML authentication when there is ACK_TIMEOUT connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); connect.core._openPopupWithLock(loginUrl, params.loginOptions); } catch (e) { connect.getLog().error('ACK_TIMEOUT occurred but we are unable to open the login popup.').withException(e).sendInternalLogToServer(); } } // Start iframe refresh for each region's CCP grProxyConduit.getAllConduits().forEach(function (conduit) { if (conduitTimerContainerMap[conduit.name].iframeRefreshTimeout === null) { try { // Stop the iframe refresh when ACK event is sent from upstream conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { this.unsubscribe(); global.clearTimeout(conduitTimerContainerMap[conduit.name].iframeRefreshTimeout); conduitTimerContainerMap[conduit.name].iframeRefreshTimeout = null; connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); if ((params.loginPopupAutoClose || params.loginOptions && params.loginOptions.autoClose) && connect.core.loginWindow) { connect.core.loginWindow.close(); connect.core.loginWindow = null; } }); // Kick off the iframe refresh connect.core._refreshIframeOnTimeout(_objectSpread(_objectSpread({}, params), {}, { ccpUrl: conduit.iframe.src }), containerDiv, conduitTimerContainerMap[conduit.name], conduit.name); } catch (e) { connect.getLog().error('Error occurred while refreshing iframe').withException(e).sendInternalLogToServer(); } } }); }); grProxyConduit.getAllConduits().forEach(function (conduit) { conduit.onUpstream(connect.GlobalResiliencyEvents.INIT, function (data) { if (!(data !== null && data !== void 0 && data.instanceRegion) || !(data !== null && data !== void 0 && data.instanceState) || !(data !== null && data !== void 0 && data.activeRegion)) { connect.getLog().error("[GR] Expected GlobalResiliencyEvents.INIT to have instance region, state, and current active region, but did not find it.").withObject({ data: data }).sendInternalLogToServer(); return; } connect.getLog().info("[GR] Received GlobalResiliencyEvents.INIT indicating ".concat(conduit.name, " in region ").concat(data === null || data === void 0 ? void 0 : data.instanceRegion, " is ").concat(data === null || data === void 0 ? void 0 : data.instanceState, ".")).withObject({ data: data }).sendInternalLogToServer(); var initialConduit = data.instanceRegion === data.activeRegion ? conduit : grProxyConduit.getOtherConduit(conduit); if (!conduit.region || !initialConduit.region) { conduit.region = data.instanceRegion; initialConduit.region = data.activeRegion; } conduit.sendUpstream(connect.GlobalResiliencyEvents.CONFIGURE_CCP_CONDUIT, { instanceState: data.instanceState }); if (!connect.core.initialized) { connect.getLog().info("[GR] Setting initial active iframe to ".concat(initialConduit.name, " in region ").concat(initialConduit.region, " because the instance state was active")).sendInternalLogToServer(); try { connect.globalResiliency._switchActiveRegion(grProxyConduit, initialConduit.name); connect.publishMetric({ name: 'GlobalResiliencySwitchRegionSuccess', data: { count: 1 } }); } catch (e) { connect.getLog().error("[GR] Failure switching active region at initialization.").withException(e).sendInternalLogToServer(); connect.publishMetric({ name: 'GlobalResiliencySwitchRegionFailure', data: { count: 1 } }); } connect.core.getEventBus().trigger(connect.EventType.INIT); connect.core.initialized = true; // We do no trigger FAILOVER_COMPLETE here as that should only be triggered after initiaization connect.publishMetric({ name: 'GlobalResiliencyCoreInitialized', data: { count: 1 } }); } else { connect.getLog().log("[GR] Deduping GlobalResiliencyEvents.INIT - Core is already initialized.").sendInternalLogToServer(); } }); conduit.onUpstream(connect.GlobalResiliencyEvents.FAILOVER_INITIATED, function (data) { LAST_FAILOVER_INITIATED_TIME = Date.now(); connect.publishMetric({ name: 'GlobalResiliencyFailoverInitiatedReceived', data: { count: 1 } }); if (hasSentFailoverPending) { connect.publishMetric({ name: 'GlobalResiliencyPendingToInitiatedLatency', data: { latency: LAST_FAILOVER_INITIATED_TIME - LAST_FAILOVER_PENDING_TIME } }); } if (!(data !== null && data !== void 0 && data.activeRegion)) { connect.getLog().error("[GR] Expected GlobalResiliencyEvents.FAILOVER_INITIATED to have new active region, but did not find it.").withObject({ data: data }).sendInternalLogToServer(); return; } connect.getLog().info("[GR] Received GlobalResiliencyEvents.FAILOVER_INITIATED indicating the activeRegion is ".concat(data.activeRegion, ".")); var newActiveConduit = grProxyConduit.getConduitByRegion(data.activeRegion); if (!newActiveConduit) { connect.getLog().debug("[GR] A conduit did not received GLOBAL_RESILIENCY.INIT event, leading to the region field being unpopulated."); grProxyConduit.getAllConduits().forEach(function (searchConduit) { if (searchConduit.region === undefined || searchConduit.region === null) { searchConduit.region = data.activeRegion; newActiveConduit = searchConduit; } }); } var didSwitch; try { didSwitch = connect.globalResiliency._switchActiveRegion(grProxyConduit, newActiveConduit.name); connect.publishMetric({ name: 'GlobalResiliencySwitchRegionSuccess', data: { count: 1 } }); } catch (e) { connect.getLog().error("[GR] Failure switching active region.").withException(e).sendInternalLogToServer(); connect.publishMetric({ name: 'GlobalResiliencySwitchRegionFailure', data: { count: 1 } }); } if (didSwitch) { hasSentFailoverPending = false; var agentUpdateSub = grProxyConduit.onUpstream(connect.AgentEvents.UPDATE, function () { agentUpdateSub.unsubscribe(); connect.core.getEventBus().trigger(connect.GlobalResiliencyEvents.FAILOVER_COMPLETE, { activeRegion: data.activeRegion }); grProxyConduit.sendUpstream(connect.GlobalResiliencyEvents.FAILOVER_COMPLETE); connect.getLog().info("[GR] GlobalResiliencyEvents.FAILOVER_COMPLETE emitted.").sendInternalLogToServer(); LAST_FAILOVER_COMPLETED_TIME = Date.now(); connect.publishMetric({ name: 'GlobalResiliencyFailoverCompleted', data: { count: 1 } }); connect.publishMetric({ name: 'GlobalResiliencyInitiatedToCompletedLatency', data: { latency: LAST_FAILOVER_COMPLETED_TIME - LAST_FAILOVER_INITIATED_TIME } }); }); } }); }); // Not clear what this is about. Probably for backward compatibilty for pre-StreamsJS customers if (params.onViewContact) { connect.core.onViewContact(params.onViewContact); } // Update the numberOfConnectedCCPs value when sent from upstream. // On CRM layer, this information is not used by any other component in Streams. grProxyConduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { connect.numberOfConnectedCCPs = data.length; }); // Update and cache the voiceIdDomainId value when sent from each upstream conduit. // The value needs to be updated when switching the active region as each region might have a different VoiceId domain associated. grProxyConduit.getAllConduits().forEach(function (conduit) { conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { if (data && data.domainId) { conduit.voiceIdDomainId = data.domainId; if (connect.isActiveConduit(conduit)) { connect.core.voiceIdDomainId = data.domainId; } } }); }); connect.core.getEventBus().subscribe(connect.EventType.IFRAME_RETRIES_EXHAUSTED, function (conduitName) { if (conduitName !== grProxyConduit.getActiveConduit().name) { // Ignore IFRAME_RETRIES_EXHAUSTED event from non-active region return; } if (initStartTime) { var refreshAttempts = conduitTimerContainerMap[grProxyConduit.getActiveConduit().name].iframeRefreshAttempt - 1; connect.getLog().info('Iframe initialization failed').sendInternalLogToServer(); connect.getLog().info("Time after iframe initialization started ".concat(Date.now() - initStartTime)).sendInternalLogToServer(); connect.getLog().info("Iframe refresh attempts ".concat(refreshAttempts)).sendInternalLogToServer(); connect.publishMetric({ name: CSM_IFRAME_REFRESH_ATTEMPTS, data: { count: refreshAttempts } }); connect.publishMetric({ name: CSM_IFRAME_INITIALIZATION_SUCCESS, data: { count: 0 } }); initStartTime = null; } }); // keep the softphone params for external use connect.core.softphoneParams = params.softphone; grProxyConduit.getAllConduits().forEach(function (conduit) { conduit.onUpstream(connect.GlobalResiliencyEvents.FAILOVER_PENDING, function (data) { if (!connect.isActiveConduit(conduit)) { return; } if (hasSentFailoverPending) { connect.getLog().info("[GR] Received FAILOVER_PENDING - deduping, will not trigger event subscription.").withObject({ data: data }).sendInternalLogToServer(); return; } connect.getLog().info("[GR] Received FAILOVER_PENDING").withObject({ data: data }).sendInternalLogToServer(); connect.core.getEventBus().trigger(connect.GlobalResiliencyEvents.FAILOVER_PENDING_CRM, { nextActiveRegion: data.activeRegion }); hasSentFailoverPending = true; LAST_FAILOVER_PENDING_TIME = Date.now(); connect.publishMetric({ name: 'GlobalResiliencyFailoverPendingReceived', data: { count: 1 } }); }); }); grProxyConduit.relayUpstream(connect.GlobalResiliencyEvents.FAILOVER_PENDING); grProxyConduit.relayUpstream(connect.GlobalResiliencyEvents.FAILOVER_INITIATED); grProxyConduit.relayUpstream(connect.GlobalResiliencyEvents.FAILOVER_COMPLETE); grProxyConduit.relayUpstream(connect.GlobalResiliencyEvents.HEARTBEAT_SYN); grProxyConduit.relayUpstream(connect.GlobalResiliencyEvents.HEARTBEAT_ACK); connect.core.getEventBus().subscribe(connect.EventType.DOWNLOAD_LOG_FROM_CCP, function () { grProxyConduit.getAllConduits().forEach(function (conduit) { var region = conduit.region || 'region'; conduit.sendUpstream(connect.EventType.DOWNLOAD_LOG_FROM_CCP, { logName: "ccp-".concat(region, "-agent-log") }); }); }); setTimeout(function () { var count = 0; grProxyConduit.getAllConduits().forEach(function (conduit) { if (conduit.region) { count += 1; } }); if (count < 2) { connect.getLog().info("[GR] One or more conduits did not GlobalResiliency.INIT event to CRM layer.").withObject({ firstConduitName: grProxyConduit.getAllConduits()[0].name, firstConduitRegion: grProxyConduit.getAllConduits()[0].region, secondConduitName: grProxyConduit.getAllConduits()[1].name, secondConduitRegion: grProxyConduit.getAllConduits()[1].region }).sendInternalLogToServer(); connect.publishMetric({ name: 'GlobalResiliencyPartialInitialization', data: { count: 1 } }); } }, 30000); }; })(); /***/ }), /***/ 95: /***/ (() => { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } !function (e) { var n = {}; function t(o) { if (n[o]) return n[o].exports; var r = n[o] = { i: o, l: !1, exports: {} }; return e[o].call(r.exports, r, r.exports, t), r.l = !0, r.exports; } t.m = e, t.c = n, t.d = function (e, n, o) { t.o(e, n) || Object.defineProperty(e, n, { enumerable: !0, get: o }); }, t.r = function (e) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e, "__esModule", { value: !0 }); }, t.t = function (e, n) { if (1 & n && (e = t(e)), 8 & n) return e; if (4 & n && "object" == _typeof(e) && e && e.__esModule) return e; var o = Object.create(null); if (t.r(o), Object.defineProperty(o, "default", { enumerable: !0, value: e }), 2 & n && "string" != typeof e) for (var r in e) t.d(o, r, function (n) { return e[n]; }.bind(null, r)); return o; }, t.n = function (e) { var n = e && e.__esModule ? function () { return e["default"]; } : function () { return e; }; return t.d(n, "a", n), n; }, t.o = function (e, n) { return Object.prototype.hasOwnProperty.call(e, n); }, t.p = "", t(t.s = 2); }([function (e, n, t) { "use strict"; var o = t(1), r = "NULL", i = "CLIENT_LOGGER", c = "DEBUG", a = 2e3, s = "AMZ_WEB_SOCKET_MANAGER:", u = "Network offline", l = "Network online, connecting to WebSocket server", f = "Network offline, ignoring this getWebSocketConnConfig request", d = "Heartbeat response not received", p = "Heartbeat response received", g = "Sending heartbeat", b = "Failed to send heartbeat since WebSocket is not open", y = "WebSocket connection established!", m = "WebSocket connection is closed", v = "WebSocketManager Error, error_event: ", S = "Scheduling WebSocket reinitialization, after delay ", h = "WebSocket URL cannot be used to establish connection", k = "WebSocket Initialization failed - Terminating and cleaning subscriptions", w = "Terminating WebSocket Manager", C = "Fetching new WebSocket connection configuration", L = "Successfully fetched webSocket connection configuration", T = "Failed to fetch webSocket connection configuration", O = "Retrying fetching new WebSocket connection configuration", W = "Initializing Websocket Manager", I = "Initializing Websocket Manager Failed!", N = "Websocket connection open", _ = "Websocket connection close", E = "Websocket connection gain", F = "Websocket connection lost", A = "Websocket subscription failure", R = "Reset Websocket state", x = "WebSocketManager Message Error", D = "Message received for topic ", j = "Invalid incoming message", M = "WebsocketManager invoke callbacks for topic success ", G = "aws/subscribe", z = "aws/unsubscribe", P = "aws/heartbeat", H = "connected", U = "disconnected"; function q(e) { return (q = "function" == typeof Symbol && "symbol" == _typeof(Symbol.iterator) ? function (e) { return _typeof(e); } : function (e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : _typeof(e); })(e); } var J = { assertTrue: function assertTrue(e, n) { if (!e) throw new Error(n); }, assertNotNull: function assertNotNull(e, n) { return J.assertTrue(null !== e && void 0 !== q(e), Object(o.sprintf)("%s must be provided", n || "A value")), e; }, isNonEmptyString: function isNonEmptyString(e) { return "string" == typeof e && e.length > 0; }, assertIsList: function assertIsList(e, n) { if (!Array.isArray(e)) throw new Error(n + " is not an array"); }, isFunction: function isFunction(e) { return !!(e && e.constructor && e.call && e.apply); }, isObject: function isObject(e) { return !("object" !== q(e) || null === e); }, isString: function isString(e) { return "string" == typeof e; }, isNumber: function isNumber(e) { return "number" == typeof e; } }, B = new RegExp("^(wss://)\\w*"); J.validWSUrl = function (e) { return B.test(e); }, J.getSubscriptionResponse = function (e, n, t) { return { topic: e, content: { status: n ? "success" : "failure", topics: t } }; }, J.assertIsObject = function (e, n) { if (!J.isObject(e)) throw new Error(n + " is not an object!"); }, J.addJitter = function (e) { var n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1; n = Math.min(n, 1); var t = Math.random() > .5 ? 1 : -1; return Math.floor(e + t * e * Math.random() * n); }, J.isNetworkOnline = function () { return navigator.onLine; }, J.isNetworkFailure = function (e) { return !(!e._debug || !e._debug.type) && "NetworkingError" === e._debug.type; }; var V = J; function X(e, n) { return !n || "object" !== Z(n) && "function" != typeof n ? function (e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }(e) : n; } function $(e) { return ($ = Object.setPrototypeOf ? Object.getPrototypeOf : function (e) { return e.__proto__ || Object.getPrototypeOf(e); })(e); } function K(e, n) { return (K = Object.setPrototypeOf || function (e, n) { return e.__proto__ = n, e; })(e, n); } function Z(e) { return (Z = "function" == typeof Symbol && "symbol" == _typeof(Symbol.iterator) ? function (e) { return _typeof(e); } : function (e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : _typeof(e); })(e); } function Q(e, n) { if (!(e instanceof n)) throw new TypeError("Cannot call a class as a function"); } function Y(e, n) { for (var t = 0; t < n.length; t++) { var o = n[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o); } } function ee(e, n, t) { return n && Y(e.prototype, n), t && Y(e, t), e; } var ne = function () { function e() { Q(this, e); } return ee(e, [{ key: "debug", value: function value(e) {} }, { key: "info", value: function value(e) {} }, { key: "warn", value: function value(e) {} }, { key: "error", value: function value(e) {} }, { key: "advancedLog", value: function value(e) {} }]), e; }(), te = s, oe = { DEBUG: 10, INFO: 20, WARN: 30, ERROR: 40, ADVANCED_LOG: 50 }, re = function () { function e() { Q(this, e), this.updateLoggerConfig(), this.consoleLoggerWrapper = ae(); } return ee(e, [{ key: "writeToClientLogger", value: function value(e, n) { if (this.hasClientLogger()) switch (e) { case oe.DEBUG: return this._clientLogger.debug(n) || n; case oe.INFO: return this._clientLogger.info(n) || n; case oe.WARN: return this._clientLogger.warn(n) || n; case oe.ERROR: return this._clientLogger.error(n) || n; case oe.ADVANCED_LOG: return this._advancedLogWriter ? this._clientLogger[this._advancedLogWriter](n) || n : ""; } } }, { key: "isLevelEnabled", value: function value(e) { return e >= this._level; } }, { key: "hasClientLogger", value: function value() { return null !== this._clientLogger; } }, { key: "getLogger", value: function value(e) { var n = e.prefix || te; return this._logsDestination === c ? this.consoleLoggerWrapper : new ce(n); } }, { key: "updateLoggerConfig", value: function value(e) { var n = e || {}; this._level = n.level || oe.INFO, this._advancedLogWriter = "warn", n.advancedLogWriter && (this._advancedLogWriter = n.advancedLogWriter), n.customizedLogger && "object" === Z(n.customizedLogger) && (this.useClientLogger = !0), this._clientLogger = n.logger || this.selectLogger(n), this._logsDestination = r, n.debug && (this._logsDestination = c), n.logger && (this._logsDestination = i); } }, { key: "selectLogger", value: function value(e) { return e.customizedLogger && "object" === Z(e.customizedLogger) ? e.customizedLogger : e.useDefaultLogger ? (this.consoleLoggerWrapper = ae(), this.consoleLoggerWrapper) : null; } }]), e; }(), ie = function () { function e() { Q(this, e); } return ee(e, [{ key: "debug", value: function value() {} }, { key: "info", value: function value() {} }, { key: "warn", value: function value() {} }, { key: "error", value: function value() {} }, { key: "advancedLog", value: function value() {} }]), e; }(), ce = function (e) { function n(e) { var t; return Q(this, n), (t = X(this, $(n).call(this))).prefix = e || te, t; } return function (e, n) { if ("function" != typeof n && null !== n) throw new TypeError("Super expression must either be null or a function"); e.prototype = Object.create(n && n.prototype, { constructor: { value: e, writable: !0, configurable: !0 } }), n && K(e, n); }(n, ie), ee(n, [{ key: "debug", value: function value() { for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; return this._log(oe.DEBUG, n); } }, { key: "info", value: function value() { for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; return this._log(oe.INFO, n); } }, { key: "warn", value: function value() { for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; return this._log(oe.WARN, n); } }, { key: "error", value: function value() { for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; return this._log(oe.ERROR, n); } }, { key: "advancedLog", value: function value() { for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; return this._log(oe.ADVANCED_LOG, n); } }, { key: "_shouldLog", value: function value(e) { return se.hasClientLogger() && se.isLevelEnabled(e); } }, { key: "_writeToClientLogger", value: function value(e, n) { return se.writeToClientLogger(e, n); } }, { key: "_log", value: function value(e, n) { if (this._shouldLog(e)) { var t = se.useClientLogger ? n : this._convertToSingleStatement(n, e); return this._writeToClientLogger(e, t); } } }, { key: "_convertToSingleStatement", value: function value(e, n) { var t = new Date(Date.now()).toISOString(), o = this._getLogLevelByValue(n), r = "[".concat(t, "][").concat(o, "]"); this.prefix && (r += this.prefix + " "), this.options && (this.options.prefix ? r += " " + this.options.prefix + ":" : r += "", this.options.logMetaData ? r += " Meta data: " + JSON.stringify(this.options.logMetaData) : r += ""); for (var i = 0; i < e.length; i++) { var c = e[i]; r += this._convertToString(c) + " "; } return r; } }, { key: "_getLogLevelByValue", value: function value(e) { switch (e) { case 10: return "DEBUG"; case 20: return "INFO"; case 30: return "WARN"; case 40: return "ERROR"; case 50: return "ADVANCED_LOG"; } } }, { key: "_convertToString", value: function value(e) { try { if (!e) return ""; if (V.isString(e)) return e; if (V.isObject(e) && V.isFunction(e.toString)) { var n = e.toString(); if ("[object Object]" !== n) return n; } return JSON.stringify(e); } catch (n) { return console.error("Error while converting argument to string", e, n), ""; } } }]), n; }(), ae = function ae() { var e = new ie(); return e.debug = function () { for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; return console.debug.apply(window.console, [].concat(n)); }, e.info = function () { for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; return console.info.apply(window.console, [].concat(n)); }, e.warn = function () { for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; return console.warn.apply(window.console, [].concat(n)); }, e.error = function () { for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; return console.error.apply(window.console, [].concat(n)); }, e; }, se = new re(); function ue(e, n) { for (var t = 0; t < n.length; t++) { var o = n[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o); } } var le = function () { function e(n) { var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : a; !function (e, n) { if (!(e instanceof n)) throw new TypeError("Cannot call a class as a function"); }(this, e), this.numAttempts = 0, this.executor = n, this.hasActiveReconnection = !1, this.defaultRetry = t; } var n, t, o; return n = e, (t = [{ key: "retry", value: function value() { var e = this; this.hasActiveReconnection || (this.hasActiveReconnection = !0, setTimeout(function () { e._execute(); }, this._getDelay())); } }, { key: "_execute", value: function value() { this.hasActiveReconnection = !1, this.executor(), this.numAttempts++; } }, { key: "connected", value: function value() { this.numAttempts = 0; } }, { key: "_getDelay", value: function value() { var e = Math.pow(2, this.numAttempts) * this.defaultRetry; return e <= 3e4 ? e : 3e4; } }, { key: "getIsConnected", value: function value() { return !this.numAttempts; } }]) && ue(n.prototype, t), o && ue(n, o), e; }(); t.d(n, "a", function () { return de; }); var fe = function fe() { var e = se.getLogger({ prefix: s }), n = V.isNetworkOnline(), t = { primary: null, secondary: null }, o = { reconnectWebSocket: !0, websocketInitFailed: !1, exponentialBackOffTime: 1e3, exponentialTimeoutHandle: null, lifeTimeTimeoutHandle: null, webSocketInitCheckerTimeoutId: null, connState: null }, r = { connectWebSocketRetryCount: 0, connectionAttemptStartTime: null, noOpenConnectionsTimestamp: null }, i = { pendingResponse: !1, intervalHandle: null }, c = { initFailure: new Set(), getWebSocketTransport: null, subscriptionUpdate: new Set(), subscriptionFailure: new Set(), topic: new Map(), allMessage: new Set(), connectionGain: new Set(), connectionLost: new Set(), connectionOpen: new Set(), connectionClose: new Set() }, a = { connConfig: null, promiseHandle: null, promiseCompleted: !0 }, q = { subscribed: new Set(), pending: new Set(), subscriptionHistory: new Set() }, J = { responseCheckIntervalId: null, requestCompleted: !0, reSubscribeIntervalId: null, consecutiveFailedSubscribeAttempts: 0, consecutiveNoResponseRequest: 0 }, B = new le(function () { he(); }), X = new Set([G, z, P]), $ = setInterval(function () { if (n !== V.isNetworkOnline()) { if (!(n = V.isNetworkOnline())) return e.advancedLog(u), void Ce(e.info(u)); var t = te(); n && (!t || Y(t, WebSocket.CLOSING) || Y(t, WebSocket.CLOSED)) && (e.advancedLog(l), Ce(e.info(l)), he()); } }, 250), K = function K(n, t) { n.forEach(function (n) { try { n(t); } catch (n) { Ce(e.error("Error executing callback", n)); } }); }, Z = function Z(e) { if (null === e) return "NULL"; switch (e.readyState) { case WebSocket.CONNECTING: return "CONNECTING"; case WebSocket.OPEN: return "OPEN"; case WebSocket.CLOSING: return "CLOSING"; case WebSocket.CLOSED: return "CLOSED"; default: return "UNDEFINED"; } }, Q = function Q() { var n = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : ""; Ce(e.debug("[" + n + "] Primary WebSocket: " + Z(t.primary) + " | Secondary WebSocket: " + Z(t.secondary))); }, Y = function Y(e, n) { return e && e.readyState === n; }, ee = function ee(e) { return Y(e, WebSocket.OPEN); }, ne = function ne(e) { return null === e || void 0 === e.readyState || Y(e, WebSocket.CLOSED); }, te = function te() { return null !== t.secondary ? t.secondary : t.primary; }, oe = function oe() { return ee(te()); }, re = function re() { if (i.pendingResponse) return e.advancedLog(d), Ce(e.warn(d)), clearInterval(i.intervalHandle), i.pendingResponse = !1, void he(); oe() ? (Ce(e.debug(g)), te().send(ve(P)), i.pendingResponse = !0) : (e.advancedLog(b), Ce(e.warn(b)), Q("sendHeartBeat"), he()); }, ie = function ie() { e.advancedLog(R), o.exponentialBackOffTime = 1e3, i.pendingResponse = !1, o.reconnectWebSocket = !0, clearTimeout(o.lifeTimeTimeoutHandle), clearInterval(i.intervalHandle), clearTimeout(o.exponentialTimeoutHandle), clearTimeout(o.webSocketInitCheckerTimeoutId); }, ce = function ce() { J.consecutiveFailedSubscribeAttempts = 0, J.consecutiveNoResponseRequest = 0, clearInterval(J.responseCheckIntervalId), clearInterval(J.reSubscribeIntervalId); }, ae = function ae() { r.connectWebSocketRetryCount = 0, r.connectionAttemptStartTime = null, r.noOpenConnectionsTimestamp = null; }, ue = function ue() { B.connected(); try { e.advancedLog(y), Ce(e.info(y)), Q("webSocketOnOpen"), null !== o.connState && o.connState !== U || K(c.connectionGain), o.connState = H; var n = Date.now(); K(c.connectionOpen, { connectWebSocketRetryCount: r.connectWebSocketRetryCount, connectionAttemptStartTime: r.connectionAttemptStartTime, noOpenConnectionsTimestamp: r.noOpenConnectionsTimestamp, connectionEstablishedTime: n, timeToConnect: n - r.connectionAttemptStartTime, timeWithoutConnection: r.noOpenConnectionsTimestamp ? n - r.noOpenConnectionsTimestamp : null }), ae(), ie(), te().openTimestamp = Date.now(), 0 === q.subscribed.size && ee(t.secondary) && ge(t.primary, "[Primary WebSocket] Closing WebSocket"), (q.subscribed.size > 0 || q.pending.size > 0) && (ee(t.secondary) && Ce(e.info("Subscribing secondary websocket to topics of primary websocket")), q.subscribed.forEach(function (e) { q.subscriptionHistory.add(e), q.pending.add(e); }), q.subscribed.clear(), pe()), re(), i.intervalHandle = setInterval(re, 1e4); var s = 1e3 * a.connConfig.webSocketTransport.transportLifeTimeInSeconds; Ce(e.debug("Scheduling WebSocket manager reconnection, after delay " + s + " ms")), o.lifeTimeTimeoutHandle = setTimeout(function () { Ce(e.debug("Starting scheduled WebSocket manager reconnection")), he(); }, s); } catch (n) { Ce(e.error("Error after establishing WebSocket connection", n)); } }, fe = function fe(n) { Q("webSocketOnError"), e.advancedLog(v, JSON.stringify(n)), Ce(e.error(v, JSON.stringify(n))), B.getIsConnected() ? he() : B.retry(); }, de = function de(n) { var o = JSON.parse(n.data); switch (o.topic) { case G: if (Ce(e.debug("Subscription Message received from webSocket server", n.data)), J.requestCompleted = !0, J.consecutiveNoResponseRequest = 0, "success" === o.content.status) J.consecutiveFailedSubscribeAttempts = 0, o.content.topics.forEach(function (e) { q.subscriptionHistory["delete"](e), q.pending["delete"](e), q.subscribed.add(e); }), 0 === q.subscriptionHistory.size ? ee(t.secondary) && (Ce(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")), ge(t.primary, "[Primary WebSocket] Closing WebSocket")) : pe(), K(c.subscriptionUpdate, o);else { if (clearInterval(J.reSubscribeIntervalId), ++J.consecutiveFailedSubscribeAttempts, 5 === J.consecutiveFailedSubscribeAttempts) return K(c.subscriptionFailure, o), void (J.consecutiveFailedSubscribeAttempts = 0); J.reSubscribeIntervalId = setInterval(function () { pe(); }, 500); } break; case P: Ce(e.debug(p)), i.pendingResponse = !1; break; default: if (o.topic) { if (e.advancedLog(D, o.topic), Ce(e.debug(D + o.topic)), ee(t.primary) && ee(t.secondary) && 0 === q.subscriptionHistory.size && this === t.primary) return void Ce(e.warn("Ignoring Message for Topic " + o.topic + ", to avoid duplicates")); if (0 === c.allMessage.size && 0 === c.topic.size) return void Ce(e.warn("No registered callback listener for Topic", o.topic)); e.advancedLog(M, o.topic), K(c.allMessage, o), c.topic.has(o.topic) && K(c.topic.get(o.topic), o); } else o.message ? (e.advancedLog(x, o), Ce(e.warn(x, o))) : (e.advancedLog(j, o), Ce(e.warn(j, o))); } }, pe = function n() { if (J.consecutiveNoResponseRequest > 3) return Ce(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")), void K(c.subscriptionFailure, V.getSubscriptionResponse(G, !1, Array.from(q.pending))); oe() ? 0 !== Array.from(q.pending).length && (clearInterval(J.responseCheckIntervalId), te().send(ve(G, { topics: Array.from(q.pending) })), J.requestCompleted = !1, J.responseCheckIntervalId = setInterval(function () { J.requestCompleted || (++J.consecutiveNoResponseRequest, n()); }, 1e3)) : Ce(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open")); }, ge = function ge(n, t) { Y(n, WebSocket.CONNECTING) || Y(n, WebSocket.OPEN) ? n.close(1e3, t) : Ce(e.warn("Ignoring WebSocket Close request, WebSocket State: " + Z(n))); }, be = function be(e) { ge(t.primary, "[Primary] WebSocket " + e), ge(t.secondary, "[Secondary] WebSocket " + e); }, ye = function ye() { r.connectWebSocketRetryCount++; var n = V.addJitter(o.exponentialBackOffTime, .3); Date.now() + n <= a.connConfig.urlConnValidTime ? (e.advancedLog(S), Ce(e.debug(S + n + " ms")), o.exponentialTimeoutHandle = setTimeout(function () { return ke(); }, n), o.exponentialBackOffTime *= 2) : (e.advancedLog(h), Ce(e.warn(h)), he()); }, me = function me(n) { ie(), ce(), e.advancedLog(k, n), Ce(e.error(k)), o.websocketInitFailed = !0, be(w), clearInterval($), K(c.initFailure, { connectWebSocketRetryCount: r.connectWebSocketRetryCount, connectionAttemptStartTime: r.connectionAttemptStartTime, reason: n }), ae(); }, ve = function ve(e, n) { return JSON.stringify({ topic: e, content: n }); }, Se = function Se(n) { return !!(V.isObject(n) && V.isObject(n.webSocketTransport) && V.isNonEmptyString(n.webSocketTransport.url) && V.validWSUrl(n.webSocketTransport.url) && 1e3 * n.webSocketTransport.transportLifeTimeInSeconds >= 3e5) || (Ce(e.error("Invalid WebSocket Connection Configuration", n)), !1); }, he = function he() { if (!V.isNetworkOnline()) return e.advancedLog(f), void Ce(e.info(f)); if (o.websocketInitFailed) Ce(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else { if (a.promiseCompleted) return ie(), e.advancedLog(C), Ce(e.info(C)), r.connectionAttemptStartTime = r.connectionAttemptStartTime || Date.now(), a.promiseCompleted = !1, a.promiseHandle = c.getWebSocketTransport(), a.promiseHandle.then(function (n) { return a.promiseCompleted = !0, e.advancedLog(L), Ce(e.debug(L, n)), Se(n) ? (a.connConfig = n, a.connConfig.urlConnValidTime = Date.now() + 85e3, ke()) : (me("Invalid WebSocket connection configuration: " + n), { webSocketConnectionFailed: !0 }); }, function (n) { return a.promiseCompleted = !0, e.advancedLog(T), Ce(e.error(T, n)), V.isNetworkFailure(n) ? (e.advancedLog(O + JSON.stringify(n)), Ce(e.info(O + JSON.stringify(n))), B.retry()) : me("Failed to fetch webSocket connection configuration: " + JSON.stringify(n)), { webSocketConnectionFailed: !0 }; }); Ce(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored")); } }, ke = function ke() { if (o.websocketInitFailed) return Ce(e.info("web-socket initializing had failed, aborting re-init")), { webSocketConnectionFailed: !0 }; if (!V.isNetworkOnline()) return Ce(e.warn("System is offline aborting web-socket init")), { webSocketConnectionFailed: !0 }; e.advancedLog(W), Ce(e.info(W)), Q("initWebSocket"); try { if (Se(a.connConfig)) { var n = null; return ee(t.primary) ? (Ce(e.debug("Primary Socket connection is already open")), Y(t.secondary, WebSocket.CONNECTING) || (Ce(e.debug("Establishing a secondary web-socket connection")), B.numAttempts = 0, t.secondary = we()), n = t.secondary) : (Y(t.primary, WebSocket.CONNECTING) || (Ce(e.debug("Establishing a primary web-socket connection")), t.primary = we()), n = t.primary), o.webSocketInitCheckerTimeoutId = setTimeout(function () { ee(n) || ye(); }, 1e3), { webSocketConnectionFailed: !1 }; } } catch (n) { return Ce(e.error("Error Initializing web-socket-manager", n)), me("Failed to initialize new WebSocket: " + n.message), { webSocketConnectionFailed: !0 }; } }, we = function we() { var n = new WebSocket(a.connConfig.webSocketTransport.url); return n.addEventListener("open", ue), n.addEventListener("message", de), n.addEventListener("error", fe), n.addEventListener("close", function (i) { return function (n, i) { e.advancedLog(m, JSON.stringify(n)), Ce(e.info(m, JSON.stringify(n))), Q("webSocketOnClose before-cleanup"), K(c.connectionClose, { openTimestamp: i.openTimestamp, closeTimestamp: Date.now(), connectionDuration: Date.now() - i.openTimestamp, code: n.code, reason: n.reason }), ne(t.primary) && (t.primary = null), ne(t.secondary) && (t.secondary = null), o.reconnectWebSocket && (ee(t.primary) || ee(t.secondary) ? ne(t.primary) && ee(t.secondary) && (Ce(e.info("[Primary] WebSocket Cleanly Closed")), t.primary = t.secondary, t.secondary = null) : (Ce(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")), o.connState === U ? Ce(e.info("Ignoring connectionLost callback invocation")) : (K(c.connectionLost, { openTimestamp: i.openTimestamp, closeTimestamp: Date.now(), connectionDuration: Date.now() - i.openTimestamp, code: n.code, reason: n.reason }), r.noOpenConnectionsTimestamp = Date.now()), o.connState = U, he()), Q("webSocketOnClose after-cleanup")); }(i, n); }), n; }, Ce = function Ce(e) { return e && "function" == typeof e.sendInternalLogToServer && e.sendInternalLogToServer(), e; }; this.init = function (n) { if (V.assertTrue(V.isFunction(n), "transportHandle must be a function"), null === c.getWebSocketTransport) return c.getWebSocketTransport = n, he(); Ce(e.warn("Web Socket Manager was already initialized")); }, this.onInitFailure = function (n) { return e.advancedLog(I), V.assertTrue(V.isFunction(n), "cb must be a function"), c.initFailure.add(n), o.websocketInitFailed && n(), function () { return c.initFailure["delete"](n); }; }, this.onConnectionOpen = function (n) { return e.advancedLog(N), V.assertTrue(V.isFunction(n), "cb must be a function"), c.connectionOpen.add(n), function () { return c.connectionOpen["delete"](n); }; }, this.onConnectionClose = function (n) { return e.advancedLog(_), V.assertTrue(V.isFunction(n), "cb must be a function"), c.connectionClose.add(n), function () { return c.connectionClose["delete"](n); }; }, this.onConnectionGain = function (n) { return e.advancedLog(E), V.assertTrue(V.isFunction(n), "cb must be a function"), c.connectionGain.add(n), oe() && n(), function () { return c.connectionGain["delete"](n); }; }, this.onConnectionLost = function (n) { return e.advancedLog(F), V.assertTrue(V.isFunction(n), "cb must be a function"), c.connectionLost.add(n), o.connState === U && n(), function () { return c.connectionLost["delete"](n); }; }, this.onSubscriptionUpdate = function (e) { return V.assertTrue(V.isFunction(e), "cb must be a function"), c.subscriptionUpdate.add(e), function () { return c.subscriptionUpdate["delete"](e); }; }, this.onSubscriptionFailure = function (n) { return e.advancedLog(A), V.assertTrue(V.isFunction(n), "cb must be a function"), c.subscriptionFailure.add(n), function () { return c.subscriptionFailure["delete"](n); }; }, this.onMessage = function (e, n) { return V.assertNotNull(e, "topicName"), V.assertTrue(V.isFunction(n), "cb must be a function"), c.topic.has(e) ? c.topic.get(e).add(n) : c.topic.set(e, new Set([n])), function () { return c.topic.get(e)["delete"](n); }; }, this.onAllMessage = function (e) { return V.assertTrue(V.isFunction(e), "cb must be a function"), c.allMessage.add(e), function () { return c.allMessage["delete"](e); }; }, this.subscribeTopics = function (e) { V.assertNotNull(e, "topics"), V.assertIsList(e), e.forEach(function (e) { q.subscribed.has(e) || q.pending.add(e); }), J.consecutiveNoResponseRequest = 0, pe(); }, this.sendMessage = function (n) { if (V.assertIsObject(n, "payload"), void 0 === n.topic || X.has(n.topic)) Ce(e.warn("Cannot send message, Invalid topic", n));else { try { n = JSON.stringify(n); } catch (t) { return void Ce(e.warn("Error stringify message", n)); } oe() ? te().send(n) : Ce(e.warn("Cannot send message, web socket connection is not open")); } }, this.closeWebSocket = function () { ie(), ce(), o.reconnectWebSocket = !1, clearInterval($), be("User request to close WebSocket"); }, this.terminateWebSocketManager = me; }, de = { create: function create() { return new fe(); }, setGlobalConfig: function setGlobalConfig(e) { var n = e && e.loggerConfig; se.updateLoggerConfig(n); }, LogLevel: oe, Logger: ne }; }, function (e, n, t) { var o; !function () { "use strict"; var r = { not_string: /[^s]/, not_bool: /[^t]/, not_type: /[^T]/, not_primitive: /[^v]/, number: /[diefg]/, numeric_arg: /[bcdiefguxX]/, json: /[j]/, not_json: /[^j]/, text: /^[^\x25]+/, modulo: /^\x25{2}/, placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, key: /^([a-z_][a-z_\d]*)/i, key_access: /^\.([a-z_][a-z_\d]*)/i, index_access: /^\[(\d+)\]/, sign: /^[+-]/ }; function i(e) { return function (e, n) { var t, o, c, a, s, u, l, f, d, p = 1, g = e.length, b = ""; for (o = 0; o < g; o++) if ("string" == typeof e[o]) b += e[o];else if ("object" == _typeof(e[o])) { if ((a = e[o]).keys) for (t = n[p], c = 0; c < a.keys.length; c++) { if (null == t) throw new Error(i('[sprintf] Cannot access property "%s" of undefined value "%s"', a.keys[c], a.keys[c - 1])); t = t[a.keys[c]]; } else t = a.param_no ? n[a.param_no] : n[p++]; if (r.not_type.test(a.type) && r.not_primitive.test(a.type) && t instanceof Function && (t = t()), r.numeric_arg.test(a.type) && "number" != typeof t && isNaN(t)) throw new TypeError(i("[sprintf] expecting number but found %T", t)); switch (r.number.test(a.type) && (f = t >= 0), a.type) { case "b": t = parseInt(t, 10).toString(2); break; case "c": t = String.fromCharCode(parseInt(t, 10)); break; case "d": case "i": t = parseInt(t, 10); break; case "j": t = JSON.stringify(t, null, a.width ? parseInt(a.width) : 0); break; case "e": t = a.precision ? parseFloat(t).toExponential(a.precision) : parseFloat(t).toExponential(); break; case "f": t = a.precision ? parseFloat(t).toFixed(a.precision) : parseFloat(t); break; case "g": t = a.precision ? String(Number(t.toPrecision(a.precision))) : parseFloat(t); break; case "o": t = (parseInt(t, 10) >>> 0).toString(8); break; case "s": t = String(t), t = a.precision ? t.substring(0, a.precision) : t; break; case "t": t = String(!!t), t = a.precision ? t.substring(0, a.precision) : t; break; case "T": t = Object.prototype.toString.call(t).slice(8, -1).toLowerCase(), t = a.precision ? t.substring(0, a.precision) : t; break; case "u": t = parseInt(t, 10) >>> 0; break; case "v": t = t.valueOf(), t = a.precision ? t.substring(0, a.precision) : t; break; case "x": t = (parseInt(t, 10) >>> 0).toString(16); break; case "X": t = (parseInt(t, 10) >>> 0).toString(16).toUpperCase(); } r.json.test(a.type) ? b += t : (!r.number.test(a.type) || f && !a.sign ? d = "" : (d = f ? "+" : "-", t = t.toString().replace(r.sign, "")), u = a.pad_char ? "0" === a.pad_char ? "0" : a.pad_char.charAt(1) : " ", l = a.width - (d + t).length, s = a.width && l > 0 ? u.repeat(l) : "", b += a.align ? d + t + s : "0" === u ? d + s + t : s + d + t); } return b; }(function (e) { if (a[e]) return a[e]; var n, t = e, o = [], i = 0; for (; t;) { if (null !== (n = r.text.exec(t))) o.push(n[0]);else if (null !== (n = r.modulo.exec(t))) o.push("%");else { if (null === (n = r.placeholder.exec(t))) throw new SyntaxError("[sprintf] unexpected placeholder"); if (n[2]) { i |= 1; var c = [], s = n[2], u = []; if (null === (u = r.key.exec(s))) throw new SyntaxError("[sprintf] failed to parse named argument key"); for (c.push(u[1]); "" !== (s = s.substring(u[0].length));) if (null !== (u = r.key_access.exec(s))) c.push(u[1]);else { if (null === (u = r.index_access.exec(s))) throw new SyntaxError("[sprintf] failed to parse named argument key"); c.push(u[1]); } n[2] = c; } else i |= 2; if (3 === i) throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported"); o.push({ placeholder: n[0], param_no: n[1], keys: n[2], sign: n[3], pad_char: n[4], align: n[5], width: n[6], precision: n[7], type: n[8] }); } t = t.substring(n[0].length); } return a[e] = o; }(e), arguments); } function c(e, n) { return i.apply(null, [e].concat(n || [])); } var a = Object.create(null); n.sprintf = i, n.vsprintf = c, "undefined" != typeof window && (window.sprintf = i, window.vsprintf = c, void 0 === (o = function () { return { sprintf: i, vsprintf: c }; }.call(n, t, n, e)) || (e.exports = o)); }(); }, function (e, n, t) { "use strict"; t.r(n), function (e) { t.d(n, "WebSocketManager", function () { return r; }); var o = t(0); e.connect = e.connect || {}, connect.WebSocketManager = o.a; var r = o.a; }.call(this, t(3)); }, function (e, n) { var t; t = function () { return this; }(); try { t = t || new Function("return this")(); } catch (e) { "object" == (typeof window === "undefined" ? "undefined" : _typeof(window)) && (t = window); } e.exports = t; }]); /***/ }), /***/ 144: /***/ (() => { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; // How frequently softphone logs should be collected and reported to shared worker. var SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS = 5000; // How frequently logs should be collected and sent downstream var LOGS_REPORT_INTERVAL_MILLIS = 5000; // The default log roll interval (30min) var DEFAULT_LOG_ROLL_INTERVAL = 1800000; // Prefix to be added to values obfuscated using MD5 digest. var OBFUSCATED_PREFIX = "[obfuscated value]"; /** * An enumeration of common logging levels. */ var LogLevel = { TEST: "TEST", TRACE: "TRACE", DEBUG: "DEBUG", INFO: "INFO", LOG: "LOG", WARN: "WARN", ERROR: "ERROR", CRITICAL: "CRITICAL" }; /** * An enumeration of common logging components. */ var LogComponent = { CCP: "ccp", SOFTPHONE: "softphone", CHAT: "chat", TASK: "task" }; /** * The numeric order of the logging levels above. * They are spaced to allow the addition of other log * levels at a later time. */ var LogLevelOrder = { TEST: 0, TRACE: 10, DEBUG: 20, INFO: 30, LOG: 40, WARN: 50, ERROR: 100, CRITICAL: 200 }; /** * An enumeration of logging context layers. */ var LogContextLayer = { CCP: "CCP", SHARED_WORKER: "SharedWorker", CRM: "CRM" }; /** * A map from log level to console logger function. */ var CONSOLE_LOGGER_MAP = { TRACE: function TRACE(text) { console.info(text); }, DEBUG: function DEBUG(text) { console.info(text); }, INFO: function INFO(text) { console.info(text); }, LOG: function LOG(text) { console.log(text); }, TEST: function TEST(text) { console.log(text); }, WARN: function WARN(text) { console.warn(text); }, ERROR: function ERROR(text) { console.error(text); }, CRITICAL: function CRITICAL(text) { console.error(text); } }; var REDACTED_STRING = "[redacted]"; /** * Checks if it is a valid log component enum */ var isValidLogComponent = function isValidLogComponent(component) { return Object.values(LogComponent).indexOf(component) !== -1; }; /** * Extract the custom arguments as required by the logger */ var extractLoggerArgs = function extractLoggerArgs(loggerArgs) { var args = Array.prototype.slice.call(loggerArgs, 0); var firstArg = args.shift(); var format; var component; if (isValidLogComponent(firstArg)) { component = firstArg; format = args.shift(); } else { //default to CCP component format = firstArg; component = LogComponent.CCP; } return { format: format, component: component, args: args }; }; /** * A log entry. * * @param component The logging component. * @param level The log level of this log entry. * @param text The text contained in the log entry. * @param loggerId The root logger id. * * Log entries are aware of their timestamp, order, * and can contain objects and exception stack traces. */ var LogEntry = function LogEntry(component, level, text, loggerId, tabId, contextLayer) { this.component = component; this.level = level; this.text = text; this.time = new Date(); this.tabId = tabId === null ? null : tabId ? tabId : connect.core.tabId; this.exception = null; this.objects = []; this.line = 0; this.agentResourceId = null; try { if (connect.agent.initialized) { this.agentResourceId = new connect.Agent()._getResourceId(); } } catch (e) { console.log("Issue finding agentResourceId: ", e); //can't use our logger here as we might infinitely attempt to log this error. } this.loggerId = loggerId; if (contextLayer) { this.contextLayer = contextLayer; } else { if (connect.isSharedWorker()) { this.contextLayer = LogContextLayer.SHARED_WORKER; } else if (connect.isCRM()) { this.contextLayer = LogContextLayer.CRM; } else if (connect.isCCP()) { this.contextLayer = LogContextLayer.CCP; } } }; LogEntry.fromObject = function (obj) { var tabId = obj.tabId || null; var contextLayer = obj.contextLayer || null; var entry = new LogEntry(LogComponent.CCP, obj.level, obj.text, obj.loggerId, tabId, contextLayer); // Required to check for Date objects sent across frame boundaries if (Object.prototype.toString.call(obj.time) === '[object Date]') { entry.time = new Date(obj.time.getTime()); } else if (typeof obj.time === 'number') { entry.time = new Date(obj.time); } else if (typeof obj.time === 'string') { entry.time = Date.parse(obj.time); } else { entry.time = new Date(); } entry.exception = obj.exception; entry.objects = obj.objects; return entry; }; /** * Private method to remove sensitive info from client log */ var _redactSensitiveInfo = function redactSensitiveInfo(data) { var authTokenRegex = /(AuthToken.*)/gi; var e164NumberFormatRegex = /Phone number.*/gi; var sendDigtRegex = /Send digit.*/gi; var connectionAuthTokenRegex = /ConnectionAuthenticationToken.*/gi; var credentialRegex = /("credential":")([^"]*)"/; var emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g; var redactedFields = ["quickconnectname", "token", "login", "credential", "internalip", "authtoken", "phonenumber", "firstname", "lastname", "emailaddress", "address", "displayname", "agentname", "description", "name", "value", "summary", "queue.name"]; var hashedFields = ["customerid", "speakerid", "customerspeakerid", "presignedurl"]; if (data && _typeof(data) === 'object') { Object.keys(data).forEach(function (key) { if (_typeof(data[key]) === 'object') { if (key === "attributes") { data[key] = REDACTED_STRING; //we want to redact the entire attributes object } else if (key === "state") { return; // don't redact agent availability status name } else { _redactSensitiveInfo(data[key]); } } else if (typeof data[key] === 'string') { if (key === "url" || key === "text") { data[key] = data[key].replace(authTokenRegex, REDACTED_STRING); //to remove all traces of phone numbers data[key] = data[key].replace(e164NumberFormatRegex, "phone number" + REDACTED_STRING); data[key] = data[key].replace(sendDigtRegex, "send digit " + REDACTED_STRING); data[key] = data[key].replace(connectionAuthTokenRegex, REDACTED_STRING); data[key] = data[key].replace(emailRegex, "email address " + REDACTED_STRING); } else if (redactedFields.includes(key.toLowerCase())) { data[key] = REDACTED_STRING; } else if ("callconfigjson" === key.toLowerCase()) { // we need to redact the credential in call config json data[key] = data[key].replace(credentialRegex, function (match, key, value) { return key + REDACTED_STRING + '"'; }); } else if (hashedFields.includes(key.toLowerCase())) { data[key] = "".concat(OBFUSCATED_PREFIX, " ").concat(md5(data[key])); } } }); } }; /** * Pulls the type, message, and stack trace * out of the given exception for JSON serialization. */ var LoggedException = function LoggedException(e) { this.type = e instanceof Error ? e.name : e.code || Object.prototype.toString.call(e); this.message = e.message; this.stack = []; if (e.stack) { try { if (Array.isArray(e.stack)) { this.stack = e.stack; } else if (_typeof(e.stack) === 'object') { this.stack = [JSON.stringify(e.stack)]; } else if (typeof e.stack === 'string') { this.stack = e.stack.split('\n'); } } catch (_unused) {} } }; /** * Minimally stringify this log entry for printing * to the console. */ LogEntry.prototype.toString = function () { return connect.sprintf("[%s] [%s] [%s]: %s", this.getTime() && this.getTime().toISOString ? this.getTime().toISOString() : "???", this.getLevel(), this.getAgentResourceId(), this.getText()); }; /** * Get the log entry timestamp. */ LogEntry.prototype.getTime = function () { return this.time; }; LogEntry.prototype.getAgentResourceId = function () { return this.agentResourceId; }; LogEntry.prototype.getTabId = function () { return this.tabId; }; LogEntry.prototype.getContextLayer = function () { return this.contextLayer; }; /** * Get the level of the log entry. */ LogEntry.prototype.getLevel = function () { return this.level; }; /** * Get the log entry text. */ LogEntry.prototype.getText = function () { return this.text; }; /** * Get the log entry component. */ LogEntry.prototype.getComponent = function () { return this.component; }; /** * Add an exception stack trace to this log entry. * A log entry may contain only one exception stack trace. */ LogEntry.prototype.withException = function (e) { this.exception = new LoggedException(e); return this; }; /** * Add an arbitrary object to the log entry. A log entry * may contain any number of objects. */ LogEntry.prototype.withObject = function (obj) { var copiedObj = connect.deepcopy(obj); _redactSensitiveInfo(copiedObj); this.objects.push(copiedObj); return this; }; /** * Add a cross origin event object to the log entry. A log entry * may contain any number of objects. */ LogEntry.prototype.withCrossOriginEventObject = function (obj) { var copiedObj = connect.deepcopyCrossOriginEvent(obj); _redactSensitiveInfo(copiedObj); this.objects.push(copiedObj); return this; }; /** * Indicate that this log entry should be sent to the server * NOTE: This should be used for internal logs only */ LogEntry.prototype.sendInternalLogToServer = function () { connect.getLog()._serverBoundInternalLogs.push(this); return this; }; /** * The logger instance. */ var Logger = function Logger() { this._logs = []; this._rolledLogs = []; this._logsToPush = []; this._serverBoundInternalLogs = []; this._echoLevel = LogLevelOrder.INFO; this._logLevel = LogLevelOrder.INFO; this._lineCount = 0; this._logRollInterval = 0; this._logRollTimer = null; this._loggerId = new Date().getTime() + "-" + Math.random().toString(36).slice(2); this.setLogRollInterval(DEFAULT_LOG_ROLL_INTERVAL); this._startLogIndexToPush = 0; }; /** * Sets the interval in milliseconds that the logs will be rotated. * Logs are rotated out completely at the end of the second roll * and will eventually be garbage collected. */ Logger.prototype.setLogRollInterval = function (interval) { var self = this; if (!this._logRollTimer || interval !== this._logRollInterval) { if (this._logRollTimer) { global.clearInterval(this._logRollTimer); } this._logRollInterval = interval; this._logRollTimer = global.setInterval(function () { self._rolledLogs = self._logs; self._logs = []; self._startLogIndexToPush = 0; self.info("Log roll interval occurred."); }, this._logRollInterval); } else { this.warn("Logger is already set to the given interval: %d", this._logRollInterval); } }; /** * Set the log level. This is the minimum level at which logs will * be kept for later archiving. */ Logger.prototype.setLogLevel = function (level) { if (level in LogLevelOrder) { this._logLevel = LogLevelOrder[level]; } else { throw new Error("Unknown logging level: " + level); } }; /** * Set the echo level. This is the minimum level at which logs will * be printed to the javascript console. */ Logger.prototype.setEchoLevel = function (level) { if (level in LogLevelOrder) { this._echoLevel = LogLevelOrder[level]; } else { throw new Error("Unknown logging level: " + level); } }; /** * Write a particular log entry. * * @param level The logging level of the entry. * @param text The text contents of the entry. * * @returns The new log entry. */ Logger.prototype.write = function (component, level, text) { var logEntry = new LogEntry(component, level, text, this.getLoggerId()); _redactSensitiveInfo(logEntry); this.addLogEntry(logEntry); return logEntry; }; Logger.prototype.addLogEntry = function (logEntry) { // Call this second time as in some places this function is called directly _redactSensitiveInfo(logEntry); this._logs.push(logEntry); //For now only send softphone logs only. //TODO add CCP logs once we are sure that no sensitive data is being logged. if (LogComponent.SOFTPHONE === logEntry.component) { this._logsToPush.push(logEntry); } if (logEntry.level in LogLevelOrder && LogLevelOrder[logEntry.level] >= this._logLevel) { if (LogLevelOrder[logEntry.level] >= this._echoLevel) { CONSOLE_LOGGER_MAP[logEntry.getLevel()](logEntry.toString()); } logEntry.line = this._lineCount++; } }; Logger.prototype.sendInternalLogEntryToServer = function (logEntry) { this._serverBoundInternalLogs.push(logEntry); if (logEntry.level in LogLevelOrder && LogLevelOrder[logEntry.level] >= this._logLevel) { if (LogLevelOrder[logEntry.level] >= this._echoLevel) { CONSOLE_LOGGER_MAP[logEntry.getLevel()](logEntry.toString()); } logEntry.line = this._lineCount++; } }; /** * Remove all objects from all log entries. */ Logger.prototype.clearObjects = function () { for (var x = 0; x < this._logs.length; x++) { if (this._logs[x].objects) { delete this._logs[x].objects; } } }; /** * Remove all exception stack traces from the log entries. */ Logger.prototype.clearExceptions = function () { for (var x = 0; x < this._logs.length; x++) { if (this._logs[x].exception) { delete this._logs[x].exception; } } }; Logger.prototype.trace = function () { var logArgs = extractLoggerArgs(arguments); return this.write(logArgs.component, LogLevel.TRACE, connect.vsprintf(logArgs.format, logArgs.args)); }; Logger.prototype.debug = function () { var logArgs = extractLoggerArgs(arguments); return this.write(logArgs.component, LogLevel.DEBUG, connect.vsprintf(logArgs.format, logArgs.args)); }; Logger.prototype.info = function () { var logArgs = extractLoggerArgs(arguments); return this.write(logArgs.component, LogLevel.INFO, connect.vsprintf(logArgs.format, logArgs.args)); }; Logger.prototype.log = function () { var logArgs = extractLoggerArgs(arguments); return this.write(logArgs.component, LogLevel.LOG, connect.vsprintf(logArgs.format, logArgs.args)); }; Logger.prototype.test = function () { var logArgs = extractLoggerArgs(arguments); return this.write(logArgs.component, LogLevel.TEST, connect.vsprintf(logArgs.format, logArgs.args)); }; Logger.prototype.warn = function () { var logArgs = extractLoggerArgs(arguments); return this.write(logArgs.component, LogLevel.WARN, connect.vsprintf(logArgs.format, logArgs.args)); }; Logger.prototype.error = function () { var logArgs = extractLoggerArgs(arguments); return this.write(logArgs.component, LogLevel.ERROR, connect.vsprintf(logArgs.format, logArgs.args)); }; Logger.prototype.critical = function () { var logArgs = extractLoggerArgs(arguments); return this.write(logArgs.component, LogLevel.ERROR, connect.vsprintf(logArgs.format, logArgs.args)); }; /** * Create a string representation of the logger contents. */ Logger.prototype.toString = function () { var lines = []; for (var x = 0; x < this._logs.length; x++) { lines.push(this._logs[x].toString()); } return lines.join("\n"); }; /** * Download/Archive logs to a file, * By default, it returns all logs. * To filter logs by the minimum log level set by setLogLevel or the default set in _logLevel, * pass in filterByLogLevel to true in options * * @param options download options [Object|String]. * - of type Object: * { logName: 'my-log-name', * filterByLogLevel: false, //download all logs * } * - of type String (for backward compatibility), the file's name */ Logger.prototype.download = function (options) { var _connect; var logName = 'agent-log'; var filterByLogLevel = false; // This will only be set to true on the CRM layer when GlobalResiliency is enabled var isGlobalResiliency = ((_connect = connect) === null || _connect === void 0 || (_connect = _connect.globalResiliency) === null || _connect === void 0 ? void 0 : _connect.globalResiliencyEnabled) === true; if (_typeof(options) === 'object' && options !== null) { logName = options.logName || logName; filterByLogLevel = options.filterByLogLevel || filterByLogLevel; } else if (typeof options === 'string') { logName = options || logName; } if (isGlobalResiliency) { // Three CCP logs will be downloaded in Global Resiliency // One from each CCP which contains CCP logs + CRM from time of initialization of CCP onwards // This is done when connect.globalResiliency._downloadCCPLogs(); is called // CRM layer which contains all CRM logs and all CCP logs, retrieved in the remainder of this function. connect.globalResiliency._downloadCCPLogs(); logName = "crm-" + logName; } var self = this; var logs = this._rolledLogs.concat(this._logs); if (filterByLogLevel) { logs = logs.filter(function (entry) { return LogLevelOrder[entry.level] >= self._logLevel; }); } var logBlob = new global.Blob([JSON.stringify(logs, undefined, 4)], ['text/plain']); var downloadLink = document.createElement('a'); var logName = logName || 'agent-log'; downloadLink.href = global.URL.createObjectURL(logBlob); downloadLink.download = logName + '.txt'; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); }; Logger.prototype.scheduleUpstreamLogPush = function (conduit) { if (!connect.upstreamLogPushScheduled) { connect.upstreamLogPushScheduled = true; /** Schedule pushing logs frequently to sharedworker upstream, sharedworker will report to the CTI backend*/ global.setInterval(connect.hitch(this, this.reportMasterLogsUpStream, conduit), SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS); } }; Logger.prototype.reportMasterLogsUpStream = function (conduit) { var logsToPush = this._logsToPush.slice(); this._logsToPush = []; connect.ifMaster(connect.MasterTopics.SEND_LOGS, function () { if (logsToPush.length > 0) { conduit.sendUpstream(connect.EventType.SEND_LOGS, logsToPush); } }); }; Logger.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush = function (conduit) { global.setInterval(connect.hitch(this, this.pushOuterContextCCPserverBoundLogsUpstream, conduit), 1000); }; Logger.prototype.scheduleUpstreamOuterContextCCPLogsPush = function (conduit) { global.setInterval(connect.hitch(this, this.pushOuterContextCCPLogsUpstream, conduit), 1000); }; Logger.prototype.pushOuterContextCCPserverBoundLogsUpstream = function (conduit) { if (this._serverBoundInternalLogs.length > 0) { for (var i = 0; i < this._serverBoundInternalLogs.length; i++) { this._serverBoundInternalLogs[i].text = this._serverBoundInternalLogs[i].text; } conduit.sendUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs); this._serverBoundInternalLogs = []; } }; Logger.prototype.pushOuterContextCCPLogsUpstream = function (conduit) { for (var i = this._startLogIndexToPush; i < this._logs.length; i++) { if (this._logs[i].loggerId !== this._loggerId) { continue; } conduit.sendUpstream(connect.EventType.LOG, this._logs[i]); } this._startLogIndexToPush = this._logs.length; }; Logger.prototype.getLoggerId = function () { return this._loggerId; }; Logger.prototype.scheduleDownstreamClientSideLogsPush = function () { global.setInterval(connect.hitch(this, this.pushClientSideLogsDownstream), LOGS_REPORT_INTERVAL_MILLIS); }; Logger.prototype.pushClientSideLogsDownstream = function () { var logs = []; // We do not send a request if we have less than 50 records so that we minimize the number of // requests per second. // 500 is the max we accept on the server. // We chose 500 because this is the limit imposed by Firehose for a put batch request if (this._serverBoundInternalLogs.length < 50) { return; } else if (this._serverBoundInternalLogs.length > 500) { logs = this._serverBoundInternalLogs.splice(0, 500); } else { logs = this._serverBoundInternalLogs; this._serverBoundInternalLogs = []; } connect.publishClientSideLogs(logs); }; var _DownstreamConduitLogger = function DownstreamConduitLogger(conduit) { Logger.call(this); this.conduit = conduit; global.setInterval(connect.hitch(this, this._pushLogsDownstream), _DownstreamConduitLogger.LOG_PUSH_INTERVAL); // Disable log rolling, we will purge our own logs once they have // been pushed downstream. global.clearInterval(this._logRollTimer); this._logRollTimer = null; }; // How frequently logs should be collected and delivered downstream. _DownstreamConduitLogger.LOG_PUSH_INTERVAL = 1000; _DownstreamConduitLogger.prototype = Object.create(Logger.prototype); _DownstreamConduitLogger.prototype.constructor = _DownstreamConduitLogger; _DownstreamConduitLogger.prototype.pushLogsDownstream = function (logs) { var self = this; logs.forEach(function (log) { self.conduit.sendDownstream(connect.EventType.LOG, log); }); }; _DownstreamConduitLogger.prototype._pushLogsDownstream = function () { var self = this; this._logs.forEach(function (log) { self.conduit.sendDownstream(connect.EventType.LOG, log); }); this._logs = []; for (var i = 0; i < this._serverBoundInternalLogs.length; i++) { this.conduit.sendDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs[i]); } this._serverBoundInternalLogs = []; }; /** * Wrap a function with try catch block */ var tryCatchWrapperMethod = function tryCatchWrapperMethod(fn) { var wrappedfunction = function wrappedfunction() { try { return fn.apply(this, arguments); } catch (e) { // Since this wraps Logger class, we can only print it in the console and eat it. CONSOLE_LOGGER_MAP.ERROR(e); } }; return wrappedfunction; }; /** * This is a wrapper method to wrap each function * in an object with try catch block. */ var tryCatchWrapperObject = function tryCatchWrapperObject(obj) { for (var method in obj) { if (typeof obj[method] === 'function') { obj[method] = tryCatchWrapperMethod(obj[method]); } } }; /** Create the singleton logger instance. */ connect.rootLogger = new Logger(); tryCatchWrapperObject(connect.rootLogger); /** Fetch the singleton logger instance. */ var getLog = function getLog() { return connect.rootLogger; }; connect = connect || {}; connect.getLog = getLog; connect.LogEntry = LogEntry; connect.Logger = Logger; connect.LogLevel = LogLevel; connect.LogComponent = LogComponent; connect.DownstreamConduitLogger = _DownstreamConduitLogger; })(); /***/ }), /***/ 254: /***/ (function() { /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * https://opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /* global define */ /* eslint-disable strict */ ; (function ($) { var ctx = this || globalThis; /** * Add integers, wrapping at 2^32. * This uses 16-bit operations internally to work around bugs in interpreters. * * @param {number} x First integer * @param {number} y Second integer * @returns {number} Sum */ function safeAdd(x, y) { var lsw = (x & 0xffff) + (y & 0xffff); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return msw << 16 | lsw & 0xffff; } /** * Bitwise rotate a 32-bit number to the left. * * @param {number} num 32-bit number * @param {number} cnt Rotation count * @returns {number} Rotated number */ function bitRotateLeft(num, cnt) { return num << cnt | num >>> 32 - cnt; } /** * Basic operation the algorithm uses. * * @param {number} q q * @param {number} a a * @param {number} b b * @param {number} x x * @param {number} s s * @param {number} t t * @returns {number} Result */ function md5cmn(q, a, b, x, s, t) { return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } /** * Basic operation the algorithm uses. * * @param {number} a a * @param {number} b b * @param {number} c c * @param {number} d d * @param {number} x x * @param {number} s s * @param {number} t t * @returns {number} Result */ function md5ff(a, b, c, d, x, s, t) { return md5cmn(b & c | ~b & d, a, b, x, s, t); } /** * Basic operation the algorithm uses. * * @param {number} a a * @param {number} b b * @param {number} c c * @param {number} d d * @param {number} x x * @param {number} s s * @param {number} t t * @returns {number} Result */ function md5gg(a, b, c, d, x, s, t) { return md5cmn(b & d | c & ~d, a, b, x, s, t); } /** * Basic operation the algorithm uses. * * @param {number} a a * @param {number} b b * @param {number} c c * @param {number} d d * @param {number} x x * @param {number} s s * @param {number} t t * @returns {number} Result */ function md5hh(a, b, c, d, x, s, t) { return md5cmn(b ^ c ^ d, a, b, x, s, t); } /** * Basic operation the algorithm uses. * * @param {number} a a * @param {number} b b * @param {number} c c * @param {number} d d * @param {number} x x * @param {number} s s * @param {number} t t * @returns {number} Result */ function md5ii(a, b, c, d, x, s, t) { return md5cmn(c ^ (b | ~d), a, b, x, s, t); } /** * Calculate the MD5 of an array of little-endian words, and a bit length. * * @param {Array} x Array of little-endian words * @param {number} len Bit length * @returns {Array} MD5 Array */ function binlMD5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << len % 32; x[(len + 64 >>> 9 << 4) + 14] = len; var i; var olda; var oldb; var oldc; var oldd; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5ff(a, b, c, d, x[i], 7, -680876936); d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5ff(c, d, a, b, x[i + 10], 17, -42063); b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5gg(b, c, d, a, x[i], 20, -373897302); a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5hh(a, b, c, d, x[i + 5], 4, -378558); d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5hh(d, a, b, c, x[i], 11, -358537222); c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5ii(a, b, c, d, x[i], 6, -198630844); d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); a = safeAdd(a, olda); b = safeAdd(b, oldb); c = safeAdd(c, oldc); d = safeAdd(d, oldd); } return [a, b, c, d]; } /** * Convert an array of little-endian words to a string * * @param {Array} input MD5 Array * @returns {string} MD5 string */ function binl2rstr(input) { var i; var output = ''; var length32 = input.length * 32; for (i = 0; i < length32; i += 8) { output += String.fromCharCode(input[i >> 5] >>> i % 32 & 0xff); } return output; } /** * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. * * @param {string} input Raw input string * @returns {Array} Array of little-endian words */ function rstr2binl(input) { var i; var output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } var length8 = input.length * 8; for (i = 0; i < length8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xff) << i % 32; } return output; } /** * Calculate the MD5 of a raw string * * @param {string} s Input string * @returns {string} Raw MD5 string */ function rstrMD5(s) { return binl2rstr(binlMD5(rstr2binl(s), s.length * 8)); } /** * Calculates the HMAC-MD5 of a key and some data (raw strings) * * @param {string} key HMAC key * @param {string} data Raw input string * @returns {string} Raw MD5 string */ function rstrHMACMD5(key, data) { var i; var bkey = rstr2binl(key); var ipad = []; var opad = []; var hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binlMD5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5c5c5c5c; } hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binlMD5(opad.concat(hash), 512 + 128)); } /** * Convert a raw string to a hex string * * @param {string} input Raw input string * @returns {string} Hex encoded string */ function rstr2hex(input) { var hexTab = '0123456789abcdef'; var output = ''; var x; var i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f); } return output; } /** * Encode a string as UTF-8 * * @param {string} input Input string * @returns {string} UTF8 string */ function str2rstrUTF8(input) { return unescape(encodeURIComponent(input)); } /** * Encodes input string as raw MD5 string * * @param {string} s Input string * @returns {string} Raw MD5 string */ function rawMD5(s) { return rstrMD5(str2rstrUTF8(s)); } /** * Encodes input string as Hex encoded string * * @param {string} s Input string * @returns {string} Hex encoded string */ function hexMD5(s) { return rstr2hex(rawMD5(s)); } /** * Calculates the raw HMAC-MD5 for the given key and data * * @param {string} k HMAC key * @param {string} d Input string * @returns {string} Raw MD5 string */ function rawHMACMD5(k, d) { return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d)); } /** * Calculates the Hex encoded HMAC-MD5 for the given key and data * * @param {string} k HMAC key * @param {string} d Input string * @returns {string} Raw MD5 string */ function hexHMACMD5(k, d) { return rstr2hex(rawHMACMD5(k, d)); } /** * Calculates MD5 value for a given string. * If a key is provided, calculates the HMAC-MD5 value. * Returns a Hex encoded string unless the raw argument is given. * * @param {string} string Input string * @param {string} [key] HMAC key * @param {boolean} [raw] Raw output switch * @returns {string} MD5 output */ function md5(string, key, raw) { if (!key) { if (!raw) { return hexMD5(string); } return rawMD5(string); } if (!raw) { return hexHMACMD5(key, string); } return rawHMACMD5(key, string); } ctx.md5 = md5; })(this); /***/ }), /***/ 142: /***/ (() => { /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). You may not use * this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express * or implied. See the License for the specific language governing permissions * and limitations under the License. */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; connect.ChatMediaController = function (mediaInfo, metadata) { var logger = connect.getLog(); var logComponent = connect.LogComponent.CHAT; var createMediaInstance = function createMediaInstance() { publishTelemetryEvent('Chat media controller init', mediaInfo.contactId); logger.info(logComponent, 'Chat media controller init').withObject(mediaInfo).sendInternalLogToServer(); connect.ChatSession.setGlobalConfig({ loggerConfig: { logger: logger }, region: metadata.region }); /** Could be also CUSTOMER - For now we are creating only Agent connection media object */ var controller = connect.ChatSession.create({ chatDetails: mediaInfo, type: 'AGENT', websocketManager: connect.core.getWebSocketManager() }); trackChatConnectionStatus(controller); return controller.connect().then(function (data) { logger.info(logComponent, 'Chat Session Successfully established for contactId %s', mediaInfo.contactId).sendInternalLogToServer(); publishTelemetryEvent('Chat Session Successfully established', mediaInfo.contactId); return controller; })["catch"](function (error) { logger.error(logComponent, 'Chat Session establishement failed for contact %s', mediaInfo.contactId).withException(error).sendInternalLogToServer(); publishTelemetryEvent('Chat Session establishement failed', mediaInfo.contactId, error); throw error; }); }; var publishTelemetryEvent = function publishTelemetryEvent(eventName, data) { connect.publishMetric({ name: eventName, contactId: mediaInfo.contactId, data: data || mediaInfo }); }; var trackChatConnectionStatus = function trackChatConnectionStatus(controller) { controller.onConnectionBroken(function (data) { logger.error(logComponent, 'Chat Session connection broken').withException(data).sendInternalLogToServer(); publishTelemetryEvent('Chat Session connection broken', data); }); controller.onConnectionEstablished(function (data) { logger.info(logComponent, 'Chat Session connection established').withObject(data).sendInternalLogToServer(); publishTelemetryEvent('Chat Session connection established', data); }); }; return { get: function get() { return createMediaInstance(); } }; }; })(); /***/ }), /***/ 884: /***/ (() => { /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). You may not use * this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express * or implied. See the License for the specific language governing permissions * and limitations under the License. */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; connect.MediaFactory = function (params) { /** controller holder */ var mediaControllers = {}; var toBeDestroyed = new Set(); var logger = connect.getLog(); var logComponent = connect.LogComponent.CHAT; var metadata = connect.merge({}, params) || {}; metadata.region = metadata.region || 'us-west-2'; // Default it to us-west-2 var getMediaController = function getMediaController(connectionObj) { var connectionId = connectionObj.getConnectionId(); var mediaInfo = connectionObj.getMediaInfo(); /** if we do not have the media info then just reject the request */ if (!mediaInfo) { logger.error(logComponent, 'Media info does not exist for a media type %s', connectionObj.getMediaType()).withObject(connectionObj).sendInternalLogToServer(); return Promise.reject('Media info does not exist for this connection'); } if (!mediaControllers[connectionId]) { logger.info(logComponent, 'media controller of type %s init', connectionObj.getMediaType()).withObject(connectionObj).sendInternalLogToServer(); switch (connectionObj.getMediaType()) { case connect.MediaType.CHAT: return mediaControllers[connectionId] = new connect.ChatMediaController(connectionObj.getMediaInfo(), metadata).get(); case connect.MediaType.SOFTPHONE: return mediaControllers[connectionId] = new connect.SoftphoneMediaController(connectionObj.getMediaInfo()).get(); case connect.MediaType.TASK: return mediaControllers[connectionId] = new connect.TaskMediaController(connectionObj.getMediaInfo()).get(); default: logger.error(logComponent, 'Unrecognized media type %s ', connectionObj.getMediaType()).sendInternalLogToServer(); return Promise.reject(); } } else { return mediaControllers[connectionId]; } }; /** Check all the active states for the connection */ var ifConnectionActive = function ifConnectionActive(connectionObj) { return connectionObj.isActive(); }; var get = function get(connectionObj) { if (ifConnectionActive(connectionObj)) { return getMediaController(connectionObj); } else { destroy(connectionObj.getConnectionId()); return Promise.reject('Media Controller is no longer available for this connection'); } }; var destroy = function destroy(connectionId) { if (mediaControllers[connectionId] && !toBeDestroyed.has(connectionId)) { logger.info(logComponent, 'Destroying mediaController for %s', connectionId); toBeDestroyed.add(connectionId); mediaControllers[connectionId].then(function (controller) { if (typeof controller.cleanUp === 'function') controller.cleanUp(); delete mediaControllers[connectionId]; toBeDestroyed["delete"](connectionId); })["catch"](function () { delete mediaControllers[connectionId]; toBeDestroyed["delete"](connectionId); }); } }; return { get: get, destroy: destroy }; }; })(); /***/ }), /***/ 390: /***/ (() => { /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). You may not use * this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express * or implied. See the License for the specific language governing permissions * and limitations under the License. */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; // TODO move softphone implementations here - Wil do this for GA connect.SoftphoneMediaController = function (mediaInfo) { return { get: function get() { return Promise.resolve(mediaInfo); } }; }; })(); /***/ }), /***/ 269: /***/ (() => { /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Amazon Software License (the "License"). You may not use * this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/asl/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express * or implied. See the License for the specific language governing permissions * and limitations under the License. */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; connect.TaskMediaController = function (mediaInfo) { var logger = connect.getLog(); var logComponent = connect.LogComponent.TASK; var createMediaInstance = function createMediaInstance() { publishTelemetryEvent('Task media controller init', mediaInfo.contactId); logger.info(logComponent, 'Task media controller init').withObject(mediaInfo); var controller = connect.TaskSession.create({ contactId: mediaInfo.contactId, initialContactId: mediaInfo.initialContactId, websocketManager: connect.core.getWebSocketManager() }); trackTaskConnectionStatus(controller); return controller.connect().then(function () { logger.info(logComponent, 'Task Session Successfully established for contactId %s', mediaInfo.contactId); publishTelemetryEvent('Task Session Successfully established', mediaInfo.contactId); return controller; })["catch"](function (error) { logger.error(logComponent, 'Task Session establishement failed for contact %s', mediaInfo.contactId).withException(error); publishTelemetryEvent('Chat Session establishement failed', mediaInfo.contactId, error); throw error; }); }; var publishTelemetryEvent = function publishTelemetryEvent(eventName, data) { connect.publishMetric({ name: eventName, contactId: mediaInfo.contactId, data: data || mediaInfo }); }; var trackTaskConnectionStatus = function trackTaskConnectionStatus(controller) { controller.onConnectionBroken(function (data) { logger.error(logComponent, 'Task Session connection broken').withException(data); publishTelemetryEvent('Task Session connection broken', data); }); controller.onConnectionEstablished(function (data) { logger.info(logComponent, 'Task Session connection established').withObject(data); publishTelemetryEvent('Task Session connection established', data); }); }; return { get: function get() { return createMediaInstance(); } }; }; })(); /***/ }), /***/ 414: /***/ (() => { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /** * Module which gets used for the Request storage access * Exposes init, hasAccess, request and onRequest methods. * utilizes core post message technique to communicate back to the parent which invokes the storage access * * @usage - Used by initCCP and customer can make use of onRequest callbacks , this will be called even before agent login * * Example - * connect.storageAccess.onRequest({ * onInit(){}, * onDeny(){}, * onGrant(){} * }); * * There are 4 lifecycle methods in the storage access check * * a) Request - StreamJS would request for storage access check to the embedded Connect hosted storage access banner * b) Init - Storage access banner inits the access check and sends back the current access state with hasAccess set to true or false * this is the step where we show the actual RSA banner to agents and for custom use cases hidden container will be shown * c) Grant [optional] - Executes when Agent/user accepts storage access or already given grant * d) Deny [optional] - Executes when Agent/user deny the storage access/ * * In a positive flow - we should expect Request, Init, Grant and negative Request, Init, Deny * * Chrome Implementation of RSA API can be found here - https://github.com/cfredric/chrome-storage-access-api */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; var requestStorageAccessPath = '/request-storage-access'; /** * Configurable options exposed via initCCP * By default canRequest will be set to false to make this as a explicit opt in */ var defaultStorageAccessParams = { /* Config which controls the opt out/in - we expect customers to explicitely opt out. */ canRequest: false, /* ["custom", "default"] - decides the rsa page view */ mode: 'default', custom: { hideCCP: true // only applicable in custom mode /** * Only applicable for custom type RSA page and these messages should be localized by customers * * title: 'Cookie Notice', * header: 'Please provide access' * */ } }; var storageParams = {}; var originalCCPUrl = ''; var rsaContainer = null; var onGrantCallbackInvoked = false; var requesthandlerUnsubscriber; var storageAccessEvents = { INIT: 'storageAccess::init', GRANTED: 'storageAccess::granted', DENIED: 'storageAccess::denied', REQUEST: 'storageAccess::request' }; var initStorageParams = function initStorageParams() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; params.custom = params.custom || {}; storageParams = _objectSpread(_objectSpread(_objectSpread({}, defaultStorageAccessParams), params), {}, { custom: _objectSpread(_objectSpread({}, defaultStorageAccessParams.custom), params.custom) }); storageParams.canRequest = !(storageParams.canRequest === 'false' || storageParams.canRequest === false); }; var resetStorageAccessState = function resetStorageAccessState() { storageParams = {}; originalCCPUrl = ''; rsaContainer = null; onGrantCallbackInvoked = false; }; /** * Handle display none/block properties for the RTSA container, if customer have different settings like height, opacity, positions etc configured they are encouraged to use * onRequest Callback handle to reset the same. * */ var getRSAContainer = function getRSAContainer() { return { show: function show() { rsaContainer.style.display = 'block'; }, hide: function hide() { rsaContainer.style.display = 'none'; } }; }; /** * Custom Mode will show minimalistic UI - without any Connect references or Connect headers * This will allow fully Custom CCPs to use banner and use minimal real estate to show the storage access Content * */ var isCustomRequestAccessMode = function isCustomRequestAccessMode() { return storageParams && storageParams.mode === 'custom'; }; /** * Check if the user wants to hide CCP * By default this is true */ var hideCCP = function hideCCP() { var _storageParams; return (_storageParams = storageParams) === null || _storageParams === void 0 || (_storageParams = _storageParams.custom) === null || _storageParams === void 0 ? void 0 : _storageParams.hideCCP; }; var isConnectDomain = function isConnectDomain(origin) { return origin.match(/.connect.aws.a2z.com|.my.connect.aws|.govcloud.connect.aws|.awsapps.com/); }; /** * Given the URL, this method generates the prefixed connect domain request storage access URL * @param {string} url * @returns {string} */ var getRsaUrlWithprefix = function getRsaUrlWithprefix(url) { var _URL = new URL(url), origin = _URL.origin, pathname = _URL.pathname; if (origin.match(/.awsapps.com/)) { var prefix = 'connect'; if (pathname.startsWith('/connect-gamma')) { prefix = 'connect-gamma'; } return "".concat(origin, "/").concat(prefix).concat(requestStorageAccessPath); } else { return "".concat(origin).concat(requestStorageAccessPath); } }; var isLocalhost = function isLocalhost(url) { return url.match(/^https?:\/\/localhost/); }; /** * Fetches the landat path for request storage access page to navigate. This is typically CCP path or channel view * @returns {string} */ var getlandAtPath = function getlandAtPath() { if (!originalCCPUrl) { throw new Error('[StorageAccess] [getlandAtPath] Invoke connect.storageAccess.init first'); } if (isConnectDomain(originalCCPUrl) || isLocalhost(originalCCPUrl)) { var _URL2 = new URL(originalCCPUrl), pathname = _URL2.pathname; return pathname; } return '/connect/ccp-v2'; }; /** * * Method which returns the relative request-storage-access page path. * Validates against localhost and connect domains and returns prefixed path * @returns {string} */ var getRequestStorageAccessUrl = function getRequestStorageAccessUrl() { // ccpUrl may contain non standard direct SSO URLs in which case we may ask customers to provide instanceUrl as part of storage access params if (!originalCCPUrl) { throw new Error('[StorageAccess] [getRequestStorageAccessUrl] Invoke connect.storageAccess.init first'); } if (isConnectDomain(originalCCPUrl)) { return getRsaUrlWithprefix(originalCCPUrl); } else if (isLocalhost(originalCCPUrl)) { connect.getLog().info("[StorageAccess] [CCP] Local testing"); return "".concat(originalCCPUrl).concat(requestStorageAccessPath); } else if (storageParams.instanceUrl && isConnectDomain(storageParams.instanceUrl)) { connect.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Customer has provided storageParams.instanceUrl ".concat(storageParams.instanceUrl)); return getRsaUrlWithprefix(storageParams.instanceUrl); } else if (storageParams.instanceUrl && isLocalhost(storageParams.instanceUrl)) { connect.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Local testing"); return "".concat(storageParams.instanceUrl).concat(requestStorageAccessPath); } else { connect.getLog().error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the correct ccpUrl or storageAccess.instanceUrl parameters"); // FIXME - For test cases to succeed passing original parameter back instead throw an error by fixing all the CCP URL parameters accross the tests. throw new Error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the valid Connect CCP URL or in case CCP URL is configured to be the SSO URL then use storageAccess.instanceUrl and pass the Connect CCP URL"); } }; /** * Method which allows customers to listen on Storage access request and it's state changes * @param {Object} consists of callbacks for the onInit, onDeny and onGrants */ var onRequestHandler = function onRequestHandler(_ref) { var onInit = _ref.onInit, onDeny = _ref.onDeny, onGrant = _ref.onGrant; function handleUpstreamMessages(_ref2) { var data = _ref2.data, source = _ref2.source; var iframeContainer = connect.core._getCCPIframe(); if (iframeContainer.contentWindow !== source) { // disabling the logs for now // connect.getLog().error('[StorageAccess][onRequestHandler] Request Coming from unknown domain %s', origin); return false; } if (connect.core.initialized) { window.removeEventListener('message', handleUpstreamMessages); } switch (data.event) { case storageAccessEvents.INIT: { connect.getLog().info("[StorageAccess][INIT] message recieved").withObject(data); if (onInit) { onInit(data); } break; } case storageAccessEvents.GRANTED: { connect.getLog().info("[StorageAccess][GRANTED] message recieved").withObject(data); if (onGrant) { onGrant(data); } break; } case storageAccessEvents.DENIED: { connect.getLog().info("[StorageAccess][DENIED] message recieved").withObject(data); if (onDeny) { onDeny(data); } break; } default: { // Make sure to clean up the handler as soon as the access is granted. if (connect.core.initialized) { window.removeEventListener('message', handleUpstreamMessages); } break; } } } // do this only if canRequest is set to true if (storageParams.canRequest) { window.addEventListener('message', handleUpstreamMessages); } return { unsubscribe: function unsubscribe() { window.removeEventListener('message', handleUpstreamMessages); } }; }; /** * setupRequestHandlers - method which attaches post message handlers and let the initCCP flow to continue. * In case of custom CCPs - it also does hide/show the container. * @param {*} param0 */ var setupRequestHandlers = function setupRequestHandlers(_ref3) { var onGrantCallback = _ref3.onGrant; if (requesthandlerUnsubscriber) { requesthandlerUnsubscriber.unsubscribe(); } requesthandlerUnsubscriber = onRequestHandler({ onInit: function onInit(messageData) { console.log('%c[StorageAccess][INIT]', 'background:yellow; color:black; font-size:large'); connect.getLog().info("[StorageAccess][onInit] callback executed").withObject(messageData === null || messageData === void 0 ? void 0 : messageData.data); if (!(messageData !== null && messageData !== void 0 && messageData.data.hasAccess) && isCustomRequestAccessMode()) { getRSAContainer().show(); } }, onDeny: function onDeny() { console.log('%c[StorageAccess][DENIED]', 'background:red; color:black; font-size:large'); connect.getLog().info("[StorageAccess][onDeny] callback executed"); if (isCustomRequestAccessMode()) { getRSAContainer().show(); } }, onGrant: function onGrant() { console.log('%c[StorageAccess][GRANTED]', 'background:lime; color:black; font-size:large'); connect.getLog().info("[StorageAccess][onGrant] callback executed"); if (isCustomRequestAccessMode() && hideCCP()) { getRSAContainer().hide(); } // Invoke onGrantCallback only once as it setsup initCCP callbacks and events if (!onGrantCallbackInvoked) { onGrantCallback(); onGrantCallbackInvoked = true; } } }); }; connect.storageAccess = Object.freeze({ /** * Checks wther user has opted out for storage Access checks or not * @returns {boolean} */ canRequest: function canRequest() { return storageParams.canRequest; }, /** * Mainly used by Tests, by default storage access is enabled for all */ optOutFromRequestAccess: function optOutFromRequestAccess() { defaultStorageAccessParams.canRequest = false; }, /** * Mainly used by Tests */ optInForRequestAccess: function optInForRequestAccess() { defaultStorageAccessParams.canRequest = true; }, /** * Method which inits the Storage Access module with Customer paramters. * and generates request storage access URL and apply customization to the default paramters * @param {*} params - storage access params * @param {*} container - Container where CCP is being shown * @returns {{canRequest, requestAccessPageurl}} */ init: function init(ccpUrl, containerDiv) { var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; connect.assertNotNull(ccpUrl, 'ccpUrl'); connect.assertNotNull(containerDiv, 'container'); rsaContainer = containerDiv; originalCCPUrl = ccpUrl; initStorageParams(params); connect.getLog().info("[StorageAccess][init] Request Storage Acccess init called with ccpUrl - ".concat(ccpUrl, " - ").concat(!storageParams.canRequest ? 'user has opted out, skipping request storage access' : 'Proceeding with requesting storage access')).withObject(storageParams); }, setupRequestHandlers: setupRequestHandlers, getRequestStorageAccessUrl: getRequestStorageAccessUrl, storageAccessEvents: storageAccessEvents, resetStorageAccessState: resetStorageAccessState, getOnGrantCallbackInvoked: function getOnGrantCallbackInvoked() { return onGrantCallbackInvoked; }, getStorageAccessParams: function getStorageAccessParams() { return storageParams; }, onRequest: onRequestHandler, request: function request() { var iframeContainer = connect.core._getCCPIframe(); iframeContainer.contentWindow.postMessage({ event: storageAccessEvents.REQUEST, data: _objectSpread(_objectSpread({}, storageParams), {}, { landat: getlandAtPath() }) }, '*'); } }); })(); /***/ }), /***/ 906: /***/ (() => { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; var RingtoneEngineBase = function RingtoneEngineBase(ringtoneConfig) { connect.assertNotNull(ringtoneConfig, "ringtoneConfig"); this._audio = null; this._deviceId = ''; this._ringtoneUrl = ringtoneConfig.ringtoneUrl; this._loadRingtone(this._ringtoneUrl)["catch"](function () {}); // NEXT TODO: trigger ringtone load failure event this._driveRingtone(); }; // loading audio is async, but browser can handle audio operation like audio.play() or audio.setSinkId() before load complete RingtoneEngineBase.prototype._loadRingtone = function (ringtoneUrl) { var _this = this; return new Promise(function (resolve, reject) { if (!ringtoneUrl) { reject(Error('ringtoneUrl is required!')); } _this._audio = new Audio(ringtoneUrl); _this._audio.loop = true; _this.setOutputDevice(_this._deviceId); // re-applying deviceId for audio reloading scenario // just in case "canplay" doesn't fire at all for some reasons var timerId = setTimeout(function () { connect.getLog().warn("Ringtone isn't loaded in 1 second but proceeding: ", +ringtoneUrl).sendInternalLogToServer(); resolve(); }, 1000); _this._audio.addEventListener('canplay', function () { connect.getLog().info("Ringtone is ready to play: ", +ringtoneUrl).sendInternalLogToServer(); clearTimeout(timerId); resolve(); }); _this._audio.addEventListener('error', function () { connect.getLog().error("Ringtone load error: ", +ringtoneUrl).sendInternalLogToServer(); clearTimeout(timerId); reject(Error('Ringtone load error: ' + ringtoneUrl)); }); }); }; RingtoneEngineBase.prototype._driveRingtone = function () { throw new Error("Not implemented."); }; RingtoneEngineBase.prototype._startRingtone = /*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(contact) { var _this2 = this; var retries, errorList, _args2 = arguments; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: retries = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 0; errorList = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : []; return _context2.abrupt("return", new Promise(function (resolve, reject) { if (!_this2._audio) reject(Error('No audio object found')); // Empty string as sinkId means audio gets sent to the default device connect.getLog().info("Attempting to start ringtone to device ".concat(_this2._audio.sinkId || "''")).sendInternalLogToServer(); _this2._audio.play().then(function () { _this2._publishTelemetryEvent("Ringtone Start", contact); connect.getLog().info("Ringtone Start: Succeeded with ".concat(retries, " retries remaining")).withObject({ errorList: errorList, contactId: contact.getContactId() }).sendInternalLogToServer(); resolve(); })["catch"](/*#__PURE__*/function () { var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(e) { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: _this2._publishTelemetryEvent("Ringtone Playback Failure", contact); connect.getLog().error("Ringtone Playback Failure: ".concat(retries, " retries remaining.")).withException(e).withObject({ currentSrc: _this2._audio.currentSrc, sinkId: _this2._audio.sinkId, volume: _this2._audio.volume, contactId: contact.getContactId() }).sendInternalLogToServer(); errorList.push(e.toString()); if (!(retries > 0)) { _context.next = 10; break; } _context.next = 6; return _this2._loadRingtone(_this2._ringtoneUrl)["catch"](function () {}); case 6: _context.next = 8; return _this2._startRingtone(contact, retries - 1, errorList).then(resolve)["catch"](function () { return reject(errorList); }); case 8: _context.next = 12; break; case 10: connect.getLog().error("Ringtone Retries Exhausted").withObject({ errorList: errorList, contactId: contact.getContactId() }).sendInternalLogToServer(); reject(errorList); case 12: case "end": return _context.stop(); } }, _callee); })); return function (_x2) { return _ref2.apply(this, arguments); }; }()); })); case 3: case "end": return _context2.stop(); } }, _callee2); })); return function (_x) { return _ref.apply(this, arguments); }; }(); RingtoneEngineBase.prototype._stopRingtone = function (contact) { if (this._audio) { this._audio.pause(); this._audio.currentTime = 0; this._publishTelemetryEvent("Ringtone Stop", contact); connect.getLog().info("Ringtone Stop").sendInternalLogToServer(); } }; /** * Stop ringtone. */ RingtoneEngineBase.prototype.stopRingtone = function () { this._stopRingtone(); }; RingtoneEngineBase.prototype._ringtoneSetup = function (contact) { var self = this; connect.ifMaster(connect.MasterTopics.RINGTONE, function () { self._startRingtone(contact, 2)["catch"](function () {}); // NEXT TODO: trigger ringtone playback failure event with error type contact.onConnected(lily.hitch(self, self._stopRingtone)); contact.onAccepted(lily.hitch(self, self._stopRingtone)); contact.onEnded(lily.hitch(self, self._stopRingtone)); // Just to make sure to stop the ringtone in case of the failures of specific callbacks(onAccepted,onConnected); contact.onRefresh(function (contact) { if (contact.getStatus().type !== connect.ContactStatusType.CONNECTING && contact.getStatus().type !== connect.ContactStatusType.INCOMING) { self._stopRingtone(); } }); }); }; RingtoneEngineBase.prototype._publishTelemetryEvent = function (eventName, contact) { if (contact && contact.getContactId()) { connect.publishMetric({ name: eventName, contactId: contact.getContactId() }); } }; /** * Change the audio device used to play ringtone. * If audio element is not fully initialized, the API will wait _audioPlayablePromise for 3 seconds and fail on timeout. * This API is supported only by browsers that implemented ES6 Promise and http://www.w3.org/TR/audio-output/ * Return a Promise that indicates the result of changing output device. */ RingtoneEngineBase.prototype.setOutputDevice = function (deviceId) { var _this3 = this; return new Promise(function (resolve, reject) { if (_this3._audio && _this3._audio.setSinkId) { _this3._audio.setSinkId(deviceId).then(function () { _this3._deviceId = deviceId; resolve(deviceId); })["catch"](function (err) { reject("RingtoneEngineBase.setOutputDevice failed: audio.setSinkId() failed with error ".concat(err)); }); } else { reject("RingtoneEngineBase.setOutputDevice failed: ".concat(_this3._audio ? "audio" : "audio.setSinkId", " not found.")); } }); }; var VoiceRingtoneEngine = function VoiceRingtoneEngine(ringtoneConfig) { RingtoneEngineBase.call(this, ringtoneConfig); }; VoiceRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); VoiceRingtoneEngine.prototype.constructor = VoiceRingtoneEngine; VoiceRingtoneEngine.prototype._driveRingtone = function () { var _this4 = this; var onContactConnect = function onContactConnect(contact) { if (contact.getType() === connect.ContactType.VOICE && contact.isSoftphoneCall() && contact.isInbound()) { _this4._ringtoneSetup(contact); _this4._publishTelemetryEvent("Ringtone Connecting", contact); connect.getLog().info("Ringtone Connecting").sendInternalLogToServer(); } }; connect.contact(function (contact) { contact.onConnecting(onContactConnect); }); // handle the case where there's a contact already in connecting state at initialization new connect.Agent().getContacts().forEach(function (contact) { if (contact.getStatus().type === connect.ContactStatusType.CONNECTING) { onContactConnect(contact); } }); }; var ChatRingtoneEngine = function ChatRingtoneEngine(ringtoneConfig) { RingtoneEngineBase.call(this, ringtoneConfig); }; ChatRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); ChatRingtoneEngine.prototype.constructor = ChatRingtoneEngine; ChatRingtoneEngine.prototype._driveRingtone = function () { var self = this; var onContactConnect = function onContactConnect(contact) { if (contact.getType() === lily.ContactType.CHAT && contact.isInbound()) { var supervisorConnection = contact.getConnections().filter(function (conn) { return conn.getType() === connect.ConnectionType.AGENT && conn.isSilentMonitor(); }); if (supervisorConnection.length === 0) { self._ringtoneSetup(contact); self._publishTelemetryEvent("Chat Ringtone Connecting", contact); connect.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer(); } } }; connect.contact(function (contact) { contact.onConnecting(onContactConnect); }); }; var TaskRingtoneEngine = function TaskRingtoneEngine(ringtoneConfig) { RingtoneEngineBase.call(this, ringtoneConfig); }; TaskRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); TaskRingtoneEngine.prototype.constructor = TaskRingtoneEngine; TaskRingtoneEngine.prototype._driveRingtone = function () { var self = this; var onContactConnect = function onContactConnect(contact) { if (contact.getType() === lily.ContactType.TASK && contact.isInbound()) { self._ringtoneSetup(contact); self._publishTelemetryEvent("Task Ringtone Connecting", contact); connect.getLog().info("Task Ringtone Connecting").sendInternalLogToServer(); } }; connect.contact(function (contact) { contact.onConnecting(onContactConnect); }); }; /** * Extends the Base ringtone engine and enables the email ringtone engine. * @param {*} ringtoneConfig */ var EmailRingtoneEngine = function EmailRingtoneEngine(ringtoneConfig) { RingtoneEngineBase.call(this, ringtoneConfig); }; EmailRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); EmailRingtoneEngine.prototype.constructor = EmailRingtoneEngine; EmailRingtoneEngine.prototype._driveRingtone = function () { var self = this; var onContactConnect = function onContactConnect(contact) { if (contact.getType() === connect.ContactType.EMAIL && contact.isInbound()) { self._ringtoneSetup(contact); self._publishTelemetryEvent("Email Ringtone Connecting", contact); connect.getLog().info("Email Ringtone Connecting").sendInternalLogToServer(); } }; connect.contact(function (contact) { contact.onConnecting(onContactConnect); }); }; var QueueCallbackRingtoneEngine = function QueueCallbackRingtoneEngine(ringtoneConfig) { RingtoneEngineBase.call(this, ringtoneConfig); }; QueueCallbackRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); QueueCallbackRingtoneEngine.prototype.constructor = QueueCallbackRingtoneEngine; QueueCallbackRingtoneEngine.prototype._driveRingtone = function () { var self = this; connect.contact(function (contact) { contact.onIncoming(function () { if (contact.getType() === lily.ContactType.QUEUE_CALLBACK) { self._ringtoneSetup(contact); self._publishTelemetryEvent("Callback Ringtone Connecting", contact); connect.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer(); } }); }); }; /* export connect.RingtoneEngine */ connect.VoiceRingtoneEngine = VoiceRingtoneEngine; connect.ChatRingtoneEngine = ChatRingtoneEngine; connect.TaskRingtoneEngine = TaskRingtoneEngine; connect.QueueCallbackRingtoneEngine = QueueCallbackRingtoneEngine; connect.EmailRingtoneEngine = EmailRingtoneEngine; })(); /***/ }), /***/ 806: /***/ (() => { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; global.ccpVersion = "V2"; var VDIPlatformType = { CITRIX: "CITRIX", AWS_WORKSPACE: "AWS_WORKSPACE" }; var BROWSER_ID = "browserId"; // A key which is used for storing browser id value in local storage var statsReportingJobIntervalMs = 30000; var CallTypeMap = {}; CallTypeMap[connect.SoftphoneCallType.AUDIO_ONLY] = 'Audio'; CallTypeMap[connect.SoftphoneCallType.VIDEO_ONLY] = 'Video'; CallTypeMap[connect.SoftphoneCallType.AUDIO_VIDEO] = 'AudioVideo'; CallTypeMap[connect.SoftphoneCallType.NONE] = 'None'; var AUDIO_INPUT = 'audio_input'; var AUDIO_OUTPUT = 'audio_output'; var MediaTypeMap = {}; MediaTypeMap[connect.ContactType.VOICE] = "Voice"; var timeSeriesStreamStatsBuffer = []; // We buffer only last 3 hours (10800 seconds) of a call's RTP stream stats. var MAX_RTP_STREAM_STATS_BUFFER_SIZE = 10800; var inputRTPStreamStatsBuffer = []; var outputRTPStreamStatsBuffer = []; var aggregatedUserAudioStats = {}; var aggregatedRemoteAudioStats = {}; var LOW_AUDIO_LEVEL_THRESHOLD = 1; var consecutiveNoAudioInputPackets = 0; var consecutiveLowInputAudioLevel = 0; var consecutiveNoAudioOutputPackets = 0; var consecutiveLowOutputAudioLevel = 0; var audioInputConnectedDurationSeconds = 0; var consecutiveAudioOutputMuteDurationSeconds = 0; var isConnected = false; // Time from CCP received the softphone contact till local media is added to the softphone session var ccpMediaReadyLatencyMillis = 0; var allowEarlyGum = false; var earlyGumWorked = false; var vdiPlatform = null; var rtpStatsJob = null; var reportStatsJob = null; //Logger specific to softphone. var logger = null; var SoftphoneErrorTypes = connect.SoftphoneErrorTypes; var HANG_UP_MULTIPLE_SESSIONS_EVENT = "MultiSessionHangUp"; var ECHO_CANCELLATION_CHECK = "echoCancellationCheck"; var localMediaStream = {}; var softphoneClientId = connect.randomId(); var requestIceAccess = function requestIceAccess(transport) { return new Promise(function (resolve, reject) { connect.core.getClient().call(connect.ClientMethods.CREATE_TRANSPORT, transport, { success: function success(data) { resolve(data.softphoneTransport.softphoneMediaConnections); }, failure: function failure(reason) { if (reason.message && reason.message.includes("SoftphoneConnectionLimitBreachedException")) { publishError("multiple_softphone_active_sessions", "Number of active sessions are more then allowed limit.", ""); } reject(Error("requestIceAccess failed")); }, authFailure: function authFailure() { reject(Error("Authentication failed while requestIceAccess")); }, accessDenied: function accessDenied() { reject(Error("Access Denied while requestIceAccess")); } }); }); }; var _SoftphoneManager = function SoftphoneManager() { var _this = this; var softphoneParams = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var self = this; this.rtcPeerConnectionFactory = null; this.rtcJsStrategy = null; this.rtcPeerConnectionManager = null; this._setRtcJsStrategy = function () { if (softphoneParams.VDIPlatform) { vdiPlatform = softphoneParams.VDIPlatform; try { if (softphoneParams.VDIPlatform === VDIPlatformType.CITRIX) { this.rtcJsStrategy = new connect.CitrixVDIStrategy(); logger.info("[SoftphoneManager] Strategy constructor retrieved: ".concat(this.rtcJsStrategy)).sendInternalLogToServer(); } else if (softphoneParams.VDIPlatform === VDIPlatformType.AWS_WORKSPACE) { this.rtcJsStrategy = new connect.DCVWebRTCStrategy(); logger.info("[SoftphoneManager] Strategy constructor retrieved: ".concat(this.rtcJsStrategy)).sendInternalLogToServer(); } else { throw new Error("VDI Strategy not supported"); } } catch (error) { if (error.message === "VDI Strategy not supported") { publishError(SoftphoneErrorTypes.VDI_STRATEGY_NOT_SUPPORTED, error.message, ""); throw error; } else if (error.message === "Citrix WebRTC redirection feature is NOT supported!") { publishError(SoftphoneErrorTypes.VDI_REDIR_NOT_SUPPORTED, error.message, ""); throw error; } else if (error.message === "DCV WebRTC redirection feature is NOT supported!") { publishError(SoftphoneErrorTypes.VDI_REDIR_NOT_SUPPORTED, error.message, ""); throw error; } else { publishError(SoftphoneErrorTypes.OTHER, error.message, ""); throw error; } } } }; this._refreshRtcPeerConnectionFactory = function () { var _connect$core; if (connect !== null && connect !== void 0 && (_connect$core = connect.core) !== null && _connect$core !== void 0 && (_connect$core = _connect$core.softphoneManager) !== null && _connect$core !== void 0 && (_connect$core = _connect$core.rtcPeerConnectionFactory) !== null && _connect$core !== void 0 && _connect$core.close) { connect.core.softphoneManager.rtcPeerConnectionFactory.close(); } if (connect.RtcPeerConnectionFactory) { if (this.rtcJsStrategy) { this.rtcPeerConnectionFactory = new connect.RtcPeerConnectionFactory(logger, connect.core.getWebSocketManager(), softphoneClientId, connect.hitch(self, requestIceAccess, { transportType: "softphone", softphoneClientId: softphoneClientId }), connect.hitch(self, publishError), this.rtcJsStrategy); } else { this.rtcPeerConnectionFactory = new connect.RtcPeerConnectionFactory(logger, connect.core.getWebSocketManager(), softphoneClientId, connect.hitch(self, requestIceAccess, { transportType: "softphone", softphoneClientId: softphoneClientId }), connect.hitch(self, publishError)); } } }; // destroy or initiate persistent peer connection based on agent configuration change var listenAgentConfigurationUpdate = function listenAgentConfigurationUpdate() { connect.agent(function (a) { var sub = a.onRefresh(function (agent) { if (_this.rtcPeerConnectionManager) { var isPPCEnabled = agent.getConfiguration().softphonePersistentConnection; _this.rtcPeerConnectionManager.handlePersistentPeerConnectionToggle(isPPCEnabled); } else { _this._initiateRtcPeerConnectionManager(); } }); }); }; this._initiateRtcPeerConnectionManager = function () { var _connect$core2; // close existing peer connection managed by rtcPeerConnectionManager if (connect !== null && connect !== void 0 && (_connect$core2 = connect.core) !== null && _connect$core2 !== void 0 && (_connect$core2 = _connect$core2.softphoneManager) !== null && _connect$core2 !== void 0 && (_connect$core2 = _connect$core2.rtcPeerConnectionManager) !== null && _connect$core2 !== void 0 && _connect$core2.close) { connect.core.softphoneManager.rtcPeerConnectionManager.close(); connect.core.softphoneManager.rtcPeerConnectionManager = null; } var isPPCEnabled = softphoneParams.isSoftphonePersistentConnectionEnabled; // browserId will be used to handle browser page refresh, iceRestart scenarios var browserId; if (!global.localStorage.getItem(BROWSER_ID)) { global.localStorage.setItem(BROWSER_ID, AWS.util.uuid.v4()); } browserId = global.localStorage.getItem(BROWSER_ID); if (connect.RtcPeerConnectionManager) { var _self$rtcPeerConnecti; // Disable earlyGum and close rtcPeerConnectionFactory before creating RtcPeerConnectionManager allowEarlyGum = false; if ((_self$rtcPeerConnecti = self.rtcPeerConnectionFactory) !== null && _self$rtcPeerConnecti !== void 0 && _self$rtcPeerConnecti.close) { self.rtcPeerConnectionFactory.close(); self.rtcPeerConnectionFactory = null; } self.rtcPeerConnectionManager = new connect.RtcPeerConnectionManager(null, // signalingURI for ccpv1 null, // iceServers connect.hitch(self, requestIceAccess, { transportType: "softphone", softphoneClientId: softphoneClientId }), // transportHandle connect.hitch(self, publishError), // publishError softphoneClientId, // clientId null, // callContextToken logger, null, // contactId null, // agent connectionId connect.core.getWebSocketManager(), self.rtcJsStrategy === null ? new connect.StandardStrategy() : self.rtcJsStrategy, isPPCEnabled, browserId); } else { // customer who doesn't upgrade RTC.js will not be able to use RtcPeerConnectionManager to initialize persistent peer connection, but calls still work for them. logger.info("RtcPeerConnectionManager does NOT exist, please upgrade RTC.js"); } }; logger = new SoftphoneLogger(connect.getLog()); logger.info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(); if (softphoneParams.allowEarlyGum !== false && (connect.isChromeBrowser() || connect.isEdgeBrowser())) { logger.info("[Softphone Manager] earlyGum mechanism enabled").sendInternalLogToServer(); allowEarlyGum = true; } else { logger.info("[Softphone Manager] earlyGum mechanism NOT enabled").sendInternalLogToServer(); allowEarlyGum = false; } logger.info("[SoftphoneManager] Client Provided Strategy: ".concat(softphoneParams.VDIPlatform)).sendInternalLogToServer(); this._setRtcJsStrategy(); this._refreshRtcPeerConnectionFactory(); // initiate RtcPeerConnectionManager if (this.rtcPeerConnectionManager === null) { this._initiateRtcPeerConnectionManager(); } listenAgentConfigurationUpdate(); if (!_SoftphoneManager.isBrowserSoftPhoneSupported()) { publishError(SoftphoneErrorTypes.UNSUPPORTED_BROWSER, "Connect does not support this browser. Some functionality may not work. ", ""); } if (softphoneParams.VDIPlatform !== VDIPlatformType.AWS_WORKSPACE) { var gumPromise = fetchUserMedia({ success: function success(stream) { publishTelemetryEvent("ConnectivityCheckResult", null, { connectivityCheckType: "MicrophonePermission", status: "granted" }); publishTelemetryEvent("MicCheckSucceeded", null, { context: "Initializing Softphone Manager" }, true); }, failure: function failure(err) { publishError(err, "Your microphone is not enabled in your browser. ", ""); publishTelemetryEvent("ConnectivityCheckResult", null, { connectivityCheckType: "MicrophonePermission", status: "denied" }); publishTelemetryEvent("GumFailed", null, { context: "Initializing Softphone Manager" }, true); } }); } var onMuteSub = handleSoftPhoneMuteToggle(); var onSetSpeakerDeviceSub = handleSpeakerDeviceChange(); var onSetMicrophoneDeviceSub = handleMicrophoneDeviceChange(!softphoneParams.disableEchoCancellation); monitorMicrophonePermission(); this.ringtoneEngine = null; var rtcSessions = {}; // Tracks the agent connection ID, so that if the same contact gets re-routed to the same agent, it'll still set up softphone var callsDetected = {}; // variables for firefox multitab var isSessionPending = false; var pendingContact = null; var pendingAgentConnectionId = null; var postponeStartingSession = function postponeStartingSession(contact, agentConnectionId) { isSessionPending = true; pendingContact = contact; pendingAgentConnectionId = agentConnectionId; }; var cancelPendingSession = function cancelPendingSession() { isSessionPending = false; pendingContact = null; pendingAgentConnectionId = null; }; // helper method to provide access to rtc sessions this.getSession = function (connectionId) { return rtcSessions[connectionId]; }; this.replaceLocalMediaTrack = function (connectionId, track) { var stream = localMediaStream[connectionId].stream; if (stream) { var oldTrack = stream.getAudioTracks()[0]; track.enabled = oldTrack.enabled; oldTrack.enabled = false; stream.removeTrack(oldTrack); if (softphoneParams.VDIPlatform === VDIPlatformType.AWS_WORKSPACE) { oldTrack.stop(); } stream.addTrack(track); } }; var isContactTerminated = function isContactTerminated(contact) { return contact.getStatus().type === connect.ContactStatusType.ENDED || contact.getStatus().type === connect.ContactStatusType.ERROR || contact.getStatus().type === connect.ContactStatusType.MISSED; }; var destroySession = function destroySession(agentConnectionId) { if (rtcSessions.hasOwnProperty(agentConnectionId)) { var session = rtcSessions[agentConnectionId]; // Currently the assumption is it will throw an exception only and if only it already has been hung up. // TODO: Update once the hangup API does not throw exceptions new Promise(function (resolve, reject) { delete rtcSessions[agentConnectionId]; delete callsDetected[agentConnectionId]; // if rtcPeerConnectionManager exists, it will hang up the session if (_this.rtcPeerConnectionManager) { _this.rtcPeerConnectionManager.hangup(); } else { session.hangup(); } })["catch"](function (err) { lily.getLog().warn("There was an error destroying the softphone session for connection ID ".concat(agentConnectionId, " : ").concat(err.message)).withObject({ agentConnectionId: agentConnectionId, errorMessage: err.message }).sendInternalLogToServer(); }); } }; // When multiple RTC sessions detected, ignore the new call and hang up the previous sessions. // TODO: Update when connect-rtc exposes an API to detect session status. var sanityCheckActiveSessions = function sanityCheckActiveSessions(rtcSessions) { if (Object.keys(rtcSessions).length > 0) { // Error! our state doesn't match, tear it all down. for (var connectionId in rtcSessions) { if (rtcSessions.hasOwnProperty(connectionId)) { // Log an error for the session we are about to end. publishMultipleSessionsEvent(HANG_UP_MULTIPLE_SESSIONS_EVENT, rtcSessions[connectionId].callId, connectionId); destroySession(connectionId); } } throw new Error("duplicate session detected, refusing to setup new connection"); } }; this._clearAllSessions = function () { connect.getLog().info("Clearing all active sessions").sendInternalLogToServer(); for (var connectionId in rtcSessions) { if (rtcSessions.hasOwnProperty(connectionId)) { destroySession(connectionId); } } }; this.startSession = function (_contact, _agentConnectionId) { var contact = isSessionPending ? pendingContact : _contact; var agentConnectionId = isSessionPending ? pendingAgentConnectionId : _agentConnectionId; if (!contact || !agentConnectionId) { return; } cancelPendingSession(); // Set to true, this will block subsequent invokes from entering. callsDetected[agentConnectionId] = true; logger.info("Softphone call detected:", "contactId " + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); // Ensure our session state matches our contact state to prevent issues should we lose track of a contact. sanityCheckActiveSessions(rtcSessions); if (contact.getStatus().type === connect.ContactStatusType.CONNECTING) { publishTelemetryEvent("Softphone Connecting", contact.getContactId()); } initializeParams(); var softphoneInfo = contact.getAgentConnection().getSoftphoneMediaInfo(); var callConfig = parseCallConfig(softphoneInfo.callConfigJson); var webSocketProvider; if (callConfig.useWebSocketProvider) { webSocketProvider = connect.core.getWebSocketManager(); } // initialize rtcPeerConnectionManager if it is not existed if (this.rtcPeerConnectionManager === null) { this._initiateRtcPeerConnectionManager(); } var session; // if rtcPeerConnectionManager exists, it will create rtcSession object if (connect.RtcPeerConnectionManager && this.rtcPeerConnectionManager) { session = this.rtcPeerConnectionManager.createSession(contact.getContactId(), callConfig.iceServers, softphoneInfo.callContextToken, agentConnectionId, webSocketProvider, this.rtcJsStrategy === null ? new connect.StandardStrategy() : this.rtcJsStrategy); } else { if (this.rtcJsStrategy) { session = new connect.RTCSession(callConfig.signalingEndpoint, callConfig.iceServers, softphoneInfo.callContextToken, logger, contact.getContactId(), agentConnectionId, webSocketProvider, this.rtcJsStrategy); } else { session = new connect.RTCSession(callConfig.signalingEndpoint, callConfig.iceServers, softphoneInfo.callContextToken, logger, contact.getContactId(), agentConnectionId, webSocketProvider); } } session.echoCancellation = !softphoneParams.disableEchoCancellation; rtcSessions[agentConnectionId] = session; // Custom Event to indicate the session init operations connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConnectionEvents.SESSION_INIT, data: { connectionId: agentConnectionId } }); session.onSessionFailed = function (rtcSession, reason) { delete rtcSessions[agentConnectionId]; delete callsDetected[agentConnectionId]; publishSoftphoneFailureLogs(rtcSession, reason); publishSessionFailureTelemetryEvent(contact.getContactId(), reason); stopJobsAndReport(contact, rtcSession.sessionReport); }; session.onSessionConnected = function (rtcSession) { publishTelemetryEvent("Softphone Session Connected", contact.getContactId()); // Become master to send logs, since we need logs from softphone tab. connect.becomeMaster(connect.MasterTopics.SEND_LOGS); //start stats collection and reporting jobs startStatsCollectionJob(rtcSession); startStatsReportingJob(contact); fireContactAcceptedEvent(contact); }; session.onSessionCompleted = function (rtcSession) { publishTelemetryEvent("Softphone Session Completed", contact.getContactId()); delete rtcSessions[agentConnectionId]; delete callsDetected[agentConnectionId]; // Stop all jobs and perform one last job. stopJobsAndReport(contact, rtcSession.sessionReport); // Cleanup the cached streams deleteLocalMediaStream(agentConnectionId); }; session.onLocalStreamAdded = function (rtcSession, stream) { // Cache the streams for mute/unmute localMediaStream[agentConnectionId] = { stream: stream }; connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, data: { connectionId: agentConnectionId } }); }; session.remoteAudioElement = document.getElementById('remote-audio') || window.parent.parent.document.getElementById('remote-audio'); if (this.rtcPeerConnectionManager) { this.rtcPeerConnectionManager.connect(); } else { if (this.rtcPeerConnectionFactory) { session.connect(this.rtcPeerConnectionFactory.get(callConfig.iceServers)); } else { session.connect(); } } }; var onDestroyContact = function onDestroyContact(agentConnectionId) { // handle an edge case where a connecting contact gets cleared and the next agent snapshot doesn't contain the contact thus the onRefreshContact callback below can't properly clean up the stale session. if (rtcSessions[agentConnectionId]) { destroySession(agentConnectionId); } }; var onRefreshContact = function onRefreshContact(contact, agentConnectionId) { if (rtcSessions[agentConnectionId] && isContactTerminated(contact)) { destroySession(agentConnectionId); cancelPendingSession(); } if (contact.isSoftphoneCall() && !callsDetected[agentConnectionId] && (contact.getStatus().type === connect.ContactStatusType.CONNECTING || contact.getStatus().type === connect.ContactStatusType.INCOMING)) { publishTelemetryEvent('SoftphoneConfigDetected', contact.getContactId(), {}, true); if (connect.isFirefoxBrowser() && connect.hasOtherConnectedCCPs()) { logger.info('[Softphone Manager] Postpone starting session: ' + contact.getContactId()).sendInternalLogToServer(); postponeStartingSession(contact, agentConnectionId); } else { var _connect$core$userMed; if (allowEarlyGum && (_connect$core$userMed = connect.core.userMediaProvider) !== null && _connect$core$userMed !== void 0 && _connect$core$userMed.precapturedMediaStreamAvailable()) { earlyGumWorked = true; logger.info('[Softphone Manager] starting session using precapturedMediaStream').sendInternalLogToServer(); self.startSession(contact, agentConnectionId, connect.core.userMediaProvider.getPrecapturedMediaStream()); } else { earlyGumWorked = false; if (connect.core._isEarlyGumDisabled) { allowEarlyGum = false; } self.startSession(contact, agentConnectionId); } } } }; var onInitContact = function onInitContact(contact) { var agentConnectionId = contact.getAgentConnection().connectionId; logger.info("Contact detected:", "contactId " + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); if (!callsDetected[agentConnectionId]) { contact.onRefresh(function (_contact) { onRefreshContact(_contact, agentConnectionId); }); contact.onDestroy(function () { onDestroyContact(agentConnectionId); // clean up localMediaStream if (localMediaStream[agentConnectionId]) deleteLocalMediaStream(agentConnectionId); }); } }; var onInitContactSub = connect.contact(onInitContact); // Contact already in connecting state scenario - In this case contact INIT is missed hence the OnRefresh callback is missed. new connect.Agent().getContacts().forEach(function (contact) { var agentConnectionId = contact.getAgentConnection().connectionId; logger.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId" + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); onInitContact(contact); onRefreshContact(contact, agentConnectionId); }); this.terminate = function () { onInitContactSub && onInitContactSub.unsubscribe && onInitContactSub.unsubscribe(); onMuteSub && onMuteSub.unsubscribe && onMuteSub.unsubscribe(); onSetSpeakerDeviceSub && onSetSpeakerDeviceSub.unsubscribe && onSetSpeakerDeviceSub.unsubscribe(); onSetMicrophoneDeviceSub && onSetMicrophoneDeviceSub.unsubscribe && onSetMicrophoneDeviceSub.unsubscribe(); if (_this.rtcPeerConnectionFactory.clearIdleRtcPeerConnectionTimerId) { // This method needs to be called when destroying the softphone manager instance. // Otherwise the refresh loop in rtcPeerConnectionFactory will keep spawning WebRTCConnections every 60 seconds // and you will eventually get SoftphoneConnectionLimitBreachedException later. _this.rtcPeerConnectionFactory.clearIdleRtcPeerConnectionTimerId(); } _this.rtcPeerConnectionFactory = null; if (_this.rtcPeerConnectionManager && _this.rtcPeerConnectionManager.clearIdleRtcPeerConnectionTimerId) { _this.rtcPeerConnectionManager.clearIdleRtcPeerConnectionTimerId(); } }; }; var fireContactAcceptedEvent = function fireContactAcceptedEvent(contact) { var conduit = connect.core.getUpstream(); var agentConnection = contact.getAgentConnection(); if (!agentConnection) { logger.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer(); return; } var softphoneMediaInfo = agentConnection.getSoftphoneMediaInfo(); if (!softphoneMediaInfo) { logger.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer(); return; } if (softphoneMediaInfo.autoAccept === true) { logger.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(); conduit.sendUpstream(connect.EventType.BROADCAST, { event: connect.ContactEvents.ACCEPTED, data: new connect.Contact(contact.contactId) }); conduit.sendUpstream(connect.EventType.BROADCAST, { event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, contact.contactId), data: new connect.Contact(contact.contactId) }); } else { logger.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer(); } }; // Bind events for mute var handleSoftPhoneMuteToggle = function handleSoftPhoneMuteToggle() { var bus = connect.core.getEventBus(); return bus.subscribe(connect.EventType.MUTE, muteToggle); }; var handleSpeakerDeviceChange = function handleSpeakerDeviceChange() { var bus = connect.core.getEventBus(); return bus.subscribe(connect.ConfigurationEvents.SET_SPEAKER_DEVICE, setSpeakerDevice); }; var handleMicrophoneDeviceChange = function handleMicrophoneDeviceChange(enableEchoCancellation) { var bus = connect.core.getEventBus(); return bus.subscribe(connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, function (data) { return setMicrophoneDevice(_objectSpread(_objectSpread({}, data), {}, { enableEchoCancellation: enableEchoCancellation })); }); }; var monitorMicrophonePermission = function monitorMicrophonePermission() { try { if (connect.isChromeBrowser() && connect.getChromeBrowserVersion() > 43) { navigator.permissions.query({ name: 'microphone' }).then(function (permissionStatus) { permissionStatus.onchange = function () { logger.info("Microphone Permission: " + permissionStatus.state); publishTelemetryEvent("ConnectivityCheckResult", null, { connectivityCheckType: "MicrophonePermission", status: permissionStatus.state }); if (permissionStatus.state === 'denied') { publishError(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED, "Your microphone is not enabled in your browser. ", ""); } }; }); } } catch (e) { logger.error("Failed in detecting microphone permission status: " + e); } }; // Make sure once we disconnected we get the mute state back to normal var deleteLocalMediaStream = function deleteLocalMediaStream(connectionId) { delete localMediaStream[connectionId]; connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.AgentEvents.MUTE_TOGGLE, data: { muted: false } }); }; // Check for the local streams if exists - revert it // And inform other clients about the change var muteToggle = function muteToggle(data) { var status; if (connect.keys(localMediaStream).length === 0) { return; } if (data && data.mute !== undefined) { status = data.mute; } for (var connectionId in localMediaStream) { if (localMediaStream.hasOwnProperty(connectionId)) { var localMedia = localMediaStream[connectionId].stream; if (localMedia) { var audioTracks = localMedia.getAudioTracks()[0]; if (status !== undefined) { audioTracks.enabled = !status; localMediaStream[connectionId].muted = status; if (status) { logger.info("Agent has muted the contact, connectionId - " + connectionId).sendInternalLogToServer(); } else { logger.info("Agent has unmuted the contact, connectionId - " + connectionId).sendInternalLogToServer(); } } else { status = localMediaStream[connectionId].muted || false; } } } } connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.AgentEvents.MUTE_TOGGLE, data: { muted: status } }); }; var setSpeakerDevice = function setSpeakerDevice() { var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var deviceId = data.deviceId || ''; connect.getLog().info("[Audio Device Settings] Attempting to set speaker device ".concat(deviceId)).sendInternalLogToServer(); if (!deviceId) { connect.getLog().warn("[Audio Device Settings] Setting speaker device cancelled due to missing deviceId").sendInternalLogToServer(); return; } var remoteAudioElement = document.getElementById('remote-audio') || window.parent.parent.document.getElementById('remote-audio'); if (remoteAudioElement && typeof remoteAudioElement.setSinkId === 'function') { remoteAudioElement.setSinkId(deviceId).then(function () { connect.getLog().info("[Audio Device Settings] Speaker device ".concat(deviceId, " successfully set to speaker audio element")).sendInternalLogToServer(); connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, data: { deviceId: deviceId } }); })["catch"](function (e) { connect.getLog().error("[Audio Device Settings] Failed to set speaker device " + deviceId).withException(e).sendInternalLogToServer(); }); } else { connect.getLog().warn("[Audio Device Settings] Setting speaker device cancelled due to missing remoteAudioElement").sendInternalLogToServer(); } }; var setMicrophoneDevice = function setMicrophoneDevice() { var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var deviceId = data.deviceId || ''; connect.getLog().info("[Audio Device Settings] Attempting to set microphone device ".concat(deviceId)).sendInternalLogToServer(); if (connect.keys(localMediaStream).length === 0) { connect.getLog().warn("[Audio Device Settings] Setting microphone device cancelled due to missing localMediaStream").sendInternalLogToServer(); return; } if (!deviceId) { connect.getLog().warn("[Audio Device Settings] Setting microphone device cancelled due to missing deviceId").sendInternalLogToServer(); return; } var softphoneManager = connect.core.getSoftphoneManager(); var CONSTRAINT = { audio: { deviceId: { exact: deviceId } } }; if (!data.enableEchoCancellation) CONSTRAINT.audio.echoCancellation = false; connect.publishMetric({ name: ECHO_CANCELLATION_CHECK, data: { count: 1, disableEchoCancellation: !data.enableEchoCancellation } }); navigator.mediaDevices.getUserMedia(CONSTRAINT).then(function (newMicrophoneStream) { try { var newMicrophoneTrack = newMicrophoneStream.getAudioTracks()[0]; for (var connectionId in localMediaStream) { if (localMediaStream.hasOwnProperty(connectionId)) { var localMedia = localMediaStream[connectionId].stream; var session = softphoneManager.getSession(connectionId); //Replace the audio track in the RtcPeerConnection session._pc.getSenders()[0].replaceTrack(newMicrophoneTrack).then(function () { //Replace the audio track in the local media stream (for mute / unmute) softphoneManager.replaceLocalMediaTrack(connectionId, newMicrophoneTrack); session._isUserProvidedStream = true; connect.getLog().info("[Audio Device Settings] Microphone device ".concat(deviceId, " successfully set to local media stream in RTCRtpSender")).sendInternalLogToServer(); }); } } } catch (e) { connect.getLog().error("[Audio Device Settings] Failed to set microphone device " + deviceId).withException(e).sendInternalLogToServer(); return; } connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, data: { deviceId: deviceId } }); })["catch"](function (e) { connect.getLog().error("[Audio Device Settings] Failed to set microphone device " + deviceId).withException(e).sendInternalLogToServer(); }); }; var publishSoftphoneFailureLogs = function publishSoftphoneFailureLogs(rtcSession, reason) { if (reason === connect.RTCErrors.ICE_COLLECTION_TIMEOUT) { var endPointUrl = "\n"; for (var i = 0; i < rtcSession._iceServers.length; i++) { for (var j = 0; j < rtcSession._iceServers[i].urls.length; j++) { endPointUrl = endPointUrl + rtcSession._iceServers[i].urls[j] + "\n"; } } publishError(SoftphoneErrorTypes.ICE_COLLECTION_TIMEOUT, "Ice collection timedout. ", endPointUrl); } else if (reason === connect.RTCErrors.USER_BUSY) { publishError(SoftphoneErrorTypes.USER_BUSY_ERROR, "Softphone call UserBusy error. ", ""); } else if (reason === connect.RTCErrors.SIGNALLING_HANDSHAKE_FAILURE) { publishError(SoftphoneErrorTypes.SIGNALLING_HANDSHAKE_FAILURE, "Handshaking with Signalling Server " + rtcSession._signalingUri + " failed. ", rtcSession._signalingUri); } else if (reason === connect.RTCErrors.GUM_TIMEOUT_FAILURE || reason === connect.RTCErrors.GUM_OTHER_FAILURE) { publishError(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED, "Your microphone is not enabled in your browser. ", ""); } else if (reason === connect.RTCErrors.SIGNALLING_CONNECTION_FAILURE) { publishError(SoftphoneErrorTypes.SIGNALLING_CONNECTION_FAILURE, "URL " + rtcSession._signalingUri + " cannot be reached. ", rtcSession._signalingUri); } else if (reason === connect.RTCErrors.CALL_NOT_FOUND) { // No need to publish any softphone error for this case. CCP UX will handle this case. logger.error("Softphone call failed due to CallNotFoundException.").sendInternalLogToServer(); } else { publishError(SoftphoneErrorTypes.WEBRTC_ERROR, "webrtc system error. ", ""); } }; /** Parse the JSON encoded web call config into the data it represents. */ var parseCallConfig = function parseCallConfig(serializedConfig) { // Our underscore is too old for unescape // https://issues.amazon.com/issues/CSWF-1467 var decodedJSON = serializedConfig.replace(/"/g, '"'); return JSON.parse(decodedJSON); }; var fetchUserMedia = function fetchUserMedia(callbacksIn) { var callbacks = callbacksIn || {}; callbacks.success = callbacks.success || function () {}; callbacks.failure = callbacks.failure || function () {}; var CONSTRAINT = { audio: true }; var promise = null; if (typeof Promise !== "function") { callbacks.failure(SoftphoneErrorTypes.UNSUPPORTED_BROWSER); return; } if (_typeof(navigator.mediaDevices) === "object" && typeof navigator.mediaDevices.getUserMedia === "function") { promise = navigator.mediaDevices.getUserMedia(CONSTRAINT); } else if (typeof navigator.webkitGetUserMedia === "function") { promise = new Promise(function (resolve, reject) { navigator.webkitGetUserMedia(CONSTRAINT, resolve, reject); }); } else { callbacks.failure(SoftphoneErrorTypes.UNSUPPORTED_BROWSER); return; } promise.then(function (stream) { var audioTracks = stream.getAudioTracks(); if (audioTracks && audioTracks.length > 0) { callbacks.success(stream); } else { callbacks.failure(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED); } }, function (err) { callbacks.failure(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED); }); return promise; }; var publishError = function publishError(errorType, message, endPointUrl) { logger.error("Softphone error occurred : ", errorType, message || "").sendInternalLogToServer(); connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.AgentEvents.SOFTPHONE_ERROR, data: new connect.SoftphoneError(errorType, message, endPointUrl) }); }; var publishSessionFailureTelemetryEvent = function publishSessionFailureTelemetryEvent(contactId, reason) { publishTelemetryEvent("Softphone Session Failed", contactId, { failedReason: reason }); }; var publishTelemetryEvent = function publishTelemetryEvent(eventName, contactId, data) { connect.publishMetric({ name: eventName, contactId: contactId, data: data }); }; // Publish the contact and agent information in a multiple sessions scenarios var publishMultipleSessionsEvent = function publishMultipleSessionsEvent(eventName, contactId, agentConnectionId) { publishTelemetryEvent(eventName, contactId, [{ name: "AgentConnectionId", value: agentConnectionId }]); logger.info("Publish multiple session error metrics", eventName, "contactId " + contactId, "agent connectionId " + agentConnectionId).sendInternalLogToServer(); }; _SoftphoneManager.isBrowserSoftPhoneSupported = function () { // In Opera, the true version is after "Opera" or after "Version" if (connect.isOperaBrowser() && connect.getOperaBrowserVersion() > 17) { return true; } // In Chrome, the true version is after "Chrome" else if (connect.isChromeBrowser() && connect.getChromeBrowserVersion() > 22) { return true; } // In Firefox, the true version is after "Firefox" else if (connect.isFirefoxBrowser() && connect.getFirefoxBrowserVersion() > 21) { return true; } else { return false; } }; var sendSoftphoneMetrics = function sendSoftphoneMetrics(contact) { var streamStats = timeSeriesStreamStatsBuffer.slice(); timeSeriesStreamStatsBuffer = []; if (streamStats.length > 0) { contact.sendSoftphoneMetrics(streamStats, { success: function success() { logger.info("sendSoftphoneMetrics success" + JSON.stringify(streamStats)).sendInternalLogToServer(); }, failure: function failure(data) { logger.error("sendSoftphoneMetrics failed.").withObject(data).sendInternalLogToServer(); } }); } }; var sendSoftphoneReport = function sendSoftphoneReport(contact, report, userAudioStats, remoteAudioStats) { report.streamStats = [addStreamTypeToStats(userAudioStats, AUDIO_INPUT), addStreamTypeToStats(remoteAudioStats, AUDIO_OUTPUT)]; var callReport = { callStartTime: report.sessionStartTime, callEndTime: report.sessionEndTime, gumTimeMillis: report.gumTimeMillis, initializationTimeMillis: report.initializationTimeMillis, iceCollectionTimeMillis: report.iceCollectionTimeMillis, signallingConnectTimeMillis: report.signallingConnectTimeMillis, handshakingTimeMillis: report.handshakingTimeMillis, preTalkingTimeMillis: report.preTalkingTimeMillis, talkingTimeMillis: report.talkingTimeMillis, cleanupTimeMillis: report.cleanupTimeMillis, iceCollectionFailure: report.iceCollectionFailure, signallingConnectionFailure: report.signallingConnectionFailure, handshakingFailure: report.handshakingFailure, gumOtherFailure: report.gumOtherFailure, gumTimeoutFailure: report.gumTimeoutFailure, createOfferFailure: report.createOfferFailure, setLocalDescriptionFailure: report.setLocalDescriptionFailure, userBusyFailure: report.userBusyFailure, invalidRemoteSDPFailure: report.invalidRemoteSDPFailure, noRemoteIceCandidateFailure: report.noRemoteIceCandidateFailure, setRemoteDescriptionFailure: report.setRemoteDescriptionFailure, softphoneStreamStatistics: report.streamStats }; contact.sendSoftphoneReport(callReport, { success: function success() { logger.info("sendSoftphoneReport success" + JSON.stringify(callReport)).sendInternalLogToServer(); }, failure: function failure(data) { logger.error("sendSoftphoneReport failed.").withObject(data).sendInternalLogToServer(); } }); var streamPerSecondStats = { AUDIO_INPUT: { packetsCount: inputRTPStreamStatsBuffer.map(function (stats) { return stats.packetsCount; }), packetsLost: inputRTPStreamStatsBuffer.map(function (stats) { return stats.packetsLost; }), audioLevel: inputRTPStreamStatsBuffer.map(function (stats) { return stats.audioLevel; }), jitterBufferMillis: inputRTPStreamStatsBuffer.map(function (stats) { return stats.jitterBufferMillis; }) }, AUDIO_OUTPUT: { packetsCount: outputRTPStreamStatsBuffer.map(function (stats) { return stats.packetsCount; }), packetsLost: outputRTPStreamStatsBuffer.map(function (stats) { return stats.packetsLost; }), audioLevel: outputRTPStreamStatsBuffer.map(function (stats) { return stats.audioLevel; }), jitterBufferMillis: outputRTPStreamStatsBuffer.map(function (stats) { return stats.jitterBufferMillis; }), roundTripTimeMillis: outputRTPStreamStatsBuffer.map(function (stats) { return stats.roundTripTimeMillis; }) } }; var telemetryCallReport = _objectSpread(_objectSpread({}, callReport), {}, { softphoneStreamPerSecondStatistics: streamPerSecondStats, iceConnectionsLost: report.iceConnectionsLost, iceConnectionsFailed: report.iceConnectionsFailed || null, peerConnectionFailed: report.peerConnectionFailed || null, rtcJsVersion: report.rtcJsVersion || null, firstRTPTimeMillis: report.firstRTPTimeMillis || null, isMediaClusterPath: report.isMediaClusterPath, isPersistentPeerConnection: report.isPersistentPeerConnection, isExistingPersistentPeerConnection: report.isExistingPersistentPeerConnection || false, consecutiveNoAudioInputPackets: consecutiveNoAudioInputPackets, consecutiveLowInputAudioLevel: consecutiveLowInputAudioLevel, consecutiveNoAudioOutputPackets: consecutiveNoAudioOutputPackets, consecutiveLowOutputAudioLevel: consecutiveLowOutputAudioLevel, audioInputConnectedDurationSeconds: audioInputConnectedDurationSeconds, ccpMediaReadyLatencyMillis: ccpMediaReadyLatencyMillis, contactSubtype: contact.getContactSubtype(), earlyGumEnabled: allowEarlyGum, earlyGumWorked: earlyGumWorked, vdiPlatform: vdiPlatform || null, userAgentData: report.userAgentData || null, isConnected: isConnected, consecutiveAudioOutputMuteDurationSeconds: consecutiveAudioOutputMuteDurationSeconds, streamJsVersion: connect.version }); ccpMediaReadyLatencyMillis = 0; isConnected = false; consecutiveAudioOutputMuteDurationSeconds = 0; connect.publishSoftphoneReport({ contactId: contact.getContactId(), ccpVersion: global.ccpVersion, report: telemetryCallReport }); logger.info("sent TelemetryCallReport " + JSON.stringify(telemetryCallReport)).sendInternalLogToServer(); }; var startStatsCollectionJob = function startStatsCollectionJob(rtcSession) { rtpStatsJob = window.setInterval(function () { var _rtcSession$mediaStre; rtcSession.getUserAudioStats().then(function (stats) { var previousUserStats = aggregatedUserAudioStats; aggregatedUserAudioStats = stats; var currRTPStreamStat = getTimeSeriesStats(aggregatedUserAudioStats, previousUserStats, AUDIO_INPUT); timeSeriesStreamStatsBuffer.push(currRTPStreamStat); telemetryCallReportRTPStreamStatsBuffer(currRTPStreamStat); }, function (error) { logger.debug("Failed to get user audio stats.", error).sendInternalLogToServer(); }); rtcSession.getRemoteAudioStats().then(function (stats) { var previousRemoteStats = aggregatedRemoteAudioStats; aggregatedRemoteAudioStats = stats; var currRTPStreamStat = getTimeSeriesStats(aggregatedRemoteAudioStats, previousRemoteStats, AUDIO_OUTPUT); timeSeriesStreamStatsBuffer.push(currRTPStreamStat); telemetryCallReportRTPStreamStatsBuffer(currRTPStreamStat); }, function (error) { logger.debug("Failed to get remote audio stats.", error).sendInternalLogToServer(); }); if (rtcSession !== null && rtcSession !== void 0 && (_rtcSession$mediaStre = rtcSession.mediaStream) !== null && _rtcSession$mediaStre !== void 0 && (_rtcSession$mediaStre = _rtcSession$mediaStre.getAudioTracks()) !== null && _rtcSession$mediaStre !== void 0 && (_rtcSession$mediaStre = _rtcSession$mediaStre[0]) !== null && _rtcSession$mediaStre !== void 0 && _rtcSession$mediaStre.enabled) { consecutiveAudioOutputMuteDurationSeconds = 0; } else { consecutiveAudioOutputMuteDurationSeconds++; } }, 1000); }; var startStatsReportingJob = function startStatsReportingJob(contact) { reportStatsJob = window.setInterval(function () { sendSoftphoneMetrics(contact); }, statsReportingJobIntervalMs); }; var initializeParams = function initializeParams() { aggregatedUserAudioStats = null; aggregatedRemoteAudioStats = null; timeSeriesStreamStatsBuffer = []; inputRTPStreamStatsBuffer = []; outputRTPStreamStatsBuffer = []; rtpStatsJob = null; reportStatsJob = null; consecutiveNoAudioInputPackets = 0; consecutiveLowInputAudioLevel = 0; consecutiveNoAudioOutputPackets = 0; consecutiveLowOutputAudioLevel = 0; audioInputConnectedDurationSeconds = 0; }; var getTimeSeriesStats = function getTimeSeriesStats(currentStats, previousStats, streamType) { if (previousStats && currentStats) { var packetsLost = currentStats.packetsLost > previousStats.packetsLost ? currentStats.packetsLost - previousStats.packetsLost : 0; var packetsCount = currentStats.packetsCount > previousStats.packetsCount ? currentStats.packetsCount - previousStats.packetsCount : 0; checkConsecutiveNoPackets(packetsCount, streamType); checkConsecutiveNoAudio(currentStats.audioLevel, streamType); return new RTPStreamStats(currentStats.timestamp, packetsLost, packetsCount, streamType, currentStats.audioLevel, currentStats.jbMilliseconds, currentStats.rttMilliseconds); } else { return new RTPStreamStats(currentStats.timestamp, currentStats.packetsLost, currentStats.packetsCount, streamType, currentStats.audioLevel, currentStats.jbMilliseconds, currentStats.rttMilliseconds); } }; var telemetryCallReportRTPStreamStatsBuffer = function telemetryCallReportRTPStreamStatsBuffer(rtpStreamStats) { if (rtpStreamStats.softphoneStreamType === AUDIO_INPUT) { while (inputRTPStreamStatsBuffer.length >= MAX_RTP_STREAM_STATS_BUFFER_SIZE) { inputRTPStreamStatsBuffer.shift(); } inputRTPStreamStatsBuffer.push(rtpStreamStats); } else if (rtpStreamStats.softphoneStreamType === AUDIO_OUTPUT) { while (outputRTPStreamStatsBuffer.length >= MAX_RTP_STREAM_STATS_BUFFER_SIZE) { outputRTPStreamStatsBuffer.shift(); } outputRTPStreamStatsBuffer.push(rtpStreamStats); } }; var checkConsecutiveNoPackets = function checkConsecutiveNoPackets(packetsCount, streamType) { if (streamType === AUDIO_INPUT) { audioInputConnectedDurationSeconds++; if (packetsCount <= 0) { consecutiveNoAudioInputPackets++; } else { consecutiveNoAudioInputPackets = 0; } } else if (streamType === AUDIO_OUTPUT) { if (packetsCount <= 0) { consecutiveNoAudioOutputPackets++; } else { consecutiveNoAudioOutputPackets = 0; } } }; var checkConsecutiveNoAudio = function checkConsecutiveNoAudio(audioLevel, streamType) { if (streamType === AUDIO_INPUT) { if (audioLevel !== null && audioLevel <= LOW_AUDIO_LEVEL_THRESHOLD) { consecutiveLowInputAudioLevel++; } else { consecutiveLowInputAudioLevel = 0; } } else if (streamType === AUDIO_OUTPUT) { if (audioLevel !== null && audioLevel <= LOW_AUDIO_LEVEL_THRESHOLD) { consecutiveLowOutputAudioLevel++; } else { consecutiveLowOutputAudioLevel = 0; } } }; var stopJob = function stopJob(task) { if (task !== null) { window.clearInterval(task); } return null; }; var stopJobsAndReport = function stopJobsAndReport(contact, sessionReport) { rtpStatsJob = stopJob(rtpStatsJob); reportStatsJob = stopJob(reportStatsJob); sendSoftphoneReport(contact, sessionReport, addStreamTypeToStats(aggregatedUserAudioStats, AUDIO_INPUT), addStreamTypeToStats(aggregatedRemoteAudioStats, AUDIO_OUTPUT)); sendSoftphoneMetrics(contact); }; /** * Adding streamtype parameter on top of RTCJS RTStats object. */ var RTPStreamStats = function RTPStreamStats(timestamp, packetsLost, packetsCount, streamType, audioLevel, jitterBufferMillis, roundTripTimeMillis) { this.softphoneStreamType = streamType; this.timestamp = timestamp; this.packetsLost = packetsLost; this.packetsCount = packetsCount; this.audioLevel = audioLevel; this.jitterBufferMillis = jitterBufferMillis; this.roundTripTimeMillis = roundTripTimeMillis; }; var addStreamTypeToStats = function addStreamTypeToStats(stats, streamType) { stats = stats || {}; return new RTPStreamStats(stats.timestamp, stats.packetsLost, stats.packetsCount, streamType, stats.audioLevel); }; var SoftphoneLogger = function SoftphoneLogger(logger) { this._originalLogger = logger; var self = this; this._tee = function (level, method) { return function () { // call the original logger object to output to browser //Connect logger follows %s format to print objects to console. var args = Array.prototype.slice.call(arguments[0]); var format = ""; args.forEach(function () { format = format + " %s"; }); return method.apply(self._originalLogger, [connect.LogComponent.SOFTPHONE, format].concat(args)); }; }; }; SoftphoneLogger.prototype.debug = function () { return this._tee(1, this._originalLogger.debug)(arguments); }; SoftphoneLogger.prototype.info = function () { return this._tee(2, this._originalLogger.info)(arguments); }; SoftphoneLogger.prototype.log = function () { return this._tee(3, this._originalLogger.log)(arguments); }; SoftphoneLogger.prototype.warn = function () { return this._tee(4, this._originalLogger.warn)(arguments); }; SoftphoneLogger.prototype.error = function () { return this._tee(5, this._originalLogger.error)(arguments); }; connect.SoftphoneManager = _SoftphoneManager; })(); /***/ }), /***/ 344: /***/ (() => { /*! @license sprintf.js | Copyright (c) 2007-2013 Alexandru Marasteanu | 3 clause BSD license */ (function () { var ctx = this || globalThis; var _sprintf = function sprintf() { if (!_sprintf.cache.hasOwnProperty(arguments[0])) { _sprintf.cache[arguments[0]] = _sprintf.parse(arguments[0]); } return _sprintf.format.call(null, _sprintf.cache[arguments[0]], arguments); }; _sprintf.format = function (parse_tree, argv) { var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length; for (i = 0; i < tree_length; i++) { node_type = get_type(parse_tree[i]); if (node_type === 'string') { output.push(parse_tree[i]); } else if (node_type === 'array') { match = parse_tree[i]; // convenience purposes only if (match[2]) { // keyword argument arg = argv[cursor]; for (k = 0; k < match[2].length; k++) { if (!arg.hasOwnProperty(match[2][k])) { throw _sprintf('[sprintf] property "%s" does not exist', match[2][k]); } arg = arg[match[2][k]]; } } else if (match[1]) { // positional argument (explicit) arg = argv[match[1]]; } else { // positional argument (implicit) arg = argv[cursor++]; } if (/[^s]/.test(match[8]) && get_type(arg) != 'number') { throw _sprintf('[sprintf] expecting number but found %s', get_type(arg)); } switch (match[8]) { case 'b': arg = arg.toString(2); break; case 'c': arg = String.fromCharCode(arg); break; case 'd': arg = parseInt(arg, 10); break; case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break; case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break; case 'o': arg = arg.toString(8); break; case 's': arg = (arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg; break; case 'u': arg = arg >>> 0; break; case 'x': arg = arg.toString(16); break; case 'X': arg = arg.toString(16).toUpperCase(); break; } arg = /[def]/.test(match[8]) && match[3] && arg >= 0 ? '+' + arg : arg; pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; pad_length = match[6] - String(arg).length; pad = match[6] ? str_repeat(pad_character, pad_length) : ''; output.push(match[5] ? arg + pad : pad + arg); } } return output.join(''); }; _sprintf.cache = {}; _sprintf.parse = function (fmt) { var _fmt = fmt, match = [], parse_tree = [], arg_names = 0; while (_fmt) { if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { parse_tree.push(match[0]); } else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { parse_tree.push('%'); } else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { if (match[2]) { arg_names |= 1; var field_list = [], replacement_field = match[2], field_match = []; if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { field_list.push(field_match[1]); while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { field_list.push(field_match[1]); } else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { field_list.push(field_match[1]); } else { throw '[sprintf] huh?'; } } } else { throw '[sprintf] huh?'; } match[2] = field_list; } else { arg_names |= 2; } if (arg_names === 3) { throw '[sprintf] mixing positional and named placeholders is not (yet) supported'; } parse_tree.push(match); } else { throw '[sprintf] huh?'; } _fmt = _fmt.substring(match[0].length); } return parse_tree; }; var vsprintf = function vsprintf(fmt, argv, _argv) { _argv = argv.slice(0); _argv.splice(0, 0, fmt); return _sprintf.apply(null, _argv); }; /** * helpers */ function get_type(variable) { return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); } function str_repeat(input, multiplier) { for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */} return output.join(''); } /** * export to either browser or node.js */ ctx.sprintf = _sprintf; ctx.vsprintf = vsprintf; })(); /***/ }), /***/ 431: /***/ (() => { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; /**--------------------------------------------------------------- * class Stream * * Represents an object from which messages can be read and to which * messages can be sent. */ var Stream = function Stream() {}; /** * Send a message to the stream. This method must be implemented by subclasses. */ Stream.prototype.send = function (message) { throw new connect.NotImplementedError(); }; /** * Provide a method to be called when messages are received from this stream. * This method must be implemented by subclasses. */ Stream.prototype.onMessage = function (f) { throw new connect.NotImplementedError(); }; /**--------------------------------------------------------------- * class NullStream extends Stream * * A null stream which provides no message sending or receiving facilities. */ var NullStream = function NullStream() { Stream.call(this); }; NullStream.prototype = Object.create(Stream.prototype); NullStream.prototype.constructor = NullStream; NullStream.prototype.onMessage = function (f) {}; NullStream.prototype.send = function (message) {}; /**--------------------------------------------------------------- * class WindowStream extends Stream * * A stream for communicating with a window object. The domain provided * must match the allowed message domains of the downstream receiver * or messages will be rejected, see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage * for more info. */ var WindowStream = function WindowStream(win, domain) { Stream.call(this); this.window = win; this.domain = domain || '*'; }; WindowStream.prototype = Object.create(Stream.prototype); WindowStream.prototype.constructor = WindowStream; WindowStream.prototype.send = function (message) { this.window.postMessage(message, this.domain); }; WindowStream.prototype.onMessage = function (f) { this.window.addEventListener("message", f); }; /**--------------------------------------------------------------- * class WindowIOStream extends Stream * * A stream used by IFrame/popup windows to communicate with their parents * and vise versa. * * This object encapsulates the fact that incoming and outgoing messages * arrive on different windows and allows this to be managed as a single * Stream object. */ var WindowIOStream = function WindowIOStream(inputwin, outputwin, domain) { Stream.call(this); this.input = inputwin; this.output = outputwin; this.domain = domain || '*'; }; WindowIOStream.prototype = Object.create(Stream.prototype); WindowIOStream.prototype.constructor = WindowIOStream; WindowIOStream.prototype.send = function (message) { this.output.postMessage(message, this.domain); }; WindowIOStream.prototype.onMessage = function (f) { var _this = this; this.input.addEventListener("message", function (message) { if (message.source === _this.output) { f(message); } }); }; /**--------------------------------------------------------------- * class PortStream extends Stream * * A stream wrapping an HTML5 Worker port. This could be the port * used to connect to a Worker or one of the multitude of ports * made available to a SharedWorker for communication back to * its connected clients. */ var PortStream = function PortStream(port) { Stream.call(this); this.port = port; this.id = connect.randomId(); }; PortStream.prototype = Object.create(Stream.prototype); PortStream.prototype.constructor = PortStream; PortStream.prototype.send = function (message) { this.port.postMessage(message); }; PortStream.prototype.onMessage = function (f) { this.port.addEventListener("message", f); }; PortStream.prototype.getId = function () { return this.id; }; /**--------------------------------------------------------------- * class StreamMultiplexer extends Stream * * A wrapper for multiplexed downstream communication with * multiple streams at once. Mainly useful for the SharedWorker to * broadcast events to many PortStream objects at once. */ var StreamMultiplexer = function StreamMultiplexer(streams) { Stream.call(this); this.streamMap = streams ? connect.index(streams, function (s) { return s.getId(); }) : {}; this.messageListeners = []; }; StreamMultiplexer.prototype = Object.create(Stream.prototype); StreamMultiplexer.prototype.constructor = StreamMultiplexer; /** * Send a message to all ports in the multiplexer. */ StreamMultiplexer.prototype.send = function (message) { this.getStreams().forEach(function (stream) { try { stream.send(message); } catch (e) { // Couldn't send message to one of the downstreams for some reason... // No reliable logging possible without further failures, // no recovery, just eat it. } }); }; /** * Register a method which will be called when a message is received from * any of the downstreams. */ StreamMultiplexer.prototype.onMessage = function (f) { this.messageListeners.push(f); // Update existing streams with the new listener. this.getStreams().forEach(function (stream) { stream.onMessage(f); }); }; /** * Add a stream to the multiplexer. */ StreamMultiplexer.prototype.addStream = function (stream) { var self = this; this.streamMap[stream.getId()] = stream; // Update stream with existing listeners. this.messageListeners.forEach(function (messageListener) { stream.onMessage(messageListener); }); }; /** * Remove the given downstream. This is typically used in response * to the SharedWorker's onclose event, indicating that a consumer * tab has been closed. */ StreamMultiplexer.prototype.removeStream = function (stream) { delete this.streamMap[stream.getId()]; }; /** * Get a list of streams in the multiplexer. */ StreamMultiplexer.prototype.getStreams = function (stream) { return connect.values(this.streamMap); }; /** * Get the stream matching the given port. */ StreamMultiplexer.prototype.getStreamForPort = function (port) { return connect.find(this.getStreams(), function (s) { return s.port === port; }); }; /**--------------------------------------------------------------- * class Conduit * * An object which bridges an upstream and a downstream, allowing messages * to be passed to and from each and providing an event bus for event * subscriptions to be made upstream and downstream. */ var Conduit = function Conduit(name, upstream, downstream) { this.name = name; this.upstream = upstream || new NullStream(); this.downstream = downstream || new NullStream(); this.downstreamBus = new connect.EventBus(); this.upstreamBus = new connect.EventBus(); this.upstream.onMessage(connect.hitch(this, this._dispatchEvent, this.upstreamBus)); this.downstream.onMessage(connect.hitch(this, this._dispatchEvent, this.downstreamBus)); // Only relevant for Global Resiliency this.active = true; this.allowedEvents = [].concat(_toConsumableArray(Object.entries(connect.GlobalResiliencyEvents).map(function (keyValue) { return keyValue[1]; })), [connect.EventType.CONFIGURE, connect.EventType.SYNCHRONIZE, connect.EventType.ACKNOWLEDGE, connect.EventType.LOG, connect.EventType.SERVER_BOUND_INTERNAL_LOG, connect.EventType.DOWNLOAD_LOG_FROM_CCP]); }; Conduit.prototype.onUpstream = function (eventName, f) { connect.assertNotNull(eventName, 'eventName'); connect.assertNotNull(f, 'f'); connect.assertTrue(connect.isFunction(f), 'f must be a function'); return this.upstreamBus.subscribe(eventName, f); }; Conduit.prototype.onAllUpstream = function (f) { connect.assertNotNull(f, 'f'); connect.assertTrue(connect.isFunction(f), 'f must be a function'); return this.upstreamBus.subscribeAll(f); }; Conduit.prototype.onDownstream = function (eventName, f) { connect.assertNotNull(eventName, 'eventName'); connect.assertNotNull(f, 'f'); connect.assertTrue(connect.isFunction(f), 'f must be a function'); return this.downstreamBus.subscribe(eventName, f); }; Conduit.prototype.onAllDownstream = function (f) { connect.assertNotNull(f, 'f'); connect.assertTrue(connect.isFunction(f), 'f must be a function'); return this.downstreamBus.subscribeAll(f); }; Conduit.prototype.sendUpstream = function (eventName, data) { connect.assertNotNull(eventName, 'eventName'); this.upstream.send({ event: eventName, data: data }); }; Conduit.prototype.sendDownstream = function (eventName, data) { connect.assertNotNull(eventName, 'eventName'); this.downstream.send({ event: eventName, data: data }); }; Conduit.prototype._dispatchEvent = function (bus, messageEvent) { var message = messageEvent.data; if (message.event) { bus.trigger(message.event, message.data); } }; /** * Returns a closure which passes events upstream. * * Usage: * conduit.onDownstream("MyEvent", conduit.passUpstream()); */ Conduit.prototype.passUpstream = function () { var self = this; return function (data, eventName) { if (!self.active && !self.allowedEvents.includes(eventName)) { connect.getLog().debug("[GR] Conduit ".concat(self.name, " has blocked event ").concat(eventName, " from going upstream.")).sendInternalLogToServer(); return; } self.upstream.send({ event: eventName, data: data }); }; }; /** * Returns a closure which passes events downstream. * * Usage: * conduit.onUpstream("MyEvent", conduit.passDownstream()); */ Conduit.prototype.passDownstream = function () { var self = this; return function (data, eventName) { if (!self.active && !self.allowedEvents.includes(eventName)) { connect.getLog().debug("[GR] Conduit ".concat(self.name, " has blocked event ").concat(eventName, " from going downstream.")).sendInternalLogToServer(); return; } self.downstream.send({ event: eventName, data: data }); }; }; /** * Shutdown the conduit's event busses and remove all subscriptions. */ Conduit.prototype.shutdown = function () { this.upstreamBus.unsubscribeAll(); this.downstreamBus.unsubscribeAll(); }; Conduit.prototype.setActive = function () { connect.getLog().info("[GR] Setting CCP conduit as active"); this.active = true; }; Conduit.prototype.setInactive = function () { connect.getLog().info("[GR] Setting CCP conduit as inactive"); this.active = false; }; /**--------------------------------------------------------------- * class IFrameConduit extends Conduit * * Creates a conduit for the given IFrame element. */ var IFrameConduit = function IFrameConduit(name, window, iframe, domain) { Conduit.call(this, name, new WindowIOStream(window, iframe.contentWindow, domain || '*'), null); }; IFrameConduit.prototype = Object.create(Conduit.prototype); IFrameConduit.prototype.constructor = IFrameConduit; var GRProxyIframeConduit = /*#__PURE__*/function () { function GRProxyIframeConduit(window, iframeConfigs, defaultActiveCCPUrl) { var _this2 = this; _classCallCheck(this, GRProxyIframeConduit); this.iframeLabelMap = {}; var defaultActiveOrigin = new URL(defaultActiveCCPUrl).origin; this.activeRegionUrl = defaultActiveOrigin; this.conduits = iframeConfigs.map(function (config) { var iframe = config.iframe, label = config.label; var iframeConduit = new IFrameConduit(iframe.src, window, iframe); iframeConduit.iframe = iframe; var _URL = new URL(iframe.src), origin = _URL.origin; iframeConduit.name = origin; _this2.iframeLabelMap[origin] = label; return iframeConduit; }); this.setActiveConduit(defaultActiveOrigin); } return _createClass(GRProxyIframeConduit, [{ key: "onUpstream", value: function onUpstream(eventName, f) { var subs = this.conduits.map(function (conduit) { return conduit.onUpstream(eventName, f); }); return { unsubscribe: function unsubscribe() { return subs.forEach(function (sub) { return sub.unsubscribe(); }); } }; } }, { key: "onAllUpstream", value: function onAllUpstream(f) { var subs = this.conduits.map(function (conduit) { return conduit.onAllUpstream(f); }); return { unsubscribe: function unsubscribe() { return subs.forEach(function (sub) { return sub.unsubscribe(); }); } }; } }, { key: "onDownstream", value: function onDownstream(eventName, f) { var subs = this.conduits.map(function (conduit) { return conduit.onDownstream(eventName, f); }); return { unsubscribe: function unsubscribe() { return subs.forEach(function (sub) { return sub.unsubscribe(); }); } }; } }, { key: "onAllDownstream", value: function onAllDownstream(f) { var subs = this.conduits.map(function (conduit) { return conduit.onAllDownstream(f); }); return { unsubscribe: function unsubscribe() { return subs.forEach(function (sub) { return sub.unsubscribe(); }); } }; } }, { key: "sendUpstream", value: function sendUpstream(eventName, data) { this.conduits.forEach(function (conduit) { conduit.sendUpstream(eventName, data); }); } }, { key: "sendDownstream", value: function sendDownstream(eventName, data) { this.conduits.forEach(function (conduit) { conduit.sendDownstream(eventName, data); }); } // Relay an event from one shared worker to another }, { key: "relayUpstream", value: function relayUpstream(eventName) { var self = this; this.conduits.forEach(function (conduit) { conduit.onUpstream(eventName, function (data) { var otherConduit = self.getOtherConduit(conduit); otherConduit.sendUpstream(eventName, data); connect.getLog().info("Relayed event ".concat(eventName, " from ").concat(conduit.name, " to ").concat(otherConduit.name, " shared worker")).withObject({ data: data }).sendInternalLogToServer(); }); }); } }, { key: "getAllConduits", value: function getAllConduits() { return this.conduits; } }, { key: "setActiveConduit", value: function setActiveConduit(activeRegionUrl) { var _this3 = this; var newActiveConduit = this.conduits.find(function (conduit) { return conduit.name === activeRegionUrl; }); if (!newActiveConduit) { connect.getLog().error("[GR] No conduit found with the given ccpUrl: ".concat(activeRegionUrl)).sendInternalLogToServer(); return; } this.conduits.forEach(function (conduit) { if (conduit.name === activeRegionUrl) { _this3.activeRegionUrl = activeRegionUrl; // Update member variables in case customer directly referencing those _this3.name = conduit.name; _this3.upstream = conduit.upstream; _this3.downstream = conduit.downstream; _this3.upstreamBus = conduit.upstreamBus; _this3.downstreamBus = conduit.downstreamBus; } }); connect.getLog().info("[GR] Switched to active conduit ".concat(this.getActiveConduit().name)).sendInternalLogToServer(); } }, { key: "getActiveConduit", value: function getActiveConduit() { var _this4 = this; return this.conduits.find(function (conduit) { return conduit.name === _this4.activeRegionUrl; }); } }, { key: "getInactiveConduit", value: function getInactiveConduit() { var _this5 = this; return this.conduits.find(function (conduit) { return conduit.name !== _this5.activeRegionUrl; }); } }, { key: "getOtherConduit", value: function getOtherConduit(conduit) { return this.conduits.find(function (otherConduit) { return conduit.name !== otherConduit.name; }); } }, { key: "getConduitByRegion", value: function getConduitByRegion(region) { return this.conduits.find(function (conduit) { return conduit.region === region; }); } }, { key: "getConduitByName", value: function getConduitByName(name) { return this.conduits.find(function (conduit) { return conduit.name === name; }); } }]); }(); connect.Stream = Stream; connect.NullStream = NullStream; connect.WindowStream = WindowStream; connect.WindowIOStream = WindowIOStream; connect.PortStream = PortStream; connect.StreamMultiplexer = StreamMultiplexer; connect.Conduit = Conduit; connect.IFrameConduit = IFrameConduit; connect.GRProxyIframeConduit = GRProxyIframeConduit; })(); /***/ }), /***/ 830: /***/ (() => { /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; /**------------------------------------------------------------------------- * GraphLink <> * * Represents the association of one or more attributes to a state transition. */ var GraphLink = function GraphLink(fromState, toState) { connect.assertNotNull(fromState, 'fromState'); connect.assertNotNull(toState, 'toState'); this.fromState = fromState; this.toState = toState; }; GraphLink.prototype.getAssociations = function (context) { throw connect.NotImplementedError(); }; GraphLink.prototype.getFromState = function () { return this.fromState; }; GraphLink.prototype.getToState = function () { return this.toState; }; /**------------------------------------------------------------------------- * DirectGraphLink <> extends GraphLink * * Represents the by-value representation of one or more attributes to a * state transition. */ var DirectGraphLink = function DirectGraphLink(fromState, toState, associations) { connect.assertNotNull(fromState, 'fromState'); connect.assertNotNull(toState, 'toState'); connect.assertNotNull(associations, 'associations'); GraphLink.call(this, fromState, toState); this.associations = associations; }; DirectGraphLink.prototype = Object.create(GraphLink.prototype); DirectGraphLink.prototype.constructor = DirectGraphLink; DirectGraphLink.prototype.getAssociations = function (context) { return this.associations; }; /** * FunctionalGraphLink <> extends GraphLink * * Represents a functional association of one or more attributes to a * state transition. */ var FunctionalGraphLink = function FunctionalGraphLink(fromState, toState, closure) { connect.assertNotNull(fromState, 'fromState'); connect.assertNotNull(toState, 'toState'); connect.assertNotNull(closure, 'closure'); connect.assertTrue(connect.isFunction(closure), 'closure must be a function'); GraphLink.call(this, fromState, toState); this.closure = closure; }; FunctionalGraphLink.prototype = Object.create(GraphLink.prototype); FunctionalGraphLink.prototype.constructor = FunctionalGraphLink; FunctionalGraphLink.prototype.getAssociations = function (context) { return this.closure(context, this.getFromState(), this.getToState()); }; /**------------------------------------------------------------------------- * EventGraph <> * * Builds a map of associations from one state to another in context of a * particular object. The associations can be direct (one or more values) * or functional (a method returning one or more values), and are used to * provide additional contextual event hooks for the UI to consume. */ var EventGraph = function EventGraph() { this.fromMap = {}; }; EventGraph.ANY = "<>"; EventGraph.prototype.assoc = function (fromStateObj, toStateObj, assocObj) { var self = this; if (!fromStateObj) { throw new Error("fromStateObj is not defined."); } if (!toStateObj) { throw new Error("toStateObj is not defined."); } if (!assocObj) { throw new Error("assocObj is not defined."); } if (fromStateObj instanceof Array) { fromStateObj.forEach(function (fromState) { self.assoc(fromState, toStateObj, assocObj); }); } else if (toStateObj instanceof Array) { toStateObj.forEach(function (toState) { self.assoc(fromStateObj, toState, assocObj); }); } else { if (typeof assocObj === "function") { this._addAssociation(new FunctionalGraphLink(fromStateObj, toStateObj, assocObj)); } else if (assocObj instanceof Array) { this._addAssociation(new DirectGraphLink(fromStateObj, toStateObj, assocObj)); } else { this._addAssociation(new DirectGraphLink(fromStateObj, toStateObj, [assocObj])); } } return this; }; EventGraph.prototype.getAssociations = function (context, fromState, toState) { connect.assertNotNull(fromState, 'fromState'); connect.assertNotNull(toState, 'toState'); var associations = []; var toMapFromAny = this.fromMap[EventGraph.ANY] || {}; var toMap = this.fromMap[fromState] || {}; associations = associations.concat(this._getAssociationsFromMap(toMapFromAny, context, fromState, toState)); associations = associations.concat(this._getAssociationsFromMap(toMap, context, fromState, toState)); return associations; }; EventGraph.prototype._addAssociation = function (assoc) { var toMap = this.fromMap[assoc.getFromState()]; if (!toMap) { toMap = this.fromMap[assoc.getFromState()] = {}; } var assocList = toMap[assoc.getToState()]; if (!assocList) { assocList = toMap[assoc.getToState()] = []; } assocList.push(assoc); }; EventGraph.prototype._getAssociationsFromMap = function (map, context, fromState, toState) { var assocList = (map[EventGraph.ANY] || []).concat(map[toState] || []); return assocList.reduce(function (prev, assoc) { return prev.concat(assoc.getAssociations(context)); }, []); }; connect.EventGraph = EventGraph; })(); /***/ }), /***/ 60: /***/ (() => { function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; var userAgent = navigator.userAgent; var ONE_DAY_MILLIS = 24 * 60 * 60 * 1000; var DEFAULT_POPUP_HEIGHT = 578; var DEFAULT_POPUP_WIDTH = 433; var COPYABLE_EVENT_FIELDS = ["bubbles", "cancelBubble", "cancelable", "composed", "data", "defaultPrevented", "eventPhase", "isTrusted", "lastEventId", "origin", "returnValue", "timeStamp", "type"]; /** * Unpollute sprintf functions from the global namespace. */ connect.sprintf = global.sprintf; connect.vsprintf = global.vsprintf; delete global.sprintf; delete global.vsprintf; connect.HTTP_STATUS_CODES = { SUCCESS: 200, UNAUTHORIZED: 401, ACCESS_DENIED: 403, TOO_MANY_REQUESTS: 429, INTERNAL_SERVER_ERROR: 500 }; connect.TRANSPORT_TYPES = { CHAT_TOKEN: "chat_token", WEB_SOCKET: "web_socket", AGENT_DISCOVERY: "agent_discovery", WEB_RTC: "web_rtc" }; /** * Binds the given instance object as the context for * the method provided. * * @param scope The instance object to be set as the scope * of the function. * @param method The method to be encapsulated. * * All other arguments, if any, are bound to the method * invocation inside the closure. * * @return A closure encapsulating the invocation of the * method provided in context of the given instance. */ connect.hitch = function () { var args = Array.prototype.slice.call(arguments); var scope = args.shift(); var method = args.shift(); connect.assertNotNull(scope, 'scope'); connect.assertNotNull(method, 'method'); connect.assertTrue(connect.isFunction(method), 'method must be a function'); return function () { var closureArgs = Array.prototype.slice.call(arguments); return method.apply(scope, args.concat(closureArgs)); }; }; /** * Determine if the given value is a callable function type. * Borrowed from Underscore.js. */ connect.isFunction = function (obj) { return !!(obj && obj.constructor && obj.call && obj.apply); }; /** * Determine if the given value is an array. */ connect.isArray = function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; /** * Get a list of keys from a Javascript object used * as a hash map. */ connect.keys = function (map) { var keys = []; connect.assertNotNull(map, 'map'); for (var k in map) { keys.push(k); } return keys; }; /** * Get a list of values from a Javascript object used * as a hash map. */ connect.values = function (map) { var values = []; connect.assertNotNull(map, 'map'); for (var k in map) { values.push(map[k]); } return values; }; /** * Get a list of key/value pairs from the given map. */ connect.entries = function (map) { var entries = []; for (var k in map) { entries.push({ key: k, value: map[k] }); } return entries; }; /** * Merge two or more maps together into a new map, * or simply copy a single map. */ connect.merge = function () { var argMaps = Array.prototype.slice.call(arguments, 0); var resultMap = {}; argMaps.forEach(function (map) { connect.entries(map).forEach(function (kv) { resultMap[kv.key] = kv.value; }); }); return resultMap; }; connect.now = function () { return new Date().getTime(); }; connect.find = function (array, predicate) { for (var x = 0; x < array.length; x++) { if (predicate(array[x])) { return array[x]; } } return null; }; connect.contains = function (obj, value) { if (obj instanceof Array) { return connect.find(obj, function (v) { return v === value; }) != null; } else { return value in obj; } }; connect.containsValue = function (obj, value) { if (obj instanceof Array) { return connect.find(obj, function (v) { return v === value; }) != null; } else { return connect.find(connect.values(obj), function (v) { return v === value; }) != null; } }; /** * Generate a random ID consisting of the current timestamp * and a random base-36 number based on Math.random(). */ connect.randomId = function () { return connect.sprintf("%s-%s", connect.now(), Math.random().toString(36).slice(2)); }; /** * Generate an enum from the given list of lower-case enum values, * where the enum keys will be upper case. * * Conversion from pascal case based on code from here: * http://stackoverflow.com/questions/30521224 */ connect.makeEnum = function (values) { var enumObj = {}; values.forEach(function (value) { var key = value.replace(/\.?([a-z]+)_?/g, function (x, y) { return y.toUpperCase() + "_"; }).replace(/_$/, ""); enumObj[key] = value; }); return enumObj; }; connect.makeNamespacedEnum = function (prefix, values) { var enumObj = connect.makeEnum(values); connect.keys(enumObj).forEach(function (key) { enumObj[key] = connect.sprintf("%s::%s", prefix, enumObj[key]); }); return enumObj; }; connect.makeGenericNamespacedEnum = function (prefix, values, delimiter) { var enumObj = connect.makeEnum(values); connect.keys(enumObj).forEach(function (key) { enumObj[key] = connect.sprintf("%s" + delimiter + "%s", prefix, enumObj[key]); }); return enumObj; }; /** * Methods to determine browser type and versions, used for softphone initialization. */ /* This will also return True for Edge and Opera since they include Chrome in the user agent string, as they are built off of Chrome. */ connect.isChromeBrowser = function () { return userAgent.indexOf("Chrome") !== -1; }; connect.isFirefoxBrowser = function () { return userAgent.indexOf("Firefox") !== -1; }; connect.isOperaBrowser = function () { return userAgent.indexOf("Opera") !== -1; }; connect.isEdgeBrowser = function () { return userAgent.indexOf("Edg") !== -1; }; connect.getChromeBrowserVersion = function () { var chromeVersion = userAgent.substring(userAgent.indexOf("Chrome") + 7); if (chromeVersion) { return parseFloat(chromeVersion); } else { return -1; } }; connect.getFirefoxBrowserVersion = function () { var firefoxVersion = userAgent.substring(userAgent.indexOf("Firefox") + 8); if (firefoxVersion) { return parseFloat(firefoxVersion); } else { return -1; } }; connect.isValidLocale = function (locale) { var languages = [{ id: 'en_US', label: 'English' }, { id: 'de_DE', label: 'Deutsch' }, { id: 'es_ES', label: 'Español' }, { id: 'fr_FR', label: 'Français' }, { id: 'ja_JP', label: '日本語' }, { id: 'it_IT', label: 'Italiano' }, { id: 'ko_KR', label: '한국어' }, { id: 'pt_BR', label: 'Português' }, { id: 'zh_CN', label: '中文(简体)' }, { id: 'zh_TW', label: '中文(繁體)' }]; return languages.map(function (language) { return language.id; }).includes(locale); }; connect.getOperaBrowserVersion = function () { var versionOffset = userAgent.indexOf("Opera"); var operaVersion = userAgent.indexOf("Version") !== -1 ? userAgent.substring(versionOffset + 8) : userAgent.substring(versionOffset + 6); if (operaVersion) { return parseFloat(operaVersion); } else { return -1; } }; /** * Return a map of items in the given list indexed by * keys determined by the closure provided. * * @param iterable A list-like object. * @param closure A closure to determine the index for the * items in the iterable. * @return A map from index to item for each item in the iterable. */ connect.index = function (iterable, closure) { var map = {}; iterable.forEach(function (item) { map[closure(item)] = item; }); return map; }; /** * Converts the given array into a map as a set, * where elements in the array are mapped to 1. */ connect.set = function (arrayIn) { var setMap = {}; arrayIn.forEach(function (key) { setMap[key] = 1; }); return setMap; }; /** * Returns a map for each key in mapB which * is NOT in mapA. */ connect.relativeComplement = function (mapA, mapB) { var compMap = {}; connect.keys(mapB).forEach(function (key) { if (!(key in mapA)) { compMap[key] = mapB[key]; } }); return compMap; }; /** * Asserts that a premise is true. */ connect.assertTrue = function (premise, message) { if (!premise) { throw new connect.ValueError(message); } }; /** * Asserts that a value is not null or undefined. */ connect.assertNotNull = function (value, name) { connect.assertTrue(value != null && _typeof(value) !== undefined, connect.sprintf("%s must be provided", name || 'A value')); return value; }; connect.deepcopy = function (src) { return JSON.parse(JSON.stringify(src)); }; connect.deepcopyCrossOriginEvent = function (event) { var obj = {}; var listOfAcceptableKeys = COPYABLE_EVENT_FIELDS; listOfAcceptableKeys.forEach(function (key) { try { obj[key] = event[key]; } catch (e) { connect.getLog().info("deepcopyCrossOriginEvent failed on key: ", key).sendInternalLogToServer(); } }); return connect.deepcopy(obj); }; /** * Get the current base url of the open page, e.g. if the page is * https://example.com:9494/oranges, this will be "https://example.com:9494". */ connect.getBaseUrl = function () { var location = global.location; return connect.sprintf("%s//%s:%s", location.protocol, location.hostname, location.port); }; connect.getUrlWithProtocol = function (url) { var protocol = global.location.protocol; if (url.substr(0, protocol.length) !== protocol) { return connect.sprintf("%s//%s", protocol, url); } return url; }; /** * Determine if the current window is in an iframe. * Courtesy: http://stackoverflow.com/questions/326069/ */ connect.isFramed = function () { try { return window.self !== window.top; } catch (e) { return true; } }; connect.hasOtherConnectedCCPs = function () { return connect.numberOfConnectedCCPs > 1; }; connect.fetch = function (endpoint, options, milliInterval, maxRetry) { maxRetry = maxRetry || 5; milliInterval = milliInterval || 1000; options = options || {}; return new Promise(function (resolve, reject) { function fetchData(maxRetry) { fetch(endpoint, options).then(function (res) { if (res.status === connect.HTTP_STATUS_CODES.SUCCESS) { res.json().then(function (json) { return resolve(json); })["catch"](function () { return resolve({}); }); } else if (maxRetry !== 1 && (res.status >= connect.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR || res.status === connect.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)) { setTimeout(function () { fetchData(--maxRetry); }, milliInterval); } else { reject(res); } })["catch"](function (e) { reject(e); }); } fetchData(maxRetry); }); }; connect.fetchWithTimeout = /*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(endpoint, timeoutMs, options, milliInterval, maxRetry) { var controller, id, response; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: options = options || {}; if (timeoutMs) { _context.next = 3; break; } return _context.abrupt("return", connect.fetch(endpoint, options, milliInterval, maxRetry)); case 3: controller = new AbortController(); id = setTimeout(function () { return controller.abort(); }, timeoutMs); _context.next = 7; return connect.fetch(endpoint, _objectSpread(_objectSpread({}, options), {}, { signal: controller.signal }), milliInterval, maxRetry); case 7: response = _context.sent; clearTimeout(id); return _context.abrupt("return", response); case 10: case "end": return _context.stop(); } }, _callee); })); return function (_x, _x2, _x3, _x4, _x5) { return _ref.apply(this, arguments); }; }(); /** * Calling a function with exponential backoff with full jitter retry strategy * It will retry calling the function for maximum maxRetry times if it fails. * Success callback will be called if the function succeeded. * Failure callback will be called only if the last try failed. */ connect.backoff = function (func, milliInterval, maxRetry, callbacks) { connect.assertTrue(connect.isFunction(func), "func must be a Function"); var self = this; var ratio = 2; func({ success: function success(data) { if (callbacks && callbacks.success) { callbacks.success(data); } }, failure: function failure(err, data) { if (maxRetry > 0) { var interval = milliInterval * 2 * Math.random(); global.setTimeout(function () { self.backoff(func, interval * ratio, --maxRetry, callbacks); }, interval); } else { if (callbacks && callbacks.failure) { callbacks.failure(err, data); } } } }); }; connect.publishMetric = function (metricData) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.CLIENT_METRIC, data: metricData }); }; connect.publishSoftphoneStats = function (stats) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.SOFTPHONE_STATS, data: stats }); }; connect.publishSoftphoneReport = function (report) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.SOFTPHONE_REPORT, data: report }); }; connect.publishClickStreamData = function (report) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.CLICK_STREAM_DATA, data: report }); }; connect.publishClientSideLogs = function (logs) { var bus = connect.core.getEventBus(); bus.trigger(connect.EventType.CLIENT_SIDE_LOGS, logs); }; connect.addNamespaceToLogs = function (namespace) { var methods = ['log', 'error', 'warn', 'info', 'debug']; methods.forEach(function (method) { var consoleMethod = window.console[method]; window.console[method] = function () { var args = Array.from(arguments); args.unshift("[".concat(namespace, "]")); consoleMethod.apply(window.console, args); }; }); }; /** * A wrapper around Window.open() for managing single instance popups. */ connect.PopupManager = function () {}; connect.PopupManager.prototype.open = function (url, name, options) { var win = null; if (options) { // default values are chosen to provide a minimum height without scrolling // and a uniform margin based on the css of the ccp login page var height = options.height || DEFAULT_POPUP_HEIGHT; var width = options.width || DEFAULT_POPUP_WIDTH; var top = options.top || 0; var left = options.left || 0; win = window.open('', name, "width=" + width + ", height=" + height + ", top=" + top + ", left=" + left); if (win.location !== url) { win = window.open(url, name, "width=" + width + ", height=" + height + ", top=" + top + ", left=" + left); } } else { win = window.open('', name); if (win.location !== url) { win = window.open(url, name); } } return win; }; connect.PopupManager.prototype.clear = function (name) { var key = this._getLocalStorageKey(name); global.localStorage.removeItem(key); }; connect.PopupManager.prototype._getLastOpenedTimestamp = function (name) { var key = this._getLocalStorageKey(name); var value = global.localStorage.getItem(key); if (value) { return parseInt(value, 10); } else { return 0; } }; connect.PopupManager.prototype._setLastOpenedTimestamp = function (name, ts) { var key = this._getLocalStorageKey(name); global.localStorage.setItem(key, '' + ts); }; connect.PopupManager.prototype._getLocalStorageKey = function (name) { return "connectPopupManager::" + name; }; /** * An enumeration of the HTML5 notification permission values. */ var NotificationPermission = connect.makeEnum(['granted', 'denied', 'default']); /** * A simple engine for showing notification popups. */ connect.NotificationManager = function () { this.queue = []; this.permission = NotificationPermission.DEFAULT; }; connect.NotificationManager.prototype.requestPermission = function () { var self = this; if (!("Notification" in global)) { connect.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(); this.permission = NotificationPermission.DENIED; } else if (global.Notification.permission === NotificationPermission.DENIED) { connect.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(); this.permission = NotificationPermission.DENIED; } else if (this.permission !== NotificationPermission.GRANTED) { global.Notification.requestPermission().then(function (permission) { self.permission = permission; if (permission === NotificationPermission.GRANTED) { self._showQueued(); } else { self.queue = []; } }); } }; connect.NotificationManager.prototype.show = function (title, options) { if (this.permission === NotificationPermission.GRANTED) { return this._showImpl({ title: title, options: options }); } else if (this.permission === NotificationPermission.DENIED) { connect.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({ title: title, options: options }); } else { var params = { title: title, options: options }; connect.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(params).sendInternalLogToServer(); this.queue.push(params); } }; connect.NotificationManager.prototype._showQueued = function () { var self = this; var notifications = this.queue.map(function (params) { return self._showImpl(params); }); this.queue = []; return notifications; }; connect.NotificationManager.prototype._showImpl = function (params) { var notification = new global.Notification(params.title, params.options); if (params.options.clicked) { notification.onclick = function () { params.options.clicked.call(notification); }; } return notification; }; connect.ValueError = function () { var args = Array.prototype.slice.call(arguments, 0); var format = args.shift(); var instance = new Error(connect.vsprintf(format, args)); Object.setPrototypeOf(instance, connect.ValueError.prototype); return instance; }; Object.setPrototypeOf(connect.ValueError.prototype, Error.prototype); Object.setPrototypeOf(connect.ValueError, Error); connect.ValueError.prototype.name = 'ValueError'; connect.NotImplementedError = function () { var args = Array.prototype.slice.call(arguments, 0); var format = args.shift(); var instance = new Error(connect.vsprintf(format, args)); Object.setPrototypeOf(instance, connect.NotImplementedError.prototype); return instance; }; Object.setPrototypeOf(connect.NotImplementedError.prototype, Error.prototype); Object.setPrototypeOf(connect.NotImplementedError, Error); connect.NotImplementedError.prototype.name = 'NotImplementedError'; connect.StateError = function () { var args = Array.prototype.slice.call(arguments, 0); var format = args.shift(); var instance = new Error(connect.vsprintf(format, args)); Object.setPrototypeOf(instance, connect.StateError.prototype); return instance; }; Object.setPrototypeOf(connect.StateError.prototype, Error.prototype); Object.setPrototypeOf(connect.StateError, Error); connect.StateError.prototype.name = 'StateError'; connect.VoiceIdError = function (type, message, err) { var error = {}; error.type = type; error.message = message; error.stack = Error(message).stack; error.err = err; return error; }; // internal use only connect.isCCP = function () { if (!connect.core.upstream) { return false; } var conduit = connect.core.getUpstream(); return conduit.name === 'ConnectSharedWorkerConduit'; }; connect.isSharedWorker = function () { return connect.worker && !!connect.worker.clientEngine; }; connect.isCRM = function () { if (!connect.core.upstream) { return false; } return connect.core.getUpstream() instanceof connect.IFrameConduit || connect.core.getUpstream() instanceof connect.GRProxyIframeConduit; }; // internal use only connect.isActiveConduit = function (conduit) { var grProxyConduit = connect.core.getUpstream(); if (grProxyConduit instanceof connect.GRProxyIframeConduit) { return conduit.name === grProxyConduit.activeRegionUrl; } else { connect.getLog().debug('connect.isActiveConduit is called but there is no GR proxy conduit').sendInternalLogToServer(); return true; } }; })(); /***/ }), /***/ 354: /***/ (() => { function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } /* * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ (function () { var global = this || globalThis; var connect = global.connect || {}; global.connect = connect; global.lily = connect; connect.worker = {}; var GET_AGENT_TIMEOUT_MS = 30000; var GET_AGENT_RECOVERY_TIMEOUT_MS = 5000; var GET_AGENT_SUCCESS_TIMEOUT_MS = 100; var LOG_BUFFER_CAP_SIZE = 400; var CHECK_ACTIVE_REGION_INTERVAL_MS = 60000; var CHECK_AUTH_TOKEN_INTERVAL_MS = 300000; // 5 minutes var REFRESH_AUTH_TOKEN_INTERVAL_MS = 10000; // 10 seconds var REFRESH_AUTH_TOKEN_MAX_TRY = 4; var GET_AGENT_CONFIGURATION_INTERVAL_MS = 30000; var GET_AGENT_CONFIGURATION_TIMEOUT_MS = 10000; var POLL_FOR_ACTIVE_REGION_METHOD = "LADS.GetAgentFailoverConfiguration"; var relatedContactIdMethods = { createTaskContact: "createTaskContact", createOutboundContact: "createOutboundContact", createTemplatedTask: "createTemplatedTask" }; /**-----------------------------------------------------------------------*/ var MasterTopicCoordinator = function MasterTopicCoordinator() { this.topicMasterMap = {}; }; MasterTopicCoordinator.prototype.getMaster = function (topic) { connect.assertNotNull(topic, 'topic'); return this.topicMasterMap[topic] || null; }; MasterTopicCoordinator.prototype.setMaster = function (topic, id) { connect.assertNotNull(topic, 'topic'); connect.assertNotNull(id, 'id'); this.topicMasterMap[topic] = id; }; MasterTopicCoordinator.prototype.removeMaster = function (id) { connect.assertNotNull(id, 'id'); var self = this; connect.entries(this.topicMasterMap).filter(function (entry) { return entry.value === id; }).forEach(function (entry) { delete self.topicMasterMap[entry.key]; }); }; /**--------------------------------------------------------------- * class WorkerClient extends ClientBase */ var WorkerClient = function WorkerClient(conduit) { connect.ClientBase.call(this); this.conduit = conduit; }; WorkerClient.prototype = Object.create(connect.ClientBase.prototype); WorkerClient.prototype.constructor = WorkerClient; WorkerClient.prototype._callImpl = function (method, params, callbacks) { var self = this; var request_start = new Date().getTime(); if (connect.containsValue(connect.AgentAppClientMethods, method)) { connect.core.getAgentAppClient()._callImpl(method, params, { success: function success(data) { self._recordAPILatency(method, request_start, params); callbacks.success(data); }, failure: function failure(error) { self._recordAPILatency(method, request_start, params, error); callbacks.failure(error); } }); } else if (connect.containsValue(connect.TaskTemplatesClientMethods, method)) { connect.core.getTaskTemplatesClient()._callImpl(method, params, { success: function success(data) { self._recordAPILatency(method, request_start, params); callbacks.success(data); }, failure: function failure(error) { self._recordAPILatency(method, request_start, params, error); callbacks.failure(error); } }); } else { connect.core.getClient()._callImpl(method, params, { success: function success(data, dataAttribute) { self._recordAPILatency(method, request_start, params); callbacks.success(data, dataAttribute); }, failure: function failure(error, data) { self._recordAPILatency(method, request_start, params, error); callbacks.failure(error, data); }, authFailure: function authFailure(error, data) { self._recordAPILatency(method, request_start, params, error); callbacks.authFailure(); }, accessDenied: function accessDenied(error, data) { self._recordAPILatency(method, request_start, params, error); callbacks.accessDenied && callbacks.accessDenied(); } }); } }; WorkerClient.prototype._recordAPILatency = function (method, request_start, params, err) { var request_end = new Date().getTime(); var request_time = request_end - request_start; this._sendAPIMetrics(method, request_time, params, err); }; WorkerClient.prototype._sendAPIMetrics = function (method, time, params, err) { var eventData = { name: method, time: time, error: err, error5xx: 0 }; var dimensions = [{ name: 'Category', value: 'API' }]; var statusCode = err && err.statusCode || 200; var retryStatus = err && err.retryStatus || connect.RetryStatus.NONE; var optionalDimensions = [{ name: 'HttpStatusCode', value: statusCode }, { name: 'HttpGenericStatusCode', value: "".concat(statusCode.toString().charAt(0), "XX") }, { name: 'RetryStatus', value: retryStatus }]; if (statusCode.toString().charAt(0) === '5') { eventData.error5xx = 1; } // API fault metric - ignores 4xx if (statusCode.toString().charAt(0) === '5') { eventData.fault = 1; } else if (statusCode.toString().charAt(0) === '2') { eventData.fault = 0; } // Subset Metrics for distinguishing when we use relatedContactId if (relatedContactIdMethods[method] && params && params.relatedContactId) { var relatedEventData = { name: "".concat(method, "WithRelatedContactId"), time: eventData.time, error: eventData.error, error5xx: eventData.error5xx }; this.conduit.sendDownstream(connect.EventType.API_METRIC, _objectSpread(_objectSpread({}, relatedEventData), {}, { dimensions: dimensions, optionalDimensions: optionalDimensions })); } this.conduit.sendDownstream(connect.EventType.API_METRIC, _objectSpread(_objectSpread({}, eventData), {}, { dimensions: dimensions, optionalDimensions: optionalDimensions })); }; /**------------------------------------------------------------------------- * The object responsible for polling and passing data downstream to all * consumer ports. */ var ClientEngine = function ClientEngine() { var self = this; this.multiplexer = new connect.StreamMultiplexer(); this.conduit = new connect.Conduit("AmazonConnectSharedWorker", null, this.multiplexer); this.client = new WorkerClient(this.conduit); this.timeout = null; this.agent = null; this.nextToken = null; this.initData = {}; this.portConduitMap = {}; this.streamMapByTabId = {}; this.masterCoord = new MasterTopicCoordinator(); this.logsBuffer = []; this.suppress = false; this.forceOffline = false; this.longPollingOptions = { allowLongPollingShadowMode: false, allowLongPollingWebsocketOnlyMode: false }; this.drPollingUrl = null; this.thisArn = null; this.otherArn = null; this.pendingFailover = null; var webSocketManager = null; connect.rootLogger = new connect.DownstreamConduitLogger(this.conduit); this.conduit.onDownstream(connect.EventType.SEND_LOGS, function (logsToUpload) { // Add softphone logs downstream connect.getLog().pushLogsDownstream(logsToUpload); self.logsBuffer = self.logsBuffer.concat(logsToUpload); //only call API to send logs if buffer reached cap if (self.logsBuffer.length > LOG_BUFFER_CAP_SIZE) { self.handleSendLogsRequest(self.logsBuffer); } }); this.conduit.onDownstream(connect.DisasterRecoveryEvents.SUPPRESS, function (data) { connect.getLog().debug("[Disaster Recovery] Setting Suppress to %s", data.suppress).sendInternalLogToServer(); self.suppress = data.suppress || false; if (!self.suppress) { self.forceOffline = false; // if we are unsuppressing this region, clear retry flag for forceOffline } //shouldSendFailoverDownstream is undefined iff suppressContacts was called from the old DR artifact, //but it is false for the suppressContacts calls made when CCP initializes DR without DR polling enabled, //and for all suppressContacts calls made from the new DR artifact. var shouldSendFailoverDownstream = typeof data.shouldSendFailoverDownstream === 'undefined' || data.shouldSendFailoverDownstream; //signal other windows that a failover happened, if following the old behavior pattern if (shouldSendFailoverDownstream) { self.conduit.sendDownstream(connect.DisasterRecoveryEvents.FAILOVER, { isPrimary: !self.suppress }); } }); this.conduit.onDownstream(connect.DisasterRecoveryEvents.FORCE_OFFLINE, function (data) { connect.getLog().debug("[Disaster Recovery] Setting FORCE_OFFLINE to %s", data.offline).sendInternalLogToServer(); //signal other windows that a failover happened, unless this force offline is being retried from a previous failure if (!self.forceOffline) { self.pendingFailover = false; self.conduit.sendDownstream(connect.DisasterRecoveryEvents.FAILOVER, { isPrimary: false, nextActiveArn: data.nextActiveArn }); } self.forceOffline = data.offline || false; }); connect.DisasterRecoveryEvents.INIT_DR_POLLING && this.conduit.onDownstream(connect.DisasterRecoveryEvents.INIT_DR_POLLING, function (data) { var log = connect.getLog(); if (self.drPollingUrl) { log.debug("[Disaster Recovery] Adding new CCP to active region polling for instance ".concat(data.instanceArn)).sendInternalLogToServer(); self.pollForActiveRegion(true, false); } else { log.info("[Disaster Recovery] Initializing active region polling for instance ".concat(data.instanceArn)).sendInternalLogToServer(); self.thisArn = data.instanceArn; self.otherArn = data.otherArn; self.getPresignedDiscoveryUrl().then(function (presignedUrl) { self.drPollingUrl = presignedUrl; self.pollForActiveRegion(true, true); }, function (err) { // Each worker is responsible for suppressing itself when needed. If this worker couldn't get a presigned URL, // it won't be able to detect whether it needs to be suppressed, but it may still be able to receive contacts. // If this should actually be the primary region after all, the other worker will trigger a force offline that will unsuppress this worker. log.error("[Disaster Recovery] Failed to get presigned URL for instance ".concat(data.instanceArn, "; suppressing contacts")).withException(err).sendInternalLogToServer(); self.suppress = true; }); } }); this.conduit.onDownstream(connect.EventType.CONFIGURE, function (data) { console.log('@@@ configure event handler', data); try { if (data.authToken && data.authToken !== self.initData.authToken) { self.initData = data; connect.core.init(data); if (data.longPollingOptions) { if (typeof data.longPollingOptions.allowLongPollingShadowMode == "boolean") { self.longPollingOptions.allowLongPollingShadowMode = data.longPollingOptions.allowLongPollingShadowMode; } if (typeof data.longPollingOptions.allowLongPollingWebsocketOnlyMode == "boolean") { self.longPollingOptions.allowLongPollingWebsocketOnlyMode = data.longPollingOptions.allowLongPollingWebsocketOnlyMode; } } // init only once. if (!webSocketManager) { connect.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(); connect.WebSocketManager.setGlobalConfig({ loggerConfig: { logger: connect.getLog(), advancedLogWriter: 'info', level: 10 } }); webSocketManager = connect.WebSocketManager.create(); webSocketManager.onInitFailure(function () { self.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE); }); webSocketManager.onConnectionOpen(function (response) { self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_OPEN, response); }); webSocketManager.onConnectionClose(function (response) { self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_CLOSE, response); }); webSocketManager.onConnectionGain(function () { self.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED); self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_GAIN); }); webSocketManager.onConnectionLost(function (response) { self.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, response); self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_LOST, response); }); webSocketManager.onSubscriptionUpdate(function (response) { self.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, response); }); webSocketManager.onSubscriptionFailure(function (response) { self.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, response); }); webSocketManager.onAllMessage(function (response) { self.conduit.sendDownstream(connect.WebSocketEvents.ALL_MESSAGE, response); }); self.conduit.onDownstream(connect.WebSocketEvents.SEND, function (message) { webSocketManager.sendMessage(message); }); self.conduit.onDownstream(connect.WebSocketEvents.SUBSCRIBE, function (topics) { webSocketManager.subscribeTopics(topics); }); webSocketManager.init(connect.hitch(self, self.getWebSocketUrl)).then(function (response) { try { if (response && !response.webSocketConnectionFailed) { // Start polling for agent data. connect.getLog().info("Kicking off agent polling").sendInternalLogToServer(); self.pollForAgent(); connect.getLog().info("Kicking off config polling").sendInternalLogToServer(); self.pollForAgentConfiguration({ repeatForever: true }); connect.getLog().info("Kicking off auth token polling").sendInternalLogToServer(); global.setInterval(connect.hitch(self, self.checkAuthToken), CHECK_AUTH_TOKEN_INTERVAL_MS); } else { if (!connect.webSocketInitFailed) { var event = connect.WebSocketEvents.INIT_FAILURE; self.conduit.sendDownstream(event); connect.webSocketInitFailed = true; throw new Error(event); } } } catch (e) { connect.getLog().error("WebSocket failed to initialize").withException(e).sendInternalLogToServer(); } }); } else { connect.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer(); } } } catch (e) { console.error('@@@ error', e); } }); this.conduit.onDownstream(connect.EventType.TERMINATE, function () { //upload pending logs before terminating. self.handleSendLogsRequest(self.logsBuffer); connect.core.terminate(); self.conduit.sendDownstream(connect.EventType.TERMINATED); }); this.conduit.onDownstream(connect.EventType.SYNCHRONIZE, function () { self.conduit.sendDownstream(connect.EventType.ACKNOWLEDGE); }); this.conduit.onDownstream(connect.EventType.BROADCAST, function (data) { self.conduit.sendDownstream(data.event, data.data); }); /** * Called when a consumer port connects to this SharedWorker. * Let's add them to our multiplexer. */ global.onconnect = function (event) { var port = event.ports[0]; var stream = new connect.PortStream(port); self.multiplexer.addStream(stream); port.start(); var portConduit = new connect.Conduit(stream.getId(), null, stream); portConduit.sendDownstream(connect.EventType.ACKNOWLEDGE, { id: stream.getId() }); self.portConduitMap[stream.getId()] = portConduit; self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { length: Object.keys(self.portConduitMap).length }); if (self.agent !== null) { self.updateAgent(); } portConduit.onDownstream(connect.EventType.API_REQUEST, connect.hitch(self, self.handleAPIRequest, portConduit)); portConduit.onDownstream(connect.EventType.MASTER_REQUEST, connect.hitch(self, self.handleMasterRequest, portConduit, stream.getId())); portConduit.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION, connect.hitch(self, self.pollForAgentConfiguration)); portConduit.onDownstream(connect.EventType.TAB_ID, connect.hitch(self, self.handleTabIdEvent, stream)); portConduit.onDownstream(connect.EventType.CLOSE, connect.hitch(self, self.handleCloseEvent, stream)); }; }; /** * Use the presigned URL previously retrieved for this ClientEngine to poll for the instance that should be active * and what failover method should be used (soft or hard). We need to poll in one of three cases: * 1) We are initializing CCPs for a DR setup where the shared workers were not already running * (i.e. no CCPs already open) * 2) We are initializing additional CCPs for a DR setup where the shared workers were already running * (i.e. this is an additional window for this DR setup) * 3) We have already polled successfully in this shared worker, and are continuing with the ongoing * polling cycle on a regular interval. (steady-state polling) * * Polling in cases 1 and 2 is done to ensure the newly-opened DR window is showing the correct region. * * Typically, failover of the UI (to display the CCP for the newly-active region) will be triggered by * the region that is being set to inactive, after it has been forced offline. * The exception is in cases 1 and 2, where both regions' workers will send a UI failover signal. * If the region assumed to be the initial primary is degraded at bootstrap time (so it can't request a URL to use for polling), * but the other region is not, and its polling response says it should be made primary, we need that other * instance's worker to be able to tell the UI to fail over to it. (The UI in each DR window will ignore * signals to fail over to the instance already being shown in that window.) * * The URL used for polling will be global, but the endpoint used to get the URL is regional, so once bootstrapping is complete, * the active region should be able to detect that it needs to be failed out even if its AWS region is degraded. */ ClientEngine.prototype.pollForActiveRegion = function (isFirstPollForCCP, isFirstPollForWorker) { var self = this; var log = connect.getLog(); if (!self.drPollingUrl) { throw new connect.StateError("[Disaster Recovery] Tried to poll for active region without first initializing DR polling in the worker."); } log.debug("[Disaster Recovery] Polling for failover with presigned URL for instance ".concat(self.thisArn)).sendInternalLogToServer(); var request_start = new Date().getTime(); return connect.fetchWithTimeout(self.drPollingUrl, GET_AGENT_CONFIGURATION_TIMEOUT_MS)["catch"](function (response) { if (response.status) { self.client._recordAPILatency(POLL_FOR_ACTIVE_REGION_METHOD, request_start, { statusCode: response.status }); if ([connect.HTTP_STATUS_CODES.ACCESS_DENIED, connect.HTTP_STATUS_CODES.UNAUTHORIZED].includes(response.status)) { log.info("[Disaster Recovery] Active region polling failed; trying to get a new URL for polling.").withObject(response).sendInternalLogToServer(); return self.getPresignedDiscoveryUrl().then(function (presignedUrl) { self.drPollingUrl = presignedUrl; }).then(function () { request_start = new Date().getTime(); // reset request start marker if we had to get a new polling URL return connect.fetchWithTimeout(self.drPollingUrl, GET_AGENT_CONFIGURATION_TIMEOUT_MS); }); } else { var errMsg = "[Disaster Recovery] Failed to poll for failover for instance ".concat(self.thisArn, ", ") + "received unexpected response code ".concat(response.status); log.error(errMsg).withObject(response).sendInternalLogToServer(); throw new Error(errMsg); } } else { var errMsg = "[Disaster Recovery] Failed to poll for failover for instance ".concat(self.thisArn, ", request timed out or aborted"); self.client._recordAPILatency(POLL_FOR_ACTIVE_REGION_METHOD, request_start, { statusCode: -1 }); log.error(errMsg).withObject(response).sendInternalLogToServer(); throw new Error(errMsg); } }).then(function (response) { self.client._recordAPILatency(POLL_FOR_ACTIVE_REGION_METHOD, request_start); if (typeof response.TerminateActiveContacts !== 'boolean') { log.error("[Disaster Recovery] DR polling response did not contain a valid value for TerminateActiveContacts.").withObject(response).sendInternalLogToServer(); return; } var softFailover = !response.TerminateActiveContacts; if (!response.InstanceArn) { log.error("[Disaster Recovery] DR polling response did not contain a truthy active instance ARN.").withObject(response).sendInternalLogToServer(); return; } else { log.debug("[Disaster Recovery] Successfully polled for active region. Primary instance ARN is ".concat(response.InstanceArn, " ") + "and soft failover is ".concat(softFailover ? "enabled" : "disabled")).sendInternalLogToServer(); } if (self.thisArn === response.InstanceArn && !self.suppress && isFirstPollForCCP) { log.debug("[Disaster Recovery] Instance ".concat(self.thisArn, " is being set to primary")).sendInternalLogToServer(); self.conduit.sendDownstream(connect.DisasterRecoveryEvents.FAILOVER, { nextActiveArn: response.InstanceArn }); } else if (self.otherArn === response.InstanceArn) { // If this poll is to bootstrap the correct region in a newly-opened additional CCP window, and soft failover is enabled, // and a soft failover has already/will be queued to occur once the current voice contact is destroyed, send a UI failover signal // to ensure the new window will display the previous primary region, in case soft failover will delay the UI failover. // Otherwise, the new window may show the wrong region until soft failover completes. if (softFailover && !isFirstPollForWorker && isFirstPollForCCP && (!self.suppress || self.pendingFailover)) { self.conduit.sendDownstream(connect.DisasterRecoveryEvents.FAILOVER, { nextActiveArn: self.thisArn }); } if (!self.suppress) { self.suppress = true; var willSoftFailover = softFailover && !isFirstPollForWorker; if (willSoftFailover) { self.pendingFailover = true; log.debug("[Disaster Recovery] Instance ".concat(self.thisArn, " will be set to stand-by using soft failover")).sendInternalLogToServer(); } else { log.debug("[Disaster Recovery] Instance ".concat(self.thisArn, " is being set to stand-by immediately")).sendInternalLogToServer(); } self.conduit.sendDownstream(connect.DisasterRecoveryEvents.FORCE_OFFLINE, { softFailover: willSoftFailover, nextActiveArn: response.InstanceArn }); } } else if (![self.thisArn, self.otherArn].includes(response.InstanceArn)) { log.error("[Disaster Recovery] The current primary instance in this agent's failover group ".concat(response.InstanceArn, " ") + "doesn't match this instance ".concat(self.thisArn, " or the other instance ").concat(self.otherArn)).sendInternalLogToServer(); } })["catch"](function (response) { if (response.status) { self.client._recordAPILatency(POLL_FOR_ACTIVE_REGION_METHOD, request_start, _objectSpread(_objectSpread({}, response), {}, { statusCode: response.status })); } log.error("[Disaster Recovery] Active region polling failed for instance ".concat(self.thisArn, ".")).withObject(response).sendInternalLogToServer(); })["finally"](function () { // This polling run should only schedule another poll if the worker has just started, or if this poll was triggered by schedule // otherwise, the polling performed when opening each additional CCP window will create its own polling schedule if (isFirstPollForWorker || !isFirstPollForCCP) { global.setTimeout(connect.hitch(self, self.pollForActiveRegion), CHECK_ACTIVE_REGION_INTERVAL_MS); } }); }; // Retrieve pre-signed URL to poll for agent discovery status ClientEngine.prototype.getPresignedDiscoveryUrl = function () { var _this = this; var self = this; return new Promise(function (resolve, reject) { connect.getLog().info("[Disaster Recovery] Getting presigned URL for instance ".concat(self.thisArn)).sendInternalLogToServer(); _this.client.call(connect.ClientMethods.CREATE_TRANSPORT, { transportType: connect.TRANSPORT_TYPES.AGENT_DISCOVERY }, { success: function success(data) { if (data && data.agentDiscoveryTransport && data.agentDiscoveryTransport.presignedUrl) { connect.getLog().info("getPresignedDiscoveryUrl succeeded").sendInternalLogToServer(); resolve(data.agentDiscoveryTransport.presignedUrl); } else { connect.getLog().info("getPresignedDiscoveryUrl received empty/invalid data").withObject(data).sendInternalLogToServer(); reject(Error("getPresignedDiscoveryUrl received empty/invalid data")); } }, failure: function failure(err, data) { connect.getLog().error("[Disaster Recovery] Failed to get presigned URL for instance ".concat(self.thisArn)).withException(err).withObject(data).sendInternalLogToServer(); reject(new Error('Failed to get presigned URL')); }, authFailure: function authFailure() { connect.hitch(self, self.handleAuthFail)(); reject(new Error('Encountered auth failure when getting presigned URL')); }, accessDenied: function accessDenied() { connect.hitch(self, self.handleAccessDenied)(); reject(new Error('Encountered access denied when getting presigned URL')); } }); }); }; ClientEngine.prototype.pollForAgent = function () { var self = this; var onAuthFail = connect.hitch(self, self.handlePollingAuthFail); this.client.call(connect.ClientMethods.GET_AGENT_SNAPSHOT, { nextToken: self.nextToken, timeout: GET_AGENT_TIMEOUT_MS }, { success: function success(data, dataAttribute) { try { self.agent = self.agent || {}; self.agent.snapshot = data.snapshot; self.agent.snapshot.localTimestamp = connect.now(); self.agent.snapshot.skew = self.agent.snapshot.snapshotTimestamp - self.agent.snapshot.localTimestamp; self.nextToken = data.nextToken; if (dataAttribute && dataAttribute.hasOwnProperty('contentLength')) { self.agent.snapshot.contentLength = dataAttribute.contentLength; } connect.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(data).sendInternalLogToServer(); self.updateAgent(); } catch (e) { connect.getLog().error("Long poll failed to update agent.").withObject(data).withException(e).sendInternalLogToServer(); } finally { global.setTimeout(connect.hitch(self, self.pollForAgent), GET_AGENT_SUCCESS_TIMEOUT_MS); } }, failure: function failure(err, data) { try { connect.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({ err: err, data: data }); } finally { global.setTimeout(connect.hitch(self, self.pollForAgent), GET_AGENT_RECOVERY_TIMEOUT_MS); } }, authFailure: function authFailure() { onAuthFail(); }, accessDenied: connect.hitch(self, self.handleAccessDenied) }); }; ClientEngine.prototype.pollForAgentConfiguration = function (paramsIn) { var self = this; var params = paramsIn || {}; var onAuthFail = connect.hitch(self, self.handlePollingAuthFail); this.client.call(connect.ClientMethods.GET_AGENT_CONFIGURATION, {}, { success: function success(data) { var configuration = data.configuration; self.pollForAgentPermissions(configuration); self.pollForAgentStates(configuration); self.pollForDialableCountryCodes(configuration); self.pollForRoutingProfileQueues(configuration); if (params.repeatForever) { global.setTimeout(connect.hitch(self, self.pollForAgentConfiguration, params), GET_AGENT_CONFIGURATION_INTERVAL_MS); } }, failure: function failure(err, data) { try { connect.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({ err: err, data: data }); } finally { if (params.repeatForever) { global.setTimeout(connect.hitch(self, self.pollForAgentConfiguration), GET_AGENT_CONFIGURATION_INTERVAL_MS, params); } } }, authFailure: function authFailure() { onAuthFail(); }, accessDenied: connect.hitch(self, self.handleAccessDenied) }); }; ClientEngine.prototype.pollForAgentStates = function (configuration, paramsIn) { var self = this; var params = paramsIn || {}; params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; this.client.call(connect.ClientMethods.GET_AGENT_STATES, { nextToken: params.nextToken || null, maxResults: params.maxResults }, { success: function success(data) { if (data.nextToken) { self.pollForAgentStates(configuration, { states: (params.states || []).concat(data.states), nextToken: data.nextToken, maxResults: params.maxResults }); } else { configuration.agentStates = (params.states || []).concat(data.states); self.updateAgentConfiguration(configuration); } }, failure: function failure(err, data) { connect.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({ err: err, data: data }); }, authFailure: connect.hitch(self, self.handlePollingAuthFail), accessDenied: connect.hitch(self, self.handleAccessDenied) }); }; ClientEngine.prototype.pollForAgentPermissions = function (configuration, paramsIn) { var self = this; var params = paramsIn || {}; params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; this.client.call(connect.ClientMethods.GET_AGENT_PERMISSIONS, { nextToken: params.nextToken || null, maxResults: params.maxResults }, { success: function success(data) { if (data.nextToken) { self.pollForAgentPermissions(configuration, { permissions: (params.permissions || []).concat(data.permissions), nextToken: data.nextToken, maxResults: params.maxResults }); } else { configuration.permissions = (params.permissions || []).concat(data.permissions); self.updateAgentConfiguration(configuration); } }, failure: function failure(err, data) { connect.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({ err: err, data: data }); }, authFailure: connect.hitch(self, self.handlePollingAuthFail), accessDenied: connect.hitch(self, self.handleAccessDenied) }); }; ClientEngine.prototype.pollForDialableCountryCodes = function (configuration, paramsIn) { var self = this; var params = paramsIn || {}; params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; this.client.call(connect.ClientMethods.GET_DIALABLE_COUNTRY_CODES, { nextToken: params.nextToken || null, maxResults: params.maxResults }, { success: function success(data) { if (data.nextToken) { self.pollForDialableCountryCodes(configuration, { countryCodes: (params.countryCodes || []).concat(data.countryCodes), nextToken: data.nextToken, maxResults: params.maxResults }); } else { configuration.dialableCountries = (params.countryCodes || []).concat(data.countryCodes); self.updateAgentConfiguration(configuration); } }, failure: function failure(err, data) { connect.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({ err: err, data: data }); }, authFailure: connect.hitch(self, self.handlePollingAuthFail), accessDenied: connect.hitch(self, self.handleAccessDenied) }); }; ClientEngine.prototype.pollForRoutingProfileQueues = function (configuration, paramsIn) { var self = this; var params = paramsIn || {}; params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; this.client.call(connect.ClientMethods.GET_ROUTING_PROFILE_QUEUES, { routingProfileARN: configuration.routingProfile.routingProfileARN, nextToken: params.nextToken || null, maxResults: params.maxResults }, { success: function success(data) { if (data.nextToken) { self.pollForRoutingProfileQueues(configuration, { countryCodes: (params.queues || []).concat(data.queues), nextToken: data.nextToken, maxResults: params.maxResults }); } else { configuration.routingProfile.queues = (params.queues || []).concat(data.queues); self.updateAgentConfiguration(configuration); } }, failure: function failure(err, data) { connect.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({ err: err, data: data }); }, authFailure: connect.hitch(self, self.handlePollingAuthFail), accessDenied: connect.hitch(self, self.handleAccessDenied) }); }; ClientEngine.prototype.handleAPIRequest = function (portConduit, request) { var self = this; this.client.call(request.method, request.params, { success: function success(data) { var response = connect.EventFactory.createResponse(connect.EventType.API_RESPONSE, request, data); portConduit.sendDownstream(response.event, response); }, failure: function failure(err, data) { var response = connect.EventFactory.createResponse(connect.EventType.API_RESPONSE, request, data, JSON.stringify(err)); portConduit.sendDownstream(response.event, response); connect.getLog().error("'%s' API request failed", request.method).withObject({ request: self.filterAuthToken(request), response: response }).withException(err).sendInternalLogToServer(); }, authFailure: connect.hitch(self, self.handleAuthFail, { authorize: true }) }); }; /** * Handle incoming master query or modification requests from connected tab ports. */ ClientEngine.prototype.handleMasterRequest = function (portConduit, portId, request) { var multiplexerConduit = this.conduit; var response = null; switch (request.method) { case connect.MasterMethods.BECOME_MASTER: var masterId = this.masterCoord.getMaster(request.params.topic); var takeOver = Boolean(masterId) && masterId !== portId; this.masterCoord.setMaster(request.params.topic, portId); response = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, request, { masterId: portId, takeOver: takeOver, topic: request.params.topic }); if (takeOver) { multiplexerConduit.sendDownstream(response.event, response); } break; case connect.MasterMethods.CHECK_MASTER: var masterId = this.masterCoord.getMaster(request.params.topic); if (!masterId && !request.params.shouldNotBecomeMasterIfNone) { this.masterCoord.setMaster(request.params.topic, portId); masterId = portId; } response = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, request, { masterId: masterId, isMaster: portId === masterId, topic: request.params.topic }); break; default: throw new Error("Unknown master method: " + request.method); } portConduit.sendDownstream(response.event, response); }; ClientEngine.prototype.handleTabIdEvent = function (stream, data) { var self = this; try { var tabId = data.tabId; var streamsInThisTab = self.streamMapByTabId[tabId]; var currentStreamId = stream.getId(); var tabIds = Object.keys(self.streamMapByTabId); var streamsTabsAcrossBrowser = tabIds.filter(function (tabId) { return self.streamMapByTabId[tabId].length > 0; }).length; if (streamsInThisTab && streamsInThisTab.length > 0) { if (!streamsInThisTab.includes(currentStreamId)) { self.streamMapByTabId[tabId].push(currentStreamId); var updateObject = { length: Object.keys(self.portConduitMap).length, tabId: tabId, streamsTabsAcrossBrowser: streamsTabsAcrossBrowser }; updateObject[tabId] = { length: streamsInThisTab.length }; self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, updateObject); } } else { self.streamMapByTabId[tabId] = [stream.getId()]; var _updateObject = { length: Object.keys(self.portConduitMap).length, tabId: tabId, streamsTabsAcrossBrowser: streamsTabsAcrossBrowser + 1 }; _updateObject[tabId] = { length: self.streamMapByTabId[tabId].length }; self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, _updateObject); } } catch (e) { connect.getLog().error("[Tab Ids] Issue updating connected CCPs within the same tab").withException(e).sendInternalLogToServer(); } }; ClientEngine.prototype.handleCloseEvent = function (stream) { var self = this; self.multiplexer.removeStream(stream); delete self.portConduitMap[stream.getId()]; self.masterCoord.removeMaster(stream.getId()); var updateObject = { length: Object.keys(self.portConduitMap).length }; var tabIds = Object.keys(self.streamMapByTabId); try { var tabId = tabIds.find(function (key) { return self.streamMapByTabId[key].includes(stream.getId()); }); if (tabId) { var streamIndexInMap = self.streamMapByTabId[tabId].findIndex(function (value) { return stream.getId() === value; }); self.streamMapByTabId[tabId].splice(streamIndexInMap, 1); var tabLength = self.streamMapByTabId[tabId] ? self.streamMapByTabId[tabId].length : 0; updateObject[tabId] = { length: tabLength }; updateObject.tabId = tabId; } var streamsTabsAcrossBrowser = tabIds.filter(function (tabId) { return self.streamMapByTabId[tabId].length > 0; }).length; updateObject.streamsTabsAcrossBrowser = streamsTabsAcrossBrowser; } catch (e) { connect.getLog().error("[Tab Ids] Issue updating tabId-specific stream data").withException(e).sendInternalLogToServer(); } self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, updateObject); }; ClientEngine.prototype.updateAgentConfiguration = function (configuration) { if (configuration.permissions && configuration.dialableCountries && configuration.agentStates && configuration.routingProfile.queues) { this.agent = this.agent || {}; this.agent.configuration = configuration; this.updateAgent(); } else { connect.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer(); } }; ClientEngine.prototype.updateAgent = function () { if (!this.agent) { connect.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer(); } else if (!this.agent.snapshot) { connect.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer(); } else if (!this.agent.configuration) { connect.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer(); } else { // Alias some of the properties for backwards compatibility. this.agent.snapshot.status = this.agent.state; // Sort the contacts on the timestamp if (this.agent.snapshot.contacts && this.agent.snapshot.contacts.length > 1) { this.agent.snapshot.contacts.sort(function (contactA, contactB) { return contactA.state.timestamp.getTime() - contactB.state.timestamp.getTime(); }); } this.agent.snapshot.contacts.forEach(function (contact) { contact.status = contact.state; contact.connections.forEach(function (connection) { connection.address = connection.endpoint; }); }); this.agent.configuration.routingProfile.defaultOutboundQueue.queueId = this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN; this.agent.configuration.routingProfile.queues.forEach(function (queue) { queue.queueId = queue.queueARN; }); this.agent.snapshot.contacts.forEach(function (contact) { //contact.queue is null when monitoring if (contact.queue !== undefined) { contact.queue.queueId = contact.queue.queueARN; } }); this.agent.configuration.routingProfile.routingProfileId = this.agent.configuration.routingProfile.routingProfileARN; if (this.suppress) { this.agent.snapshot.contacts = this.agent.snapshot.contacts.filter(function (contact) { return contact.state.type == connect.ContactStateType.CONNECTED || contact.state.type == connect.ContactStateType.ENDED; }); if (this.forceOffline) { this.conduit.sendDownstream(connect.DisasterRecoveryEvents.FORCE_OFFLINE); } } this.conduit.sendDownstream(connect.AgentEvents.UPDATE, this.agent); } }; /** * Provides a websocket url through the create_transport API. * @returns a promise which, upon success, returns the response from the createTransport API. */ ClientEngine.prototype.getWebSocketUrl = function () { var self = this; var client = connect.core.getClient(); var onAuthFail = connect.hitch(self, self.handleAuthFail); var onAccessDenied = connect.hitch(self, self.handleAccessDenied); return new Promise(function (resolve, reject) { client.call(connect.ClientMethods.CREATE_TRANSPORT, { transportType: connect.TRANSPORT_TYPES.WEB_SOCKET }, { success: function success(data) { connect.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(); resolve(data); }, failure: function failure(err, data) { connect.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({ err: err, data: data }); reject({ reason: 'getWebSocketUrl failed', _debug: err }); }, authFailure: function authFailure() { connect.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(); reject(Error("Authentication failed while getting getWebSocketUrl")); onAuthFail(); }, accessDenied: function accessDenied() { connect.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(); reject(Error("Access Denied Failure while getting getWebSocketUrl")); onAccessDenied(); } }); }); }; /** * Send a message downstream to all consumers when we detect that authentication * against one of our APIs has failed. */ ClientEngine.prototype.handleSendLogsRequest = function () { var self = this; var logEvents = []; var logsToSend = self.logsBuffer.slice(); self.logsBuffer = []; logsToSend.forEach(function (log) { logEvents.push({ timestamp: log.time, component: log.component, message: log.text }); }); this.client.call(connect.ClientMethods.SEND_CLIENT_LOGS, { logEvents: logEvents }, { success: function success(data) { connect.getLog().info("SendLogs request succeeded.").sendInternalLogToServer(); }, failure: function failure(err, data) { connect.getLog().error("SendLogs request failed.").withObject(data).withException(err).sendInternalLogToServer(); }, authFailure: connect.hitch(self, self.handleAuthFail) }); }; ClientEngine.prototype.handleAuthFail = function (data) { var self = this; if (data) { self.conduit.sendDownstream(connect.EventType.AUTH_FAIL, data); } else { self.conduit.sendDownstream(connect.EventType.AUTH_FAIL); } }; ClientEngine.prototype.handlePollingAuthFail = function () { var self = this; self.conduit.sendDownstream(connect.EventType.CTI_AUTHORIZE_RETRIES_EXHAUSTED); }; ClientEngine.prototype.handleAccessDenied = function () { var self = this; self.conduit.sendDownstream(connect.EventType.ACCESS_DENIED); }; ClientEngine.prototype.checkAuthToken = function () { var self = this; var expirationDate = new Date(self.initData.authTokenExpiration); var currentTimeStamp = new Date().getTime(); var thirtyMins = 30 * 60 * 1000; // refresh token 30 minutes before expiration if (expirationDate.getTime() < currentTimeStamp + thirtyMins) { connect.getLog().info("Auth token expires at " + expirationDate + " Start refreshing token with retry.").sendInternalLogToServer(); connect.backoff(connect.hitch(self, self.authorize), REFRESH_AUTH_TOKEN_INTERVAL_MS, REFRESH_AUTH_TOKEN_MAX_TRY); } }; ClientEngine.prototype.authorize = function (callbacks) { var self = this; connect.core.authorize(this.initData.authorizeEndpoint).then(function (response) { var expiration = new Date(response.expiration); connect.getLog().info("Authorization succeeded and the token expires at %s", expiration).sendInternalLogToServer(); self.initData.authToken = response.accessToken; self.initData.authTokenExpiration = expiration; connect.core.initClient(self.initData); connect.core.initAgentAppClient(self.initData); callbacks.success(); })["catch"](function (response) { connect.getLog().error("Authorization failed with code %s", response.status).sendInternalLogToServer(); if (response.status === 401) { self.handleAuthFail(); } else { callbacks.failure(); } }); }; /** * Filter the 'authentication' field of the request params from the given API_REQUEST event. */ ClientEngine.prototype.filterAuthToken = function (request) { var new_request = {}; for (var keyA in request) { if (keyA === 'params') { var new_params = {}; for (var keyB in request.params) { if (keyB !== 'authentication') { new_params[keyB] = request.params[keyB]; } } new_request.params = new_params; } else { new_request[keyA] = request[keyA]; } } return new_request; }; /**-----------------------------------------------------------------------*/ connect.worker.main = function () { connect.worker.clientEngine = new ClientEngine(); }; })(); /***/ }), /***/ 181: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * lodash (Custom Build) * Build: `lodash modularize exports="npm" -o ./` * Copyright jQuery Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max, nativeMin = Math.min; /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = function() { return root.Date.now(); }; /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall; return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = debounce; /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/amd options */ /******/ (() => { /******/ __webpack_require__.amdO = {}; /******/ })(); /******/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module used 'module' so it can't be inlined /******/ __webpack_require__(167); /******/ __webpack_require__(254); /******/ __webpack_require__(344); /******/ __webpack_require__(144); /******/ __webpack_require__(60); /******/ __webpack_require__(682); /******/ __webpack_require__(431); /******/ __webpack_require__(555); /******/ __webpack_require__(830); /******/ __webpack_require__(414); /******/ __webpack_require__(610); /******/ __webpack_require__(95); /******/ __webpack_require__(399); /******/ __webpack_require__(906); /******/ __webpack_require__(806); /******/ __webpack_require__(354); /******/ __webpack_require__(142); /******/ __webpack_require__(884); /******/ __webpack_require__(390); /******/ __webpack_require__(269); /******/ __webpack_require__(825); /******/ __webpack_require__(961); /******/ var __webpack_exports__ = __webpack_require__(949); /******/ /******/ })() ;