var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { EventEmitter } from 'events';
import { HttpClient, StreamingClientError, StreamingClientErrorTypes } from 'genesys-cloud-streaming-client';
import { jwtDecode } from "jwt-decode";
import { isSecurityCode, isCustomerData } from './types/interfaces';
import { setupStreamingClient, proxyStreamingClientEvents } from './client-private';
import { requestApi, createAndEmitSdkError, defaultConfigOption, requestApiWithRetry } from './utils';
import { setupLogging } from './logging';
import { MediaHandling, SdkErrorTypes, SessionTypes } from './types/enums';
import { SdkMedia } from './media/media';
import { HeadsetProxyService } from './headsets/headset';
import { setupWebrtcForWindows11 } from './windows11-first-session-hack';
const ENVIRONMENTS = [
    'mypurecloud.com',
    'mypurecloud.com.au',
    'mypurecloud.jp',
    'mypurecloud.de',
    'mypurecloud.ie',
    'usw2.pure.cloud',
    'cac1.pure.cloud',
    'euw2.pure.cloud',
    'apne2.pure.cloud',
    'use2.us-gov-pure.cloud',
    'sae1.pure.cloud',
    'aps1.pure.cloud'
];
const DISASSOCIATED_EVENT = 'Disassociated';
const ASSOCIATED_EVENT = 'Associated';
/**
 * Validate SDK construct options.
 *  Returns `null` if no errors,
 *    returns `string` with error message if there are errors
 * @param options
 */
function validateOptions(options) {
    if (!options) {
        return 'Options required to create an instance of the SDK';
    }
    if (!options.accessToken && !options.organizationId && !options.jwt) {
        return 'An accessToken, jwt, or organizationId (for guest access) is required to instantiate the sdk.';
    }
    if (!options.environment) {
        (options.logger || console).warn('No environment provided, using mypurecloud.com');
        options.environment = 'mypurecloud.com';
    }
    if (ENVIRONMENTS.indexOf(options.environment) === -1) {
        (options.logger || console).warn('Environment is not in the standard list. You may not be able to connect.');
    }
    return null;
}
/**
 * SDK to interact with GenesysCloud WebRTC functionality
 */
export class GenesysCloudWebrtcSdk extends EventEmitter {
    get isInitialized() {
        return !!this._streamingConnection;
    }
    get connected() {
        return !!this._streamingConnection.connected;
    }
    get isJwtAuth() {
        return !!this._config.jwt;
    }
    get isGuest() {
        return !this.isJwtAuth && !this._config.accessToken;
    }
    get VERSION() {
        return GenesysCloudWebrtcSdk.VERSION;
    }
    constructor(options) {
        super();
        this._mediaHandling = MediaHandling.standardMedia;
        const errorMsg = validateOptions(options);
        if (errorMsg) {
            throw createAndEmitSdkError.call(this, SdkErrorTypes.invalid_options, errorMsg, options);
        }
        /* grab copies or valid objects */
        const defaultsOptions = options.defaults || {};
        let allowedSessionTypes = options.allowedSessionTypes || [SessionTypes.softphone, SessionTypes.collaborateVideo, SessionTypes.acdScreenShare, SessionTypes.liveScreenMonitoring];
        // If using JWT auth, we only support screen recording, video conferencing and live screen monitoring.
        if (options.jwt) {
            console.debug(`Forcing allowed session types to be ${SessionTypes.screenRecording}, ${SessionTypes.collaborateVideo} and ${SessionTypes.liveScreenMonitoring} due to jwt auth`);
            allowedSessionTypes = [SessionTypes.screenRecording, SessionTypes.collaborateVideo, SessionTypes.liveScreenMonitoring];
        }
        this._config = Object.assign(Object.assign({}, options), {
            autoConnectSessions: options.autoConnectSessions !== false, // default true
            autoAcceptPendingScreenRecordingRequests: !!options.autoAcceptPendingScreenRecordingRequests,
            autoAcceptPendingLiveScreenMonitoringRequests: !!options.autoAcceptPendingLiveScreenMonitoringRequests,
            logLevel: options.logLevel || 'info',
            disableAutoAnswer: options.disableAutoAnswer || false, // default false
            optOutOfTelemetry: options.optOutOfTelemetry || false, // default false
            allowedSessionTypes,
            useHeadsets: options.useHeadsets || false, // default false
            customHeaders: options.customHeaders,
            useServerSidePings: defaultConfigOption(options.useServerSidePings, false),
            reportStatistics: defaultConfigOption(options.reportStatistics, false),
            eagerPersistentConnectionEstablishment: defaultConfigOption(options.eagerPersistentConnectionEstablishment, 'auto'),
            skipConstraints: options.skipConstraints,
            /* sdk defaults */
            defaults: Object.assign(Object.assign({}, defaultsOptions), { audioStream: undefined, micAutoGainControl: defaultConfigOption(defaultsOptions.micAutoGainControl, true), micEchoCancellation: defaultConfigOption(defaultsOptions.micEchoCancellation, true), micNoiseSuppression: defaultConfigOption(defaultsOptions.micNoiseSuppression, true), videoDeviceId: defaultsOptions.videoDeviceId || null, audioDeviceId: defaultsOptions.audioDeviceId || null, audioVolume: defaultConfigOption(defaultsOptions.audioVolume, 100), outputDeviceId: defaultsOptions.outputDeviceId || null, monitorMicVolume: !!defaultsOptions.monitorMicVolume // default to false
             })
        });
        this._orgDetails = { id: options.organizationId };
        setupLogging.call(this, options.logger || console);
        this._config.logger = this.logger;
        this.media = new SdkMedia(this);
        this.headset = new HeadsetProxyService(this);
        this.setDefaultAudioStream(defaultsOptions.audioStream);
        // Telemetry for specific events
        // onPendingSession, onSession, onMediaStarted, onSessionTerminated logged in event handlers
        this.on('cancelPendingSession', (ids) => this.logger.info('cancelPendingSession', ids));
        this.on('handledPendingSession', (ids) => this.logger.info('handledPendingSession', ids));
        this.on('sdkError', (error) => {
            /* this prints it more readable in the console */
            this.logger.error('sdkError', {
                name: error.name,
                message: error.message,
                type: error.type,
                details: error.details
            });
        });
        this._connected = false;
        this._preDisconnectSessionIds = [];
        this._streamingConnection = null;
        this._http = new HttpClient();
    }
    /**
     * Setup the SDK for use and authenticate the user
     *  - agents must have an accessToken passed into the constructor options
     *  - guests need a securityCode (or the data received from an
     *    already redeemed securityCode). If the customerData is not passed in
     *    this will redeem the code for the data, else it will use the data
     *    passed in.
     *
     * @param opts optional initialize options
     *
     * @returns a promise that is fulled once the web socket is connected
     *  and other necessary async tasks are complete.
     */
    initialize(opts) {
        return __awaiter(this, void 0, void 0, function* () {
            var _a, _b;
            const httpRequests = [];
            if (this.isGuest) {
                let guestPromise;
                /* if there is a securityCode, fetch conversation details */
                if (isSecurityCode(opts)) {
                    this.logger.debug('Fetching conversation details via secuirty code', opts.securityCode);
                    guestPromise = requestApi.call(this, '/conversations/codes', {
                        method: 'post',
                        data: {
                            organizationId: this._orgDetails.id,
                            addCommunicationCode: opts.securityCode
                        },
                        noAuthHeader: true
                    }).then(({ data }) => {
                        this._customerData = data;
                    });
                    /* if no securityCode, check for valid customerData */
                }
                else if (isCustomerData(opts)) {
                    this.logger.debug('Using customerData passed into the initialize', opts);
                    guestPromise = Promise.resolve().then(() => {
                        this._customerData = opts;
                    });
                }
                else {
                    throw createAndEmitSdkError.call(this, SdkErrorTypes.invalid_options, '`securityCode` is required to initialize the SDK as a guest');
                }
                httpRequests.push(guestPromise);
            }
            else if (this.isJwtAuth) {
                this.parseJwt();
            }
            else {
                const getOrg = this.fetchOrganization();
                const getPerson = this.fetchAuthenticatedUser();
                httpRequests.push(getOrg);
                httpRequests.push(getPerson);
            }
            try {
                yield Promise.all(httpRequests);
                yield setupStreamingClient.call(this);
                yield proxyStreamingClientEvents.call(this);
                yield setupWebrtcForWindows11(this._streamingConnection._webrtcSessions['iceServers']);
                /* istanbul ignore next */
                window.addEventListener('beforeunload', () => {
                    this.logger.info('window.beforeunload was called', { activeConversationsForClient: this.sessionManager.getAllActiveConversations() });
                });
                const sessionsToActivate = this._config.allowedSessionTypes;
                this._config.allowedSessionTypes = [];
                const activateSessionTypes = sessionsToActivate.map((allowedSessionType) => this.addAllowedSessionType(allowedSessionType));
                if ((_a = this._config.jidResource) === null || _a === void 0 ? void 0 : _a.startsWith('mediahelper')) {
                    this._config.headsetRequestType = 'mediaHelper';
                }
                yield Promise.all(activateSessionTypes);
                this.headset.initialize();
                this.emit('ready');
            }
            catch (err) {
                if (err instanceof StreamingClientError && err.type == StreamingClientErrorTypes.invalid_token) {
                    throw createAndEmitSdkError.call(this, SdkErrorTypes.invalid_token, err.message, err);
                }
                if (err.name === 'AxiosError' && [401, 403].includes(((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) || 0)) {
                    throw createAndEmitSdkError.call(this, SdkErrorTypes.invalid_token, err.message, err);
                }
                throw createAndEmitSdkError.call(this, SdkErrorTypes.initialization, err.message, err);
            }
        });
    }
    addAllowedSessionType(sessionType) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this._config.allowedSessionTypes.includes(sessionType)) {
                this.logger.warn('addAllowedSessionType was called but the sessionType is already allowed', { sessionType });
                return;
            }
            this.logger.info('adding sessionType', { sessionType });
            if (sessionType === SessionTypes.softphone && !this.isGuest) {
                this.logger.info('Softphone sessionType added, requesting station');
                const stationReq = this.fetchUsersStation()
                    .catch((err) => {
                    // these errors shouldn't halt initialization
                    this.logger.warn('error fetching users station', err);
                });
                const stationSub = this.listenForStationEvents();
                yield Promise.all([stationReq, stationSub]);
            }
            yield this.sessionManager.addAllowedSessionType(sessionType);
            this._config.allowedSessionTypes.push(sessionType);
        });
    }
    removeAllowedSessionType(sessionType) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this._config.allowedSessionTypes.includes(sessionType)) {
                this.logger.warn('removeAllowedSessionType was called but the sessionType is already disallowed', { sessionType });
                return;
            }
            this.logger.info('removing sessionType', { sessionType });
            yield this.sessionManager.removeAllowedSessionType(sessionType);
            this._config.allowedSessionTypes = this._config.allowedSessionTypes.filter(st => st.toString() !== sessionType.toString());
        });
    }
    isScreenRecordingSession(session) {
        return session.sessionType === SessionTypes.screenRecording;
    }
    isVideoSession(session) {
        return session.sessionType === SessionTypes.collaborateVideo;
    }
    isLiveScreenMonitoringSession(session) {
        return session.sessionType === SessionTypes.liveScreenMonitoring;
    }
    /**
     * Start a screen share. Currently, screen share is only supported
     *  for guest users.
     *
     *  `initialize()` must be called first.
     *
     * @returns MediaStream promise of the selected screen stream
     */
    startScreenShare() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.isGuest) {
                return this.sessionManager.startSession({ sessionType: SessionTypes.acdScreenShare });
            }
            else {
                throw createAndEmitSdkError.call(this, SdkErrorTypes.not_supported, 'Agent screen share is not yet supported');
            }
        });
    }
    /**
     * Start a video conference. Not supported for guests.
     *  Conferences can only be joined by authenticated users
     *  from the same organization. If `inviteeJid` is provided,
     *  the specified user will receive a propose/pending session
     *  they can accept and join the conference.
     *
     *  `initialize()` must be called first.
     *
     * @param roomJid jid of the conference to join. Can be made up if
     *  starting a new conference but must adhere to the format:
     *  <lowercase string>@conference.<lowercase string>
     * @param inviteeJid jid of a user to invite to this conference.
     *
     * @returns a promise with an object with the newly created `conversationId`
     */
    startVideoConference(roomJid, inviteeJid) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this._config.jwt && !this._config.accessToken) {
                throw createAndEmitSdkError.call(this, SdkErrorTypes.not_supported, 'Video conferencing requires authentication via JWT or access token.');
            }
            return this.sessionManager.startSession({ jid: roomJid, inviteeJid, sessionType: SessionTypes.collaborateVideo });
        });
    }
    /**
     * Start a video conference using a meeting id. Not supported for guests.
     *  Conferences can only be joined by authenticated users
     *  from the same organization.
     *
     *  `initialize()` must be called first.
     *
     * @param meetingId meetingId of the conference to join.
     *
     * @returns a promise with an object with the newly created 'conversationId'
     */
    startVideoMeeting(meetingId) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.isGuest) {
                throw createAndEmitSdkError.call(this, SdkErrorTypes.not_supported, 'video conferencing meetings not supported for guests');
            }
            return this.sessionManager.startSession({ meetingId, sessionType: SessionTypes.collaborateVideo });
        });
    }
    /**
     * Start a softphone session with the given peer or peers.
     *  `initialize()` must be called first.
     *
     * @param softphoneParams participant information for initiating a softphone session. See IStartSoftphoneSessionParams for more details.
     */
    startSoftphoneSession(softphoneParams) {
        return __awaiter(this, void 0, void 0, function* () {
            softphoneParams.sessionType = SessionTypes.softphone;
            const callInfo = yield this.sessionManager.startSession(softphoneParams);
            return callInfo;
        });
    }
    /**
     * Update the output device for all incoming audio
     *
     *  NOTES:
     *    - This will log a warning and not attempt to update
     *        the output device if the a broswer
     *        does not support output devices
     *    - This will attempt to update all active sessions
     *    - This does _not_ update the sdk `defaultOutputDeviceId`
     * @param deviceId `deviceId` for audio output, `true` for sdk default output, or `null` for system default
     * @returns a promise that fullfils once the output deviceId has been updated
     */
    updateOutputDevice(deviceId) {
        if (!this.media.getState().hasOutputDeviceSupport) {
            const sessions = this.sessionManager.getAllActiveSessions()
                .map(s => ({ sessionId: s.id, conversationId: s.conversationId }));
            this.logger.warn('cannot update output deviceId in unsupported browser', sessions);
            return;
        }
        return this.sessionManager.updateOutputDeviceForAllSessions(deviceId);
    }
    /**
     * Update outgoing media for a specified session
     *  - `conversationId` _or_ `session` is required to find the session to update
     *  - `stream`: if a stream is passed in, the session media will be
     *    updated to use the media on the stream. This supercedes deviceId(s)
     *    passed in.
     *  - `videoDeviceId` & `audioDeviceId` (superceded by `stream`)
     *    - `undefined|false`: the sdk will not touch the `video|audio` media
     *    - `null`: the sdk will update the `video|audio` media to system default
     *    - `string`: the sdk will attempt to update the `video|audio` media
     *        to the passed in deviceId
     *
     * Note: this does not update the SDK default device(s). Also, if the requested
     *  device is _already in use_ by the session, the media will not be re-requested.
     *
     * @param updateOptions device(s) to update
     *
     * @returns a promise that fullfils once the outgoing
     *  media devices have been updated
     */
    updateOutgoingMedia(updateOptions) {
        const updatingVideo = updateOptions.videoDeviceId || updateOptions.videoDeviceId === null;
        const updatingAudio = updateOptions.audioDeviceId || updateOptions.audioDeviceId === null;
        if (!updateOptions || (!updateOptions.stream && !updatingVideo && !updatingAudio)) {
            throw createAndEmitSdkError.call(this, SdkErrorTypes.invalid_options, 'updateOutgoingMedia must be called with a MediaStream, a videoDeviceId, or an audioDeviceId');
        }
        return this.sessionManager.updateOutgoingMedia(updateOptions);
    }
    /**
     * Update the default device(s) for the sdk.
     *  Pass in the following:
     *  - `string`: sdk will update that default to the deviceId
     *  - `null`: sdk will update to system default device
     *  - `undefined`: sdk will not update that media deviceId
     *
     * If `updateActiveSessions` is `true`, any active sessions will
     *  have their outgoing media devices updated and/or the output
     *  deviceId updated. Note, if the requested device is
     *  _already in use_ by the session, the media will not be re-requested.
     *
     * Else, only the sdk defaults will be updated and active sessions'
     * media devices will not be touched.
     *
     * @param options default device(s) to update
     *
     * @returns a promise that fullfils once the default
     *  device values have been updated
     */
    updateDefaultDevices() {
        return __awaiter(this, arguments, void 0, function* (options = {}) {
            const updateVideo = options.videoDeviceId !== undefined;
            const updateAudio = options.audioDeviceId !== undefined;
            const updateOutput = options.outputDeviceId !== undefined;
            if (updateVideo) {
                this.logger.info('Updating defaultVideoDeviceId', { defaultVideoDeviceId: options.videoDeviceId });
                this._config.defaults.videoDeviceId = options.videoDeviceId;
            }
            if (updateAudio) {
                this.logger.info('Updating defaultAudioDeviceId', { defaultAudioDeviceId: options.audioDeviceId });
                this.headset.updateAudioInputDevice(options.audioDeviceId);
                this._config.defaults.audioDeviceId = options.audioDeviceId;
            }
            if (updateOutput) {
                this.logger.info('Updating defaultOutputDeviceId', { defaultOutputDeviceId: options.outputDeviceId });
                this._config.defaults.outputDeviceId = options.outputDeviceId;
            }
            if (typeof options.updateActiveSessions === 'boolean' && options.updateActiveSessions) {
                const promises = [];
                this.logger.info('Updating devices for all active session', {
                    defaultVideoDeviceId: options.videoDeviceId,
                    defaultAudioDeviceId: options.audioDeviceId,
                    defaultOutputDeviceId: options.outputDeviceId
                });
                if ((updateVideo || updateAudio) && this.sessionManager) {
                    const updateOptions = {};
                    if (updateVideo)
                        updateOptions.videoDeviceId = options.videoDeviceId;
                    if (updateAudio)
                        updateOptions.audioDeviceId = options.audioDeviceId;
                    promises.push(this.sessionManager.updateOutgoingMediaForAllSessions(updateOptions));
                }
                if (updateOutput && this.sessionManager) {
                    promises.push(this.sessionManager.updateOutputDeviceForAllSessions(this._config.defaults.outputDeviceId));
                }
                return Promise.all(promises).then(() => undefined);
            }
        });
    }
    /**
   * Update the default resolution of the selected video track for the sdk.
   *  Pass in the following:
   *  - resolution: Either undefined or an object containing ConstrainULongs
   *      representing both width and height
   *  - updateActiveSessions: boolean
   *
   * If `updateActiveSessions` is `true`, any active sessions will
   *  have their video resolutions updated to either the selected resolution
   *  or the next best resolution the device is capable of
   *
   * Else, only the sdk defaults will be updated and active sessions'
   * resolutions will not be touched
   *
   * Success or failure of `applyConstraints` will emit an event for
   * the consuming app to listen for so that it can determine if the
   * resolution they requested is actually in place or the next best
   * option. This will allow the consuming app to notify the user as
   * they see fit.
   *
   * @param resolution the width and height that was requested
   * to update the video; could be undefined to represent the default value
   *
   * @returns a promise that fullfils once the event has been emitted
   * signaling that the resolution has updated
   */
    updateDefaultResolution(resolution, updateActiveSessions) {
        return __awaiter(this, void 0, void 0, function* () {
            this._config.defaults.videoResolution = resolution;
            if (!updateActiveSessions) {
                return;
            }
            this.sessionManager.getAllActiveSessions()
                .filter(session => session.sessionType === 'collaborateVideo' && session._outboundStream)
                .forEach(videoSession => {
                videoSession._outboundStream.getVideoTracks().forEach((track) => __awaiter(this, void 0, void 0, function* () {
                    try {
                        if (resolution) {
                            yield track.applyConstraints(Object.assign(Object.assign({}, track.getConstraints()), { height: resolution.height, width: resolution.width }));
                        }
                        else {
                            /* If the consumer passes in undefined, it means they selected the default resolution
                              option.  Since we do not know what the system default is, we will need to stop the current
                              track and re-request the media again so that it fetches the system default automatically.
                            */
                            track.stop();
                            videoSession._outboundStream.removeTrack(track);
                            const newTrack = (yield this.media.startMedia({ video: true, session: videoSession })).getVideoTracks()[0];
                            yield this.sessionManager.addOrReplaceTrackOnSession(newTrack, videoSession);
                            videoSession._outboundStream.addTrack(newTrack);
                        }
                    }
                    catch (e) {
                        createAndEmitSdkError.call(this, SdkErrorTypes.generic, e.message, e);
                    }
                    const actualResolution = { width: track.getSettings().width, height: track.getSettings().height };
                    if ((resolution === null || resolution === void 0 ? void 0 : resolution.width) !== actualResolution.width || (resolution === null || resolution === void 0 ? void 0 : resolution.height) !== actualResolution.height) {
                        this._config.defaults.videoResolution = resolution ? actualResolution : undefined;
                    }
                    this.emit('resolutionUpdated', {
                        requestedResolution: resolution,
                        actualResolution: actualResolution,
                        videoTrack: track,
                        sessionId: videoSession.id,
                        conversationId: videoSession.conversationId
                    });
                }));
            });
        });
    }
    /**
     * Update the default media settings from the config.
     *
     * If `updateActiveSessions` is `true`, any active sessions will
     *  have their outgoing media devices updated.
     *
     * Else, only the defaults will be updated and active sessions'
     * media devices will not be touched.
     *
     * @returns a promise that fullfils once the default
     *  settings and sessions are updated (if specified)
     */
    updateDefaultMediaSettings(settings) {
        return __awaiter(this, void 0, void 0, function* () {
            var _a;
            const allowedSettings = [
                'micAutoGainControl',
                'micEchoCancellation',
                'micNoiseSuppression',
                'monitorMicVolume'
            ];
            const entries = Object.entries(settings)
                .filter(([setting]) => allowedSettings.includes(setting));
            this.logger.info('updating media settings', entries);
            entries.forEach(([key, value]) => {
                this._config.defaults[key] = value;
            });
            if (settings.updateActiveSessions) {
                return (_a = this.sessionManager) === null || _a === void 0 ? void 0 : _a.updateOutgoingMediaForAllSessions();
            }
        });
    }
    /**
     * Updates the audio volume for all active applicable sessions
     * as well as the default volume for future sessions
     *
     * @param volume desired volume between 0 and 100
     *
     * @returns void
     */
    updateAudioVolume(volume) {
        var _a;
        if (volume < 0 || volume > 100) {
            throw createAndEmitSdkError.call(this, SdkErrorTypes.not_supported, 'Invalid volume level. Must be between 0 and 100 inclusive.', { providedVolume: volume });
        }
        this._config.defaults.audioVolume = volume;
        (_a = this.sessionManager) === null || _a === void 0 ? void 0 : _a.updateAudioVolume(volume);
    }
    fetchOrganization() {
        return __awaiter(this, void 0, void 0, function* () {
            return requestApiWithRetry.call(this, '/organizations/me').promise
                .then(({ data }) => {
                this._orgDetails = data;
                this.logger.debug('Fetched organization details', data, { skipServer: true }); // don't log PII
                return data;
            });
        });
    }
    fetchAuthenticatedUser() {
        return __awaiter(this, void 0, void 0, function* () {
            return requestApiWithRetry.call(this, '/users/me?expand=station').promise
                .then(({ data }) => {
                this._personDetails = data;
                this.logger.debug('Fetched person details', data, { skipServer: true }); // don't log PII
                return data;
            });
        });
    }
    parseJwt() {
        try {
            const decoded = jwtDecode(this._config.jwt);
            this._personDetails = {
                id: decoded.data.uid,
                name: decoded.name,
                chat: {
                    jabberId: decoded.data.jid
                }
            };
            this._customerData = {
                conversation: {
                    id: decoded.data.conversationId,
                },
                sourceCommunicationId: decoded.data.sourceCommunicationId,
                jwt: this._config.jwt
            };
            this._orgDetails = {
                id: decoded.org,
                name: null
            };
        }
        catch (e) {
            throw createAndEmitSdkError.call(this, SdkErrorTypes.invalid_options, 'Failed to parse provided jwt, please ensure it is valid', e);
        }
    }
    fetchUsersStation() {
        return __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c;
            if (!this._personDetails) {
                yield this.fetchAuthenticatedUser();
            }
            const stationId = (_c = (_b = (_a = this._personDetails) === null || _a === void 0 ? void 0 : _a.station) === null || _b === void 0 ? void 0 : _b.effectiveStation) === null || _c === void 0 ? void 0 : _c.id;
            if (!stationId) {
                const error = new Error('User does not have an effective station');
                throw createAndEmitSdkError.call(this, SdkErrorTypes.generic, error.message, error);
            }
            const { data } = yield requestApiWithRetry.call(this, `/stations/${stationId}`).promise;
            this.station = data;
            this.logger.info('Fetched user station', {
                userId: data.userId,
                type: data.type,
                webRtcPersistentEnabled: data.webRtcPersistentEnabled,
                webRtcForceTurn: data.webRtcForceTurn,
                webRtcCallAppearances: data.webRtcCallAppearances,
            });
            this.emit('concurrentSoftphoneSessionsEnabled', this.isConcurrentSoftphoneSessionsEnabled());
            this.emit('station', { action: 'Associated', station: data });
            return data;
        });
    }
    /**
     * Check to see if the user's currently effective station has
     *  persistent connection enabled.
     *
     * @returns if the station has persistent connection enabled
     */
    isPersistentConnectionEnabled() {
        const station = this.station;
        return !!(station &&
            station.webRtcPersistentEnabled &&
            station.type === 'inin_webrtc_softphone');
    }
    /**
     * Check to see if the user's currently effective station has
     *  Line Appearance > 1.
     *
     * @returns if the station has Line Appearance > 1
     */
    isConcurrentSoftphoneSessionsEnabled() {
        var _a;
        return ((_a = this.station) === null || _a === void 0 ? void 0 : _a.webRtcCallAppearances) > 1;
    }
    /**
     * Mutes/Unmutes video/camera for a session and updates the conversation accordingly.
     * Will fail if the session is not found.
     * Incoming video is unaffected.
     *
     * When muting, the camera track is destroyed. When unmuting, the camera media
     *  must be requested again.
     *
     * NOTE: if no `unmuteDeviceId` is provided when unmuting, it will unmute and
     *  attempt to use the sdk `defaultVideoDeviceId` as the camera device
     *
     * @returns a promise that fullfils once the mute request has completed
     */
    setVideoMute(muteOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.sessionManager.setVideoMute(muteOptions);
        });
    }
    /**
     * Mutes/Unmutes audio/mic for a session and updates the conversation accordingly.
     * Will fail if the session is not found.
     * Incoming audio is unaffected.
     *
     * NOTE: if no `unmuteDeviceId` is provided when unmuting _AND_ there is no active
     *  audio stream, it will unmute and attempt to use the sdk `defaultAudioDeviceId`
     *  at the device
     *
     * @returns a promise that fullfils once the mute request has completed
     */
    setAudioMute(muteOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.sessionManager.setAudioMute(muteOptions);
        });
    }
    /**
     * Set a conversation's hold state.
     *
     * > NOTE: only applicable for softphone conversations
     *
     * @param heldOptions conversationId and desired held state
     */
    setConversationHeld(heldOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.sessionManager.setConversationHeld(heldOptions);
        });
    }
    /**
     * Set the accessToken the sdk uses to authenticate
     *  to the API.
     * @param token new access token
     *
     * @returns void
     */
    setAccessToken(token) {
        this._config.accessToken = token;
        this.logger.setAccessToken(token);
        if (this._streamingConnection) {
            this._streamingConnection.config.authToken = token;
        }
    }
    /**
   * Set the JWT the sdk uses to authenticate
   *  to the API.
   * @param jwt new jwt
   *
   * @returns void
   */
    setJwt(jwt) {
        this._config.jwt = jwt;
        // this.logger.setJwt(jwt);
        if (this._streamingConnection) {
            this._streamingConnection.config.jwt = jwt;
        }
    }
    /**
     * Changes the headset functionality for the sdk
     * @param useHeadsets if true, this enables events from active headsets
     *
     * @returns void
     */
    setUseHeadsets(useHeadsets) {
        this._config.useHeadsets = !!useHeadsets;
        this.headset.setUseHeadsets(!!useHeadsets);
    }
    /**
     * Set the sdk default audioStream. This will call
     *  through to `sdk.media.setDefaultAudioStream(stream);`
     *
     * Calling with a falsy value will clear out sdk default.
     *
     * @param stream media stream to use
     */
    setDefaultAudioStream(stream) {
        this.media.setDefaultAudioStream(stream);
    }
    /**
     * **Genesys internal use only** - non-Genesys apps may experience unexpected behavior.
     *
     * Change the media handling for softphone sessions, which should be
     * be chosen based on the alerting leader status of the consuming client.
     *
     * If media handling is reduced, idle persistent connections will be
     * disconnected.
     *
     * @param mediaHandling how softphone media should be handled
     */
    setMediaHandling(mediaHandling) {
        const useHeadsets = !(mediaHandling === MediaHandling.reducedMedia);
        if (!this.sessionManager) {
            this._mediaHandling = mediaHandling;
            this.setUseHeadsets(useHeadsets);
            return;
        }
        const activeConversations = this.sessionManager.getAllActiveConversations();
        if (activeConversations.length !== 0 && !useHeadsets) {
            this._mediaHandling = MediaHandling.reducedMediaHeadsets;
            this.setUseHeadsets(true);
            throw createAndEmitSdkError.call(this, SdkErrorTypes.not_supported, 'Cannot downgrade media handling to stop using headsets during an active call');
        }
        this._mediaHandling = mediaHandling;
        this.setUseHeadsets(useHeadsets);
        const reduceMediaHandling = mediaHandling === MediaHandling.reducedMediaHeadsets || mediaHandling === MediaHandling.reducedMedia;
        if (reduceMediaHandling) {
            const conversationSessionIds = activeConversations.map(conversation => conversation.sessionId);
            // Disconnect connections that aren't associated with an active conversation.
            // When a client is no longer the alerting leader, it needs to give up any
            // persistent connections. Active calls should be maintained.
            this.sessionManager.getAllSessions().forEach(session => {
                if (session.sessionType === SessionTypes.softphone && !conversationSessionIds.includes(session.id)) {
                    this.sessionManager.forceTerminateSession(session.id);
                }
            });
        }
    }
    /**
     * Accept a pending session based on the passed in conversation ID.
     *
     * @param params conversationId of the pending session to accept
     * @returns a promise that fullfils once the session accept goes out
     */
    acceptPendingSession(params) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.sessionManager.proceedWithSession(params);
        });
    }
    /**
     * Reject a pending session based on the passed in conversation ID.
     *
     * @param params conversationId of the pending session to reject
     * @returns a promise that fullfils once the session reject goes out
     */
    rejectPendingSession(params) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.sessionManager.rejectPendingSession(params);
        });
    }
    /**
     * Accept a pending session based on the passed in ID.
     *
     * @param acceptOptions options with which to accept the session
     * @returns a promise that fullfils once the session accept goes out
     */
    acceptSession(acceptOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.sessionManager.acceptSession(acceptOptions);
        });
    }
    /**
     * End an active session based on the conversation ID (one is required)
     * @param opts object with conversation ID
     * @returns a promise that fullfils once the session has ended
     */
    endSession(endOptions) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.sessionManager.endSession(endOptions);
        });
    }
    /**
     * End an active session based on the session ID
     * @param sessionId session ID corresponding to the session you want to force terminate
     * @param reason optional reason to terminate the session with. defaults to "success"
     * @returns a promise that fullfils once the session has ended
     */
    forceTerminateSession(sessionId, reason) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.sessionManager.forceTerminateSession(sessionId, reason);
        });
    }
    /**
     * Disconnect the streaming connection
     * @returns a promise that fullfils once the web socket has disconnected
     */
    disconnect() {
        var _a;
        this._http.stopAllRetries();
        return (_a = this._streamingConnection) === null || _a === void 0 ? void 0 : _a.disconnect();
    }
    /**
     * Ends all active sessions, disconnects the
     *  streaming-client, removes all event listeners,
     *  and cleans up media.
     *
     * WARNING: calling this effectively renders the SDK
     *  instance useless. A new instance will need to be
     *  created after this is called.
     *
     * @returns a promise that fullfils once all the cleanup
     *  tasks have completed
     */
    destroy() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this.sessionManager) {
                return;
            }
            const activeSessions = this.sessionManager.getAllSessions();
            this.logger.info('destroying webrtc sdk', {
                activeSessions: activeSessions.map(s => ({ sessionId: s.id, conversationId: s.conversationId }))
            });
            yield Promise.all(activeSessions.map(s => this.sessionManager.forceTerminateSession(s.id)));
            this.removeAllListeners();
            this.media.destroy();
            yield this.disconnect();
        });
    }
    listenForStationEvents() {
        return this._streamingConnection._notifications.subscribe(`v2.users.${this._personDetails.id}.station`, (event) => {
            var _a;
            if (event.metadata.action === DISASSOCIATED_EVENT) {
                this.logger.info('station disassociated', {
                    stationId: (_a = this.station) === null || _a === void 0 ? void 0 : _a.id
                });
                this.station = null;
                this.emit('station', { action: 'Disassociated', station: null });
            }
            else if (event.metadata.action === ASSOCIATED_EVENT) {
                this.logger.info('station associated. fetching station', {
                    stationId: event.eventBody.associatedStation.id
                });
                const associatedStation = event.eventBody.associatedStation;
                this._personDetails.station = {
                    effectiveStation: associatedStation,
                    associatedStation: associatedStation
                };
                // we emit the effectiveStation station after it is loaded
                return this.fetchUsersStation();
            }
            else if (event.metadata.action === 'WebRTCMigration') {
                this.logger.info('Received line appearance migration event, updating station', { activeConversationsForClient: this.sessionManager.getAllActiveConversations() });
                return this.fetchUsersStation();
            }
        });
    }
}
GenesysCloudWebrtcSdk.VERSION = '14.0.0';
export default GenesysCloudWebrtcSdk;
//# sourceMappingURL=client.js.map