/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

window.SpeechSDK = __webpack_require__(1);



/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(4);
// Common.Storage.SetLocalStorage(new Common.Browser.LocalStorage());
// Common.Storage.SetSessionStorage(new Common.Browser.SessionStorage());
Exports_2.Events.instance.attachListener(new Exports_1.ConsoleLoggingListener());
// Speech SDK API
__exportStar(__webpack_require__(61), exports);



/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(__webpack_require__(3), exports);
__exportStar(__webpack_require__(51), exports);
__exportStar(__webpack_require__(52), exports);
__exportStar(__webpack_require__(233), exports);
__exportStar(__webpack_require__(234), exports);
__exportStar(__webpack_require__(235), exports);
__exportStar(__webpack_require__(236), exports);
__exportStar(__webpack_require__(249), exports);
__exportStar(__webpack_require__(250), exports);
__exportStar(__webpack_require__(251), exports);
__exportStar(__webpack_require__(210), exports);



/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConsoleLoggingListener = void 0;
var Exports_1 = __webpack_require__(4);
var ConsoleLoggingListener = /** @class */ (function () {
    function ConsoleLoggingListener(logLevelFilter) {
        var _this = this;
        if (logLevelFilter === void 0) { logLevelFilter = Exports_1.EventType.Warning; }
        this.onEvent = function (event) {
            if (event.eventType >= _this.privLogLevelFilter) {
                var log = _this.toString(event);
                switch (event.eventType) {
                    case Exports_1.EventType.Debug:
                        // tslint:disable-next-line:no-console
                        console.debug(log);
                        break;
                    case Exports_1.EventType.Info:
                        // tslint:disable-next-line:no-console
                        console.info(log);
                        break;
                    case Exports_1.EventType.Warning:
                        // tslint:disable-next-line:no-console
                        console.warn(log);
                        break;
                    case Exports_1.EventType.Error:
                        // tslint:disable-next-line:no-console
                        console.error(log);
                        break;
                    default:
                        // tslint:disable-next-line:no-console
                        console.log(log);
                        break;
                }
            }
        };
        this.toString = function (event) {
            var logFragments = [
                "" + event.EventTime,
                "" + event.Name,
            ];
            for (var prop in event) {
                if (prop && event.hasOwnProperty(prop) &&
                    prop !== "eventTime" && prop !== "eventType" &&
                    prop !== "eventId" && prop !== "name" &&
                    prop !== "constructor") {
                    var value = event[prop];
                    var valueToLog = "<NULL>";
                    if (value !== undefined && value !== null) {
                        if (typeof (value) === "number" || typeof (value) === "string") {
                            valueToLog = value.toString();
                        }
                        else {
                            valueToLog = JSON.stringify(value);
                        }
                    }
                    logFragments.push(prop + ": " + valueToLog);
                }
            }
            return logFragments.join(" | ");
        };
        this.privLogLevelFilter = logLevelFilter;
    }
    return ConsoleLoggingListener;
}());
exports.ConsoleLoggingListener = ConsoleLoggingListener;



/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(__webpack_require__(5), exports);
__exportStar(__webpack_require__(23), exports);
__exportStar(__webpack_require__(24), exports);
__exportStar(__webpack_require__(26), exports);
__exportStar(__webpack_require__(27), exports);
__exportStar(__webpack_require__(25), exports);
__exportStar(__webpack_require__(28), exports);
__exportStar(__webpack_require__(29), exports);
__exportStar(__webpack_require__(7), exports);
__exportStar(__webpack_require__(30), exports);
__exportStar(__webpack_require__(31), exports);
__exportStar(__webpack_require__(32), exports);
__exportStar(__webpack_require__(33), exports);
__exportStar(__webpack_require__(34), exports);
__exportStar(__webpack_require__(35), exports);
__exportStar(__webpack_require__(36), exports);
__exportStar(__webpack_require__(37), exports);
__exportStar(__webpack_require__(38), exports);
__exportStar(__webpack_require__(39), exports);
__exportStar(__webpack_require__(6), exports);
__exportStar(__webpack_require__(40), exports);
__exportStar(__webpack_require__(41), exports);
__exportStar(__webpack_require__(42), exports);
__exportStar(__webpack_require__(43), exports);
__exportStar(__webpack_require__(44), exports);
var TranslationStatus_1 = __webpack_require__(45);
Object.defineProperty(exports, "TranslationStatus", { enumerable: true, get: function () { return TranslationStatus_1.TranslationStatus; } });
__exportStar(__webpack_require__(46), exports);
__exportStar(__webpack_require__(47), exports);
__exportStar(__webpack_require__(48), exports);
__exportStar(__webpack_require__(49), exports);
__exportStar(__webpack_require__(50), exports);



/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AudioStreamNodeErrorEvent = exports.AudioStreamNodeDetachedEvent = exports.AudioStreamNodeAttachedEvent = exports.AudioStreamNodeAttachingEvent = exports.AudioStreamNodeEvent = exports.AudioSourceErrorEvent = exports.AudioSourceOffEvent = exports.AudioSourceReadyEvent = exports.AudioSourceInitializingEvent = exports.AudioSourceEvent = void 0;
// tslint:disable:max-classes-per-file
var PlatformEvent_1 = __webpack_require__(6);
var AudioSourceEvent = /** @class */ (function (_super) {
    __extends(AudioSourceEvent, _super);
    function AudioSourceEvent(eventName, audioSourceId, eventType) {
        if (eventType === void 0) { eventType = PlatformEvent_1.EventType.Info; }
        var _this = _super.call(this, eventName, eventType) || this;
        _this.privAudioSourceId = audioSourceId;
        return _this;
    }
    Object.defineProperty(AudioSourceEvent.prototype, "audioSourceId", {
        get: function () {
            return this.privAudioSourceId;
        },
        enumerable: false,
        configurable: true
    });
    return AudioSourceEvent;
}(PlatformEvent_1.PlatformEvent));
exports.AudioSourceEvent = AudioSourceEvent;
var AudioSourceInitializingEvent = /** @class */ (function (_super) {
    __extends(AudioSourceInitializingEvent, _super);
    function AudioSourceInitializingEvent(audioSourceId) {
        return _super.call(this, "AudioSourceInitializingEvent", audioSourceId) || this;
    }
    return AudioSourceInitializingEvent;
}(AudioSourceEvent));
exports.AudioSourceInitializingEvent = AudioSourceInitializingEvent;
var AudioSourceReadyEvent = /** @class */ (function (_super) {
    __extends(AudioSourceReadyEvent, _super);
    function AudioSourceReadyEvent(audioSourceId) {
        return _super.call(this, "AudioSourceReadyEvent", audioSourceId) || this;
    }
    return AudioSourceReadyEvent;
}(AudioSourceEvent));
exports.AudioSourceReadyEvent = AudioSourceReadyEvent;
var AudioSourceOffEvent = /** @class */ (function (_super) {
    __extends(AudioSourceOffEvent, _super);
    function AudioSourceOffEvent(audioSourceId) {
        return _super.call(this, "AudioSourceOffEvent", audioSourceId) || this;
    }
    return AudioSourceOffEvent;
}(AudioSourceEvent));
exports.AudioSourceOffEvent = AudioSourceOffEvent;
var AudioSourceErrorEvent = /** @class */ (function (_super) {
    __extends(AudioSourceErrorEvent, _super);
    function AudioSourceErrorEvent(audioSourceId, error) {
        var _this = _super.call(this, "AudioSourceErrorEvent", audioSourceId, PlatformEvent_1.EventType.Error) || this;
        _this.privError = error;
        return _this;
    }
    Object.defineProperty(AudioSourceErrorEvent.prototype, "error", {
        get: function () {
            return this.privError;
        },
        enumerable: false,
        configurable: true
    });
    return AudioSourceErrorEvent;
}(AudioSourceEvent));
exports.AudioSourceErrorEvent = AudioSourceErrorEvent;
var AudioStreamNodeEvent = /** @class */ (function (_super) {
    __extends(AudioStreamNodeEvent, _super);
    function AudioStreamNodeEvent(eventName, audioSourceId, audioNodeId) {
        var _this = _super.call(this, eventName, audioSourceId) || this;
        _this.privAudioNodeId = audioNodeId;
        return _this;
    }
    Object.defineProperty(AudioStreamNodeEvent.prototype, "audioNodeId", {
        get: function () {
            return this.privAudioNodeId;
        },
        enumerable: false,
        configurable: true
    });
    return AudioStreamNodeEvent;
}(AudioSourceEvent));
exports.AudioStreamNodeEvent = AudioStreamNodeEvent;
var AudioStreamNodeAttachingEvent = /** @class */ (function (_super) {
    __extends(AudioStreamNodeAttachingEvent, _super);
    function AudioStreamNodeAttachingEvent(audioSourceId, audioNodeId) {
        return _super.call(this, "AudioStreamNodeAttachingEvent", audioSourceId, audioNodeId) || this;
    }
    return AudioStreamNodeAttachingEvent;
}(AudioStreamNodeEvent));
exports.AudioStreamNodeAttachingEvent = AudioStreamNodeAttachingEvent;
var AudioStreamNodeAttachedEvent = /** @class */ (function (_super) {
    __extends(AudioStreamNodeAttachedEvent, _super);
    function AudioStreamNodeAttachedEvent(audioSourceId, audioNodeId) {
        return _super.call(this, "AudioStreamNodeAttachedEvent", audioSourceId, audioNodeId) || this;
    }
    return AudioStreamNodeAttachedEvent;
}(AudioStreamNodeEvent));
exports.AudioStreamNodeAttachedEvent = AudioStreamNodeAttachedEvent;
var AudioStreamNodeDetachedEvent = /** @class */ (function (_super) {
    __extends(AudioStreamNodeDetachedEvent, _super);
    function AudioStreamNodeDetachedEvent(audioSourceId, audioNodeId) {
        return _super.call(this, "AudioStreamNodeDetachedEvent", audioSourceId, audioNodeId) || this;
    }
    return AudioStreamNodeDetachedEvent;
}(AudioStreamNodeEvent));
exports.AudioStreamNodeDetachedEvent = AudioStreamNodeDetachedEvent;
var AudioStreamNodeErrorEvent = /** @class */ (function (_super) {
    __extends(AudioStreamNodeErrorEvent, _super);
    function AudioStreamNodeErrorEvent(audioSourceId, audioNodeId, error) {
        var _this = _super.call(this, "AudioStreamNodeErrorEvent", audioSourceId, audioNodeId) || this;
        _this.privError = error;
        return _this;
    }
    Object.defineProperty(AudioStreamNodeErrorEvent.prototype, "error", {
        get: function () {
            return this.privError;
        },
        enumerable: false,
        configurable: true
    });
    return AudioStreamNodeErrorEvent;
}(AudioStreamNodeEvent));
exports.AudioStreamNodeErrorEvent = AudioStreamNodeErrorEvent;



/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlatformEvent = exports.EventType = void 0;
var Guid_1 = __webpack_require__(7);
var EventType;
(function (EventType) {
    EventType[EventType["Debug"] = 0] = "Debug";
    EventType[EventType["Info"] = 1] = "Info";
    EventType[EventType["Warning"] = 2] = "Warning";
    EventType[EventType["Error"] = 3] = "Error";
})(EventType = exports.EventType || (exports.EventType = {}));
var PlatformEvent = /** @class */ (function () {
    function PlatformEvent(eventName, eventType) {
        this.privName = eventName;
        this.privEventId = Guid_1.createNoDashGuid();
        this.privEventTime = new Date().toISOString();
        this.privEventType = eventType;
        this.privMetadata = {};
    }
    Object.defineProperty(PlatformEvent.prototype, "name", {
        get: function () {
            return this.privName;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PlatformEvent.prototype, "eventId", {
        get: function () {
            return this.privEventId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PlatformEvent.prototype, "eventTime", {
        get: function () {
            return this.privEventTime;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PlatformEvent.prototype, "eventType", {
        get: function () {
            return this.privEventType;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PlatformEvent.prototype, "metadata", {
        get: function () {
            return this.privMetadata;
        },
        enumerable: false,
        configurable: true
    });
    return PlatformEvent;
}());
exports.PlatformEvent = PlatformEvent;



/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNoDashGuid = exports.createGuid = void 0;
var uuid_1 = __webpack_require__(8);
var createGuid = function () {
    return uuid_1.v4();
};
exports.createGuid = createGuid;
var createNoDashGuid = function () {
    return createGuid().replace(new RegExp("-", "g"), "").toUpperCase();
};
exports.createNoDashGuid = createNoDashGuid;



/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _v1_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v1", function() { return _v1_js__WEBPACK_IMPORTED_MODULE_0__["default"]; });

/* harmony import */ var _v3_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v3", function() { return _v3_js__WEBPACK_IMPORTED_MODULE_1__["default"]; });

/* harmony import */ var _v4_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v4", function() { return _v4_js__WEBPACK_IMPORTED_MODULE_2__["default"]; });

/* harmony import */ var _v5_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(19);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "v5", function() { return _v5_js__WEBPACK_IMPORTED_MODULE_3__["default"]; });

/* harmony import */ var _nil_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(21);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NIL", function() { return _nil_js__WEBPACK_IMPORTED_MODULE_4__["default"]; });

/* harmony import */ var _version_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(22);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "version", function() { return _version_js__WEBPACK_IMPORTED_MODULE_5__["default"]; });

/* harmony import */ var _validate_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(12);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "validate", function() { return _validate_js__WEBPACK_IMPORTED_MODULE_6__["default"]; });

/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(11);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "stringify", function() { return _stringify_js__WEBPACK_IMPORTED_MODULE_7__["default"]; });

/* harmony import */ var _parse_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(16);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return _parse_js__WEBPACK_IMPORTED_MODULE_8__["default"]; });











/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _rng_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10);
/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11);

 // **`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 || new Array(16);
  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_js__WEBPACK_IMPORTED_MODULE_0__["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 : Date.now(); // 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 || Object(_stringify_js__WEBPACK_IMPORTED_MODULE_1__["default"])(b);
}

/* harmony default export */ __webpack_exports__["default"] = (v1);

/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return 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()).
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
  // lazy load so that environments that need to polyfill have a chance to do so
  if (!getRandomValues) {
    // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
    // find the complete implementation of crypto (msCrypto) on IE11.
    getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);

    if (!getRandomValues) {
      throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
    }
  }

  return getRandomValues(rnds8);
}

/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _validate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12);

/**
 * 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.push((i + 0x100).toString(16).substr(1));
}

function stringify(arr) {
  var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  // Note: Be careful editing this code!  It's been tuned for performance
  // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
  var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID.  If this throws, it's likely due to one
  // of the following:
  // - One or more input array values don't map to a hex octet (leading to
  // "undefined" in the uuid)
  // - Invalid input values for the RFC `version` or `variant` fields

  if (!Object(_validate_js__WEBPACK_IMPORTED_MODULE_0__["default"])(uuid)) {
    throw TypeError('Stringified UUID is invalid');
  }

  return uuid;
}

/* harmony default export */ __webpack_exports__["default"] = (stringify);

/***/ }),
/* 12 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _regex_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(13);


function validate(uuid) {
  return typeof uuid === 'string' && _regex_js__WEBPACK_IMPORTED_MODULE_0__["default"].test(uuid);
}

/* harmony default export */ __webpack_exports__["default"] = (validate);

/***/ }),
/* 13 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);

/***/ }),
/* 14 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _v35_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15);
/* harmony import */ var _md5_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);


var v3 = Object(_v35_js__WEBPACK_IMPORTED_MODULE_0__["default"])('v3', 0x30, _md5_js__WEBPACK_IMPORTED_MODULE_1__["default"]);
/* harmony default export */ __webpack_exports__["default"] = (v3);

/***/ }),
/* 15 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DNS", function() { return DNS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "URL", function() { return URL; });
/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11);
/* harmony import */ var _parse_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16);



function stringToBytes(str) {
  str = unescape(encodeURIComponent(str)); // UTF8 escape

  var bytes = [];

  for (var i = 0; i < str.length; ++i) {
    bytes.push(str.charCodeAt(i));
  }

  return bytes;
}

var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
/* harmony default export */ __webpack_exports__["default"] = (function (name, version, hashfunc) {
  function generateUUID(value, namespace, buf, offset) {
    if (typeof value === 'string') {
      value = stringToBytes(value);
    }

    if (typeof namespace === 'string') {
      namespace = Object(_parse_js__WEBPACK_IMPORTED_MODULE_1__["default"])(namespace);
    }

    if (namespace.length !== 16) {
      throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
    } // Compute hash of namespace and value, Per 4.3
    // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
    // hashfunc([...namespace, ... value])`


    var bytes = new Uint8Array(16 + value.length);
    bytes.set(namespace);
    bytes.set(value, namespace.length);
    bytes = hashfunc(bytes);
    bytes[6] = bytes[6] & 0x0f | version;
    bytes[8] = bytes[8] & 0x3f | 0x80;

    if (buf) {
      offset = offset || 0;

      for (var i = 0; i < 16; ++i) {
        buf[offset + i] = bytes[i];
      }

      return buf;
    }

    return Object(_stringify_js__WEBPACK_IMPORTED_MODULE_0__["default"])(bytes);
  } // Function#name is not settable on some platforms (#270)


  try {
    generateUUID.name = name; // eslint-disable-next-line no-empty
  } catch (err) {} // For CommonJS default export support


  generateUUID.DNS = DNS;
  generateUUID.URL = URL;
  return generateUUID;
});

/***/ }),
/* 16 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _validate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12);


function parse(uuid) {
  if (!Object(_validate_js__WEBPACK_IMPORTED_MODULE_0__["default"])(uuid)) {
    throw TypeError('Invalid UUID');
  }

  var v;
  var arr = new Uint8Array(16); // Parse ########-....-....-....-............

  arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  arr[1] = v >>> 16 & 0xff;
  arr[2] = v >>> 8 & 0xff;
  arr[3] = v & 0xff; // Parse ........-####-....-....-............

  arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  arr[5] = v & 0xff; // Parse ........-....-####-....-............

  arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  arr[7] = v & 0xff; // Parse ........-....-....-####-............

  arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  arr[9] = v & 0xff; // Parse ........-....-....-....-############
  // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)

  arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
  arr[11] = v / 0x100000000 & 0xff;
  arr[12] = v >>> 24 & 0xff;
  arr[13] = v >>> 16 & 0xff;
  arr[14] = v >>> 8 & 0xff;
  arr[15] = v & 0xff;
  return arr;
}

/* harmony default export */ __webpack_exports__["default"] = (parse);

/***/ }),
/* 17 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/*
 * 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 Uint8Array(msg.length);

    for (var i = 0; i < msg.length; ++i) {
      bytes[i] = msg.charCodeAt(i);
    }
  }

  return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
}
/*
 * Convert an array of little-endian words to an array of bytes
 */


function md5ToHexEncodedArray(input) {
  var output = [];
  var length32 = input.length * 32;
  var hexTab = '0123456789abcdef';

  for (var i = 0; i < length32; i += 8) {
    var x = input[i >> 5] >>> i % 32 & 0xff;
    var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
    output.push(hex);
  }

  return output;
}
/**
 * Calculate output length with padding and bit length
 */


function getOutputLength(inputLength8) {
  return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
}
/*
 * Calculate the MD5 of an array of little-endian words, and a bit length.
 */


function wordsToMd5(x, len) {
  /* append padding */
  x[len >> 5] |= 0x80 << len % 32;
  x[getOutputLength(len) - 1] = len;
  var a = 1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d = 271733878;

  for (var i = 0; i < x.length; i += 16) {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var 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 bytes to an array of little-endian words
 * Characters >255 have their high-byte silently ignored.
 */


function bytesToWords(input) {
  if (input.length === 0) {
    return [];
  }

  var length8 = input.length * 8;
  var output = new Uint32Array(getOutputLength(length8));

  for (var i = 0; i < length8; i += 8) {
    output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
  }

  return output;
}
/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */


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.
 */


function bitRotateLeft(num, cnt) {
  return num << cnt | 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);
}

/* harmony default export */ __webpack_exports__["default"] = (md5);

/***/ }),
/* 18 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _rng_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(10);
/* harmony import */ var _stringify_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11);



function v4(options, buf, offset) {
  options = options || {};
  var rnds = options.random || (options.rng || _rng_js__WEBPACK_IMPORTED_MODULE_0__["default"])(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`

  rnds[6] = rnds[6] & 0x0f | 0x40;
  rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided

  if (buf) {
    offset = offset || 0;

    for (var i = 0; i < 16; ++i) {
      buf[offset + i] = rnds[i];
    }

    return buf;
  }

  return Object(_stringify_js__WEBPACK_IMPORTED_MODULE_1__["default"])(rnds);
}

/* harmony default export */ __webpack_exports__["default"] = (v4);

/***/ }),
/* 19 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _v35_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15);
/* harmony import */ var _sha1_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20);


var v5 = Object(_v35_js__WEBPACK_IMPORTED_MODULE_0__["default"])('v5', 0x50, _sha1_js__WEBPACK_IMPORTED_MODULE_1__["default"]);
/* harmony default export */ __webpack_exports__["default"] = (v5);

/***/ }),
/* 20 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
// 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 << n | 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 = [];

    for (var i = 0; i < msg.length; ++i) {
      bytes.push(msg.charCodeAt(i));
    }
  } else if (!Array.isArray(bytes)) {
    // Convert Array-like to Array
    bytes = Array.prototype.slice.call(bytes);
  }

  bytes.push(0x80);
  var l = bytes.length / 4 + 2;
  var N = Math.ceil(l / 16);
  var M = new Array(N);

  for (var _i = 0; _i < N; ++_i) {
    var arr = new Uint32Array(16);

    for (var j = 0; j < 16; ++j) {
      arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
    }

    M[_i] = arr;
  }

  M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
  M[N - 1][14] = Math.floor(M[N - 1][14]);
  M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;

  for (var _i2 = 0; _i2 < N; ++_i2) {
    var W = new Uint32Array(80);

    for (var t = 0; t < 16; ++t) {
      W[t] = M[_i2][t];
    }

    for (var _t = 16; _t < 80; ++_t) {
      W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
    }

    var a = H[0];
    var b = H[1];
    var c = H[2];
    var d = H[3];
    var e = H[4];

    for (var _t2 = 0; _t2 < 80; ++_t2) {
      var s = Math.floor(_t2 / 20);
      var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 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];
}

/* harmony default export */ __webpack_exports__["default"] = (sha1);

/***/ }),
/* 21 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = ('00000000-0000-0000-0000-000000000000');

/***/ }),
/* 22 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _validate_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12);


function version(uuid) {
  if (!Object(_validate_js__WEBPACK_IMPORTED_MODULE_0__["default"])(uuid)) {
    throw TypeError('Invalid UUID');
  }

  return parseInt(uuid.substr(14, 1), 16);
}

/* harmony default export */ __webpack_exports__["default"] = (version);

/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionMessageSentEvent = exports.ConnectionMessageReceivedEvent = exports.ConnectionEstablishErrorEvent = exports.ConnectionErrorEvent = exports.ConnectionClosedEvent = exports.ConnectionEstablishedEvent = exports.ConnectionStartEvent = exports.ConnectionEvent = exports.ServiceEvent = void 0;
var PlatformEvent_1 = __webpack_require__(6);
var ServiceEvent = /** @class */ (function (_super) {
    __extends(ServiceEvent, _super);
    function ServiceEvent(eventName, jsonstring, eventType) {
        if (eventType === void 0) { eventType = PlatformEvent_1.EventType.Info; }
        var _this = _super.call(this, eventName, eventType) || this;
        _this.privJsonResult = jsonstring;
        return _this;
    }
    Object.defineProperty(ServiceEvent.prototype, "jsonString", {
        get: function () {
            return this.privJsonResult;
        },
        enumerable: false,
        configurable: true
    });
    return ServiceEvent;
}(PlatformEvent_1.PlatformEvent));
exports.ServiceEvent = ServiceEvent;
var ConnectionEvent = /** @class */ (function (_super) {
    __extends(ConnectionEvent, _super);
    function ConnectionEvent(eventName, connectionId, eventType) {
        if (eventType === void 0) { eventType = PlatformEvent_1.EventType.Info; }
        var _this = _super.call(this, eventName, eventType) || this;
        _this.privConnectionId = connectionId;
        return _this;
    }
    Object.defineProperty(ConnectionEvent.prototype, "connectionId", {
        get: function () {
            return this.privConnectionId;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectionEvent;
}(PlatformEvent_1.PlatformEvent));
exports.ConnectionEvent = ConnectionEvent;
var ConnectionStartEvent = /** @class */ (function (_super) {
    __extends(ConnectionStartEvent, _super);
    function ConnectionStartEvent(connectionId, uri, headers) {
        var _this = _super.call(this, "ConnectionStartEvent", connectionId) || this;
        _this.privUri = uri;
        _this.privHeaders = headers;
        return _this;
    }
    Object.defineProperty(ConnectionStartEvent.prototype, "uri", {
        get: function () {
            return this.privUri;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionStartEvent.prototype, "headers", {
        get: function () {
            return this.privHeaders;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectionStartEvent;
}(ConnectionEvent));
exports.ConnectionStartEvent = ConnectionStartEvent;
var ConnectionEstablishedEvent = /** @class */ (function (_super) {
    __extends(ConnectionEstablishedEvent, _super);
    function ConnectionEstablishedEvent(connectionId, metadata) {
        return _super.call(this, "ConnectionEstablishedEvent", connectionId) || this;
    }
    return ConnectionEstablishedEvent;
}(ConnectionEvent));
exports.ConnectionEstablishedEvent = ConnectionEstablishedEvent;
var ConnectionClosedEvent = /** @class */ (function (_super) {
    __extends(ConnectionClosedEvent, _super);
    function ConnectionClosedEvent(connectionId, statusCode, reason) {
        var _this = _super.call(this, "ConnectionClosedEvent", connectionId, PlatformEvent_1.EventType.Debug) || this;
        _this.privReason = reason;
        _this.privStatusCode = statusCode;
        return _this;
    }
    Object.defineProperty(ConnectionClosedEvent.prototype, "reason", {
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionClosedEvent.prototype, "statusCode", {
        get: function () {
            return this.privStatusCode;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectionClosedEvent;
}(ConnectionEvent));
exports.ConnectionClosedEvent = ConnectionClosedEvent;
var ConnectionErrorEvent = /** @class */ (function (_super) {
    __extends(ConnectionErrorEvent, _super);
    function ConnectionErrorEvent(connectionId, message, type) {
        var _this = _super.call(this, "ConnectionErrorEvent", connectionId, PlatformEvent_1.EventType.Debug) || this;
        _this.privMessage = message;
        _this.privType = type;
        return _this;
    }
    Object.defineProperty(ConnectionErrorEvent.prototype, "message", {
        get: function () {
            return this.privMessage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionErrorEvent.prototype, "type", {
        get: function () {
            return this.privType;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectionErrorEvent;
}(ConnectionEvent));
exports.ConnectionErrorEvent = ConnectionErrorEvent;
var ConnectionEstablishErrorEvent = /** @class */ (function (_super) {
    __extends(ConnectionEstablishErrorEvent, _super);
    function ConnectionEstablishErrorEvent(connectionId, statuscode, reason) {
        var _this = _super.call(this, "ConnectionEstablishErrorEvent", connectionId, PlatformEvent_1.EventType.Error) || this;
        _this.privStatusCode = statuscode;
        _this.privReason = reason;
        return _this;
    }
    Object.defineProperty(ConnectionEstablishErrorEvent.prototype, "reason", {
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionEstablishErrorEvent.prototype, "statusCode", {
        get: function () {
            return this.privStatusCode;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectionEstablishErrorEvent;
}(ConnectionEvent));
exports.ConnectionEstablishErrorEvent = ConnectionEstablishErrorEvent;
var ConnectionMessageReceivedEvent = /** @class */ (function (_super) {
    __extends(ConnectionMessageReceivedEvent, _super);
    function ConnectionMessageReceivedEvent(connectionId, networkReceivedTimeISO, message) {
        var _this = _super.call(this, "ConnectionMessageReceivedEvent", connectionId) || this;
        _this.privNetworkReceivedTime = networkReceivedTimeISO;
        _this.privMessage = message;
        return _this;
    }
    Object.defineProperty(ConnectionMessageReceivedEvent.prototype, "networkReceivedTime", {
        get: function () {
            return this.privNetworkReceivedTime;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessageReceivedEvent.prototype, "message", {
        get: function () {
            return this.privMessage;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectionMessageReceivedEvent;
}(ConnectionEvent));
exports.ConnectionMessageReceivedEvent = ConnectionMessageReceivedEvent;
var ConnectionMessageSentEvent = /** @class */ (function (_super) {
    __extends(ConnectionMessageSentEvent, _super);
    function ConnectionMessageSentEvent(connectionId, networkSentTimeISO, message) {
        var _this = _super.call(this, "ConnectionMessageSentEvent", connectionId) || this;
        _this.privNetworkSentTime = networkSentTimeISO;
        _this.privMessage = message;
        return _this;
    }
    Object.defineProperty(ConnectionMessageSentEvent.prototype, "networkSentTime", {
        get: function () {
            return this.privNetworkSentTime;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessageSentEvent.prototype, "message", {
        get: function () {
            return this.privMessage;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectionMessageSentEvent;
}(ConnectionEvent));
exports.ConnectionMessageSentEvent = ConnectionMessageSentEvent;



/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionMessage = exports.MessageType = void 0;
var Error_1 = __webpack_require__(25);
var Guid_1 = __webpack_require__(7);
var MessageType;
(function (MessageType) {
    MessageType[MessageType["Text"] = 0] = "Text";
    MessageType[MessageType["Binary"] = 1] = "Binary";
})(MessageType = exports.MessageType || (exports.MessageType = {}));
var ConnectionMessage = /** @class */ (function () {
    function ConnectionMessage(messageType, body, headers, id) {
        this.privBody = null;
        if (messageType === MessageType.Text && body && !(typeof (body) === "string")) {
            throw new Error_1.InvalidOperationError("Payload must be a string");
        }
        if (messageType === MessageType.Binary && body && !(body instanceof ArrayBuffer)) {
            throw new Error_1.InvalidOperationError("Payload must be ArrayBuffer");
        }
        this.privMessageType = messageType;
        this.privBody = body;
        this.privHeaders = headers ? headers : {};
        this.privId = id ? id : Guid_1.createNoDashGuid();
        switch (this.messageType) {
            case MessageType.Binary:
                this.privSize = this.binaryBody !== null ? this.binaryBody.byteLength : 0;
                break;
            case MessageType.Text:
                this.privSize = this.textBody.length;
        }
    }
    Object.defineProperty(ConnectionMessage.prototype, "messageType", {
        get: function () {
            return this.privMessageType;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessage.prototype, "headers", {
        get: function () {
            return this.privHeaders;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessage.prototype, "body", {
        get: function () {
            return this.privBody;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessage.prototype, "textBody", {
        get: function () {
            if (this.privMessageType === MessageType.Binary) {
                throw new Error_1.InvalidOperationError("Not supported for binary message");
            }
            return this.privBody;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessage.prototype, "binaryBody", {
        get: function () {
            if (this.privMessageType === MessageType.Text) {
                throw new Error_1.InvalidOperationError("Not supported for text message");
            }
            return this.privBody;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessage.prototype, "id", {
        get: function () {
            return this.privId;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectionMessage;
}());
exports.ConnectionMessage = ConnectionMessage;



/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjectDisposedError = exports.InvalidOperationError = exports.ArgumentNullError = void 0;
// tslint:disable:max-classes-per-file
/**
 * The error that is thrown when an argument passed in is null.
 *
 * @export
 * @class ArgumentNullError
 * @extends {Error}
 */
var ArgumentNullError = /** @class */ (function (_super) {
    __extends(ArgumentNullError, _super);
    /**
     * Creates an instance of ArgumentNullError.
     *
     * @param {string} argumentName - Name of the argument that is null
     *
     * @memberOf ArgumentNullError
     */
    function ArgumentNullError(argumentName) {
        var _this = _super.call(this, argumentName) || this;
        _this.name = "ArgumentNull";
        _this.message = argumentName;
        return _this;
    }
    return ArgumentNullError;
}(Error));
exports.ArgumentNullError = ArgumentNullError;
/**
 * The error that is thrown when an invalid operation is performed in the code.
 *
 * @export
 * @class InvalidOperationError
 * @extends {Error}
 */
var InvalidOperationError = /** @class */ (function (_super) {
    __extends(InvalidOperationError, _super);
    /**
     * Creates an instance of InvalidOperationError.
     *
     * @param {string} error - The error
     *
     * @memberOf InvalidOperationError
     */
    function InvalidOperationError(error) {
        var _this = _super.call(this, error) || this;
        _this.name = "InvalidOperation";
        _this.message = error;
        return _this;
    }
    return InvalidOperationError;
}(Error));
exports.InvalidOperationError = InvalidOperationError;
/**
 * The error that is thrown when an object is disposed.
 *
 * @export
 * @class ObjectDisposedError
 * @extends {Error}
 */
// tslint:disable-next-line:max-classes-per-file
var ObjectDisposedError = /** @class */ (function (_super) {
    __extends(ObjectDisposedError, _super);
    /**
     * Creates an instance of ObjectDisposedError.
     *
     * @param {string} objectName - The object that is disposed
     * @param {string} error - The error
     *
     * @memberOf ObjectDisposedError
     */
    function ObjectDisposedError(objectName, error) {
        var _this = _super.call(this, error) || this;
        _this.name = objectName + "ObjectDisposed";
        _this.message = error;
        return _this;
    }
    return ObjectDisposedError;
}(Error));
exports.ObjectDisposedError = ObjectDisposedError;



/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionOpenResponse = void 0;
var ConnectionOpenResponse = /** @class */ (function () {
    function ConnectionOpenResponse(statusCode, reason) {
        this.privStatusCode = statusCode;
        this.privReason = reason;
    }
    Object.defineProperty(ConnectionOpenResponse.prototype, "statusCode", {
        get: function () {
            return this.privStatusCode;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionOpenResponse.prototype, "reason", {
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectionOpenResponse;
}());
exports.ConnectionOpenResponse = ConnectionOpenResponse;



/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SendingAgentContextMessageEvent = exports.DialogEvent = void 0;
var PlatformEvent_1 = __webpack_require__(6);
var DialogEvent = /** @class */ (function (_super) {
    __extends(DialogEvent, _super);
    function DialogEvent(eventName, eventType) {
        if (eventType === void 0) { eventType = PlatformEvent_1.EventType.Info; }
        return _super.call(this, eventName, eventType) || this;
    }
    return DialogEvent;
}(PlatformEvent_1.PlatformEvent));
exports.DialogEvent = DialogEvent;
var SendingAgentContextMessageEvent = /** @class */ (function (_super) {
    __extends(SendingAgentContextMessageEvent, _super);
    function SendingAgentContextMessageEvent(agentConfig) {
        var _this = _super.call(this, "SendingAgentContextMessageEvent") || this;
        _this.privAgentConfig = agentConfig;
        return _this;
    }
    Object.defineProperty(SendingAgentContextMessageEvent.prototype, "agentConfig", {
        get: function () {
            return this.privAgentConfig;
        },
        enumerable: false,
        configurable: true
    });
    return SendingAgentContextMessageEvent;
}(DialogEvent));
exports.SendingAgentContextMessageEvent = SendingAgentContextMessageEvent;



/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Events = void 0;
var Error_1 = __webpack_require__(25);
var EventSource_1 = __webpack_require__(29);
var Events = /** @class */ (function () {
    function Events() {
    }
    Object.defineProperty(Events, "instance", {
        get: function () {
            return Events.privInstance;
        },
        enumerable: false,
        configurable: true
    });
    Events.privInstance = new EventSource_1.EventSource();
    Events.setEventSource = function (eventSource) {
        if (!eventSource) {
            throw new Error_1.ArgumentNullError("eventSource");
        }
        Events.privInstance = eventSource;
    };
    return Events;
}());
exports.Events = Events;



/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventSource = void 0;
var Error_1 = __webpack_require__(25);
var Guid_1 = __webpack_require__(7);
var EventSource = /** @class */ (function () {
    function EventSource(metadata) {
        var _this = this;
        this.privEventListeners = {};
        this.privIsDisposed = false;
        this.onEvent = function (event) {
            if (_this.isDisposed()) {
                throw (new Error_1.ObjectDisposedError("EventSource"));
            }
            if (_this.metadata) {
                for (var paramName in _this.metadata) {
                    if (paramName) {
                        if (event.metadata) {
                            if (!event.metadata[paramName]) {
                                event.metadata[paramName] = _this.metadata[paramName];
                            }
                        }
                    }
                }
            }
            for (var eventId in _this.privEventListeners) {
                if (eventId && _this.privEventListeners[eventId]) {
                    _this.privEventListeners[eventId](event);
                }
            }
        };
        this.attach = function (onEventCallback) {
            var id = Guid_1.createNoDashGuid();
            _this.privEventListeners[id] = onEventCallback;
            return {
                detach: function () {
                    delete _this.privEventListeners[id];
                    return Promise.resolve();
                },
            };
        };
        this.attachListener = function (listener) {
            return _this.attach(listener.onEvent);
        };
        this.isDisposed = function () {
            return _this.privIsDisposed;
        };
        this.dispose = function () {
            _this.privEventListeners = null;
            _this.privIsDisposed = true;
        };
        this.privMetadata = metadata;
    }
    Object.defineProperty(EventSource.prototype, "metadata", {
        get: function () {
            return this.privMetadata;
        },
        enumerable: false,
        configurable: true
    });
    return EventSource;
}());
exports.EventSource = EventSource;



/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionState = void 0;
var ConnectionState;
(function (ConnectionState) {
    ConnectionState[ConnectionState["None"] = 0] = "None";
    ConnectionState[ConnectionState["Connected"] = 1] = "Connected";
    ConnectionState[ConnectionState["Connecting"] = 2] = "Connecting";
    ConnectionState[ConnectionState["Disconnected"] = 3] = "Disconnected";
})(ConnectionState = exports.ConnectionState || (exports.ConnectionState = {}));



/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.List = void 0;
var Error_1 = __webpack_require__(25);
var List = /** @class */ (function () {
    function List(list) {
        var _this = this;
        this.privSubscriptionIdCounter = 0;
        this.privAddSubscriptions = {};
        this.privRemoveSubscriptions = {};
        this.privDisposedSubscriptions = {};
        this.privDisposeReason = null;
        this.get = function (itemIndex) {
            _this.throwIfDisposed();
            return _this.privList[itemIndex];
        };
        this.first = function () {
            return _this.get(0);
        };
        this.last = function () {
            return _this.get(_this.length() - 1);
        };
        this.add = function (item) {
            _this.throwIfDisposed();
            _this.insertAt(_this.privList.length, item);
        };
        this.insertAt = function (index, item) {
            _this.throwIfDisposed();
            if (index === 0) {
                _this.privList.unshift(item);
            }
            else if (index === _this.privList.length) {
                _this.privList.push(item);
            }
            else {
                _this.privList.splice(index, 0, item);
            }
            _this.triggerSubscriptions(_this.privAddSubscriptions);
        };
        this.removeFirst = function () {
            _this.throwIfDisposed();
            return _this.removeAt(0);
        };
        this.removeLast = function () {
            _this.throwIfDisposed();
            return _this.removeAt(_this.length() - 1);
        };
        this.removeAt = function (index) {
            _this.throwIfDisposed();
            return _this.remove(index, 1)[0];
        };
        this.remove = function (index, count) {
            _this.throwIfDisposed();
            var removedElements = _this.privList.splice(index, count);
            _this.triggerSubscriptions(_this.privRemoveSubscriptions);
            return removedElements;
        };
        this.clear = function () {
            _this.throwIfDisposed();
            _this.remove(0, _this.length());
        };
        this.length = function () {
            _this.throwIfDisposed();
            return _this.privList.length;
        };
        this.onAdded = function (addedCallback) {
            _this.throwIfDisposed();
            var subscriptionId = _this.privSubscriptionIdCounter++;
            _this.privAddSubscriptions[subscriptionId] = addedCallback;
            return {
                detach: function () {
                    delete _this.privAddSubscriptions[subscriptionId];
                    return Promise.resolve();
                },
            };
        };
        this.onRemoved = function (removedCallback) {
            _this.throwIfDisposed();
            var subscriptionId = _this.privSubscriptionIdCounter++;
            _this.privRemoveSubscriptions[subscriptionId] = removedCallback;
            return {
                detach: function () {
                    delete _this.privRemoveSubscriptions[subscriptionId];
                    return Promise.resolve();
                },
            };
        };
        this.onDisposed = function (disposedCallback) {
            _this.throwIfDisposed();
            var subscriptionId = _this.privSubscriptionIdCounter++;
            _this.privDisposedSubscriptions[subscriptionId] = disposedCallback;
            return {
                detach: function () {
                    delete _this.privDisposedSubscriptions[subscriptionId];
                    return Promise.resolve();
                },
            };
        };
        this.join = function (seperator) {
            _this.throwIfDisposed();
            return _this.privList.join(seperator);
        };
        this.toArray = function () {
            var cloneCopy = Array();
            _this.privList.forEach(function (val) {
                cloneCopy.push(val);
            });
            return cloneCopy;
        };
        this.any = function (callback) {
            _this.throwIfDisposed();
            if (callback) {
                return _this.where(callback).length() > 0;
            }
            else {
                return _this.length() > 0;
            }
        };
        this.all = function (callback) {
            _this.throwIfDisposed();
            return _this.where(callback).length() === _this.length();
        };
        this.forEach = function (callback) {
            _this.throwIfDisposed();
            for (var i = 0; i < _this.length(); i++) {
                callback(_this.privList[i], i);
            }
        };
        this.select = function (callback) {
            _this.throwIfDisposed();
            var selectList = [];
            for (var i = 0; i < _this.privList.length; i++) {
                selectList.push(callback(_this.privList[i], i));
            }
            return new List(selectList);
        };
        this.where = function (callback) {
            _this.throwIfDisposed();
            var filteredList = new List();
            for (var i = 0; i < _this.privList.length; i++) {
                if (callback(_this.privList[i], i)) {
                    filteredList.add(_this.privList[i]);
                }
            }
            return filteredList;
        };
        this.orderBy = function (compareFn) {
            _this.throwIfDisposed();
            var clonedArray = _this.toArray();
            var orderedArray = clonedArray.sort(compareFn);
            return new List(orderedArray);
        };
        this.orderByDesc = function (compareFn) {
            _this.throwIfDisposed();
            return _this.orderBy(function (a, b) { return compareFn(b, a); });
        };
        this.clone = function () {
            _this.throwIfDisposed();
            return new List(_this.toArray());
        };
        this.concat = function (list) {
            _this.throwIfDisposed();
            return new List(_this.privList.concat(list.toArray()));
        };
        this.concatArray = function (array) {
            _this.throwIfDisposed();
            return new List(_this.privList.concat(array));
        };
        this.isDisposed = function () {
            return _this.privList == null;
        };
        this.dispose = function (reason) {
            if (!_this.isDisposed()) {
                _this.privDisposeReason = reason;
                _this.privList = null;
                _this.privAddSubscriptions = null;
                _this.privRemoveSubscriptions = null;
                _this.triggerSubscriptions(_this.privDisposedSubscriptions);
            }
        };
        this.throwIfDisposed = function () {
            if (_this.isDisposed()) {
                throw new Error_1.ObjectDisposedError("List", _this.privDisposeReason);
            }
        };
        this.triggerSubscriptions = function (subscriptions) {
            if (subscriptions) {
                for (var subscriptionId in subscriptions) {
                    if (subscriptionId) {
                        subscriptions[subscriptionId]();
                    }
                }
            }
        };
        this.privList = [];
        // copy the list rather than taking as is.
        if (list) {
            for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
                var item = list_1[_i];
                this.privList.push(item);
            }
        }
    }
    return List;
}());
exports.List = List;



/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.marshalPromiseToCallbacks = exports.Sink = exports.Deferred = exports.PromiseResultEventSource = exports.PromiseResult = exports.PromiseState = void 0;
var PromiseState;
(function (PromiseState) {
    PromiseState[PromiseState["None"] = 0] = "None";
    PromiseState[PromiseState["Resolved"] = 1] = "Resolved";
    PromiseState[PromiseState["Rejected"] = 2] = "Rejected";
})(PromiseState = exports.PromiseState || (exports.PromiseState = {}));
var PromiseResult = /** @class */ (function () {
    function PromiseResult(promiseResultEventSource) {
        var _this = this;
        this.throwIfError = function () {
            if (_this.isError) {
                throw _this.error;
            }
        };
        promiseResultEventSource.on(function (result) {
            if (!_this.privIsCompleted) {
                _this.privIsCompleted = true;
                _this.privIsError = false;
                _this.privResult = result;
            }
        }, function (error) {
            if (!_this.privIsCompleted) {
                _this.privIsCompleted = true;
                _this.privIsError = true;
                _this.privError = error;
            }
        });
    }
    Object.defineProperty(PromiseResult.prototype, "isCompleted", {
        get: function () {
            return this.privIsCompleted;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PromiseResult.prototype, "isError", {
        get: function () {
            return this.privIsError;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PromiseResult.prototype, "error", {
        get: function () {
            return this.privError;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PromiseResult.prototype, "result", {
        get: function () {
            return this.privResult;
        },
        enumerable: false,
        configurable: true
    });
    return PromiseResult;
}());
exports.PromiseResult = PromiseResult;
var PromiseResultEventSource = /** @class */ (function () {
    function PromiseResultEventSource() {
        var _this = this;
        this.setResult = function (result) {
            _this.privOnSetResult(result);
        };
        this.setError = function (error) {
            _this.privOnSetError(error);
        };
        this.on = function (onSetResult, onSetError) {
            _this.privOnSetResult = onSetResult;
            _this.privOnSetError = onSetError;
        };
    }
    return PromiseResultEventSource;
}());
exports.PromiseResultEventSource = PromiseResultEventSource;
var Deferred = /** @class */ (function () {
    function Deferred() {
        var _this = this;
        this.resolve = function (result) {
            _this.privResolve(result);
            return _this;
        };
        this.reject = function (error) {
            _this.privReject(error);
            return _this;
        };
        this.privPromise = new Promise(function (resolve, reject) {
            _this.privResolve = resolve;
            _this.privReject = reject;
        });
    }
    Object.defineProperty(Deferred.prototype, "promise", {
        get: function () {
            return this.privPromise;
        },
        enumerable: false,
        configurable: true
    });
    return Deferred;
}());
exports.Deferred = Deferred;
var Sink = /** @class */ (function () {
    function Sink() {
        var _this = this;
        this.privState = PromiseState.None;
        this.privPromiseResult = null;
        this.privPromiseResultEvents = null;
        this.privSuccessHandlers = [];
        this.privErrorHandlers = [];
        this.resolve = function (result) {
            if (_this.privState !== PromiseState.None) {
                throw new Error("'Cannot resolve a completed promise'");
            }
            _this.privState = PromiseState.Resolved;
            _this.privPromiseResultEvents.setResult(result);
            for (var i = 0; i < _this.privSuccessHandlers.length; i++) {
                _this.executeSuccessCallback(result, _this.privSuccessHandlers[i], _this.privErrorHandlers[i]);
            }
            _this.detachHandlers();
        };
        this.reject = function (error) {
            if (_this.privState !== PromiseState.None) {
                throw new Error("'Cannot reject a completed promise'");
            }
            _this.privState = PromiseState.Rejected;
            _this.privPromiseResultEvents.setError(error);
            for (var _i = 0, _a = _this.privErrorHandlers; _i < _a.length; _i++) {
                var errorHandler = _a[_i];
                _this.executeErrorCallback(error, errorHandler);
            }
            _this.detachHandlers();
        };
        this.on = function (successCallback, errorCallback) {
            if (successCallback == null) {
                successCallback = function (r) { return; };
            }
            if (_this.privState === PromiseState.None) {
                _this.privSuccessHandlers.push(successCallback);
                _this.privErrorHandlers.push(errorCallback);
            }
            else {
                if (_this.privState === PromiseState.Resolved) {
                    _this.executeSuccessCallback(_this.privPromiseResult.result, successCallback, errorCallback);
                }
                else if (_this.privState === PromiseState.Rejected) {
                    _this.executeErrorCallback(_this.privPromiseResult.error, errorCallback);
                }
                _this.detachHandlers();
            }
        };
        this.executeSuccessCallback = function (result, successCallback, errorCallback) {
            try {
                successCallback(result);
            }
            catch (e) {
                _this.executeErrorCallback("'Unhandled callback error: " + e + "'", errorCallback);
            }
        };
        this.executeErrorCallback = function (error, errorCallback) {
            if (errorCallback) {
                try {
                    errorCallback(error);
                }
                catch (e) {
                    throw new Error("'Unhandled callback error: " + e + ". InnerError: " + error + "'");
                }
            }
            else {
                throw new Error("'Unhandled error: " + error + "'");
            }
        };
        this.detachHandlers = function () {
            _this.privErrorHandlers = [];
            _this.privSuccessHandlers = [];
        };
        this.privPromiseResultEvents = new PromiseResultEventSource();
        this.privPromiseResult = new PromiseResult(this.privPromiseResultEvents);
    }
    Object.defineProperty(Sink.prototype, "state", {
        get: function () {
            return this.privState;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Sink.prototype, "result", {
        get: function () {
            return this.privPromiseResult;
        },
        enumerable: false,
        configurable: true
    });
    return Sink;
}());
exports.Sink = Sink;
function marshalPromiseToCallbacks(promise, cb, err) {
    promise.then(function (val) {
        try {
            if (!!cb) {
                cb(val);
            }
        }
        catch (error) {
            if (!!err) {
                try {
                    if (error instanceof Error) {
                        var typedError = error;
                        err(typedError.name + ": " + typedError.message);
                    }
                    else {
                        err(error);
                    }
                    /* tslint:disable:no-empty */
                }
                catch (error) { }
            }
        }
    }, function (error) {
        if (!!err) {
            try {
                if (error instanceof Error) {
                    var typedError = error;
                    err(typedError.name + ": " + typedError.message);
                }
                else {
                    err(error);
                }
                /* tslint:disable:no-empty */
            }
            catch (error) { }
        }
    });
}
exports.marshalPromiseToCallbacks = marshalPromiseToCallbacks;



/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Queue = void 0;
var Error_1 = __webpack_require__(25);
var List_1 = __webpack_require__(39);
var Promise_1 = __webpack_require__(40);
var SubscriberType;
(function (SubscriberType) {
    SubscriberType[SubscriberType["Dequeue"] = 0] = "Dequeue";
    SubscriberType[SubscriberType["Peek"] = 1] = "Peek";
})(SubscriberType || (SubscriberType = {}));
var Queue = /** @class */ (function () {
    function Queue(list) {
        var _this = this;
        this.privPromiseStore = new List_1.List();
        this.privIsDrainInProgress = false;
        this.privIsDisposing = false;
        this.privDisposeReason = null;
        this.enqueue = function (item) {
            _this.throwIfDispose();
            _this.enqueueFromPromise(new Promise(function (resolve, reject) { resolve(item); }));
        };
        this.enqueueFromPromise = function (promise) {
            _this.throwIfDispose();
            promise.then(function (val) {
                _this.privList.add(val);
                /* tslint:disable:no-empty */
            }, function (error) { });
        };
        this.dequeue = function () {
            _this.throwIfDispose();
            var deferredSubscriber = new Promise_1.Deferred();
            if (_this.privSubscribers) {
                _this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Dequeue });
                _this.drain();
            }
            return deferredSubscriber.promise;
        };
        this.peek = function () {
            _this.throwIfDispose();
            var deferredSubscriber = new Promise_1.Deferred();
            var subs = _this.privSubscribers;
            if (subs) {
                _this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Peek });
                _this.drain();
            }
            return deferredSubscriber.promise;
        };
        this.length = function () {
            _this.throwIfDispose();
            return _this.privList.length();
        };
        this.isDisposed = function () {
            return _this.privSubscribers == null;
        };
        this.drain = function () {
            if (!_this.privIsDrainInProgress && !_this.privIsDisposing) {
                _this.privIsDrainInProgress = true;
                var subs = _this.privSubscribers;
                var lists = _this.privList;
                if (subs && lists) {
                    while (lists.length() > 0 && subs.length() > 0 && !_this.privIsDisposing) {
                        var subscriber = subs.removeFirst();
                        if (subscriber.type === SubscriberType.Peek) {
                            subscriber.deferral.resolve(lists.first());
                        }
                        else {
                            var dequeuedItem = lists.removeFirst();
                            subscriber.deferral.resolve(dequeuedItem);
                        }
                    }
                    // note: this block assumes cooperative multitasking, i.e.,
                    // between the if-statement and the assignment there are no
                    // thread switches.
                    // Reason is that between the initial const = this.; and this
                    // point there is the derral.resolve() operation that might have
                    // caused recursive calls to the Queue, especially, calling
                    // Dispose() on the queue alredy (which would reset the var
                    // here to null!).
                    // That should generally hold true for javascript...
                    if (_this.privSubscribers === subs) {
                        _this.privSubscribers = subs;
                    }
                    // note: this block assumes cooperative multitasking, i.e.,
                    // between the if-statement and the assignment there are no
                    // thread switches.
                    // Reason is that between the initial const = this.; and this
                    // point there is the derral.resolve() operation that might have
                    // caused recursive calls to the Queue, especially, calling
                    // Dispose() on the queue alredy (which would reset the var
                    // here to null!).
                    // That should generally hold true for javascript...
                    if (_this.privList === lists) {
                        _this.privList = lists;
                    }
                }
                _this.privIsDrainInProgress = false;
            }
        };
        this.throwIfDispose = function () {
            if (_this.isDisposed()) {
                if (_this.privDisposeReason) {
                    throw new Error_1.InvalidOperationError(_this.privDisposeReason);
                }
                throw new Error_1.ObjectDisposedError("Queue");
            }
            else if (_this.privIsDisposing) {
                throw new Error_1.InvalidOperationError("Queue disposing");
            }
        };
        this.privList = list ? list : new List_1.List();
        this.privDetachables = [];
        this.privSubscribers = new List_1.List();
        this.privDetachables.push(this.privList.onAdded(this.drain));
    }
    Queue.prototype.drainAndDispose = function (pendingItemProcessor, reason) {
        return __awaiter(this, void 0, void 0, function () {
            var subs, subscriber, _i, _a, detachable, promiseArray_1;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!(!this.isDisposed() && !this.privIsDisposing)) return [3 /*break*/, 5];
                        this.privDisposeReason = reason;
                        this.privIsDisposing = true;
                        subs = this.privSubscribers;
                        if (subs) {
                            while (subs.length() > 0) {
                                subscriber = subs.removeFirst();
                                // TODO: this needs work (Resolve(null) instead?).
                                subscriber.deferral.resolve(undefined);
                                // subscriber.deferral.reject("Disposed");
                            }
                            // note: this block assumes cooperative multitasking, i.e.,
                            // between the if-statement and the assignment there are no
                            // thread switches.
                            // Reason is that between the initial const = this.; and this
                            // point there is the derral.resolve() operation that might have
                            // caused recursive calls to the Queue, especially, calling
                            // Dispose() on the queue alredy (which would reset the var
                            // here to null!).
                            // That should generally hold true for javascript...
                            if (this.privSubscribers === subs) {
                                this.privSubscribers = subs;
                            }
                        }
                        _i = 0, _a = this.privDetachables;
                        _b.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3 /*break*/, 4];
                        detachable = _a[_i];
                        return [4 /*yield*/, detachable.detach()];
                    case 2:
                        _b.sent();
                        _b.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4:
                        if (this.privPromiseStore.length() > 0 && pendingItemProcessor) {
                            promiseArray_1 = [];
                            this.privPromiseStore.toArray().forEach(function (wrapper) {
                                promiseArray_1.push(wrapper);
                            });
                            return [2 /*return*/, Promise.all(promiseArray_1).finally(function () {
                                    _this.privSubscribers = null;
                                    _this.privList.forEach(function (item, index) {
                                        pendingItemProcessor(item);
                                    });
                                    _this.privList = null;
                                    return;
                                }).then()];
                        }
                        else {
                            this.privSubscribers = null;
                            this.privList = null;
                        }
                        _b.label = 5;
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    Queue.prototype.dispose = function (reason) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.drainAndDispose(null, reason)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return Queue;
}());
exports.Queue = Queue;



/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.RawWebsocketMessage = void 0;
var ConnectionMessage_1 = __webpack_require__(24);
var Error_1 = __webpack_require__(25);
var Guid_1 = __webpack_require__(7);
var RawWebsocketMessage = /** @class */ (function () {
    function RawWebsocketMessage(messageType, payload, id) {
        this.privPayload = null;
        if (!payload) {
            throw new Error_1.ArgumentNullError("payload");
        }
        if (messageType === ConnectionMessage_1.MessageType.Binary && payload.__proto__.constructor.name !== "ArrayBuffer") {
            throw new Error_1.InvalidOperationError("Payload must be ArrayBuffer");
        }
        if (messageType === ConnectionMessage_1.MessageType.Text && !(typeof (payload) === "string")) {
            throw new Error_1.InvalidOperationError("Payload must be a string");
        }
        this.privMessageType = messageType;
        this.privPayload = payload;
        this.privId = id ? id : Guid_1.createNoDashGuid();
    }
    Object.defineProperty(RawWebsocketMessage.prototype, "messageType", {
        get: function () {
            return this.privMessageType;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RawWebsocketMessage.prototype, "payload", {
        get: function () {
            return this.privPayload;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RawWebsocketMessage.prototype, "textContent", {
        get: function () {
            if (this.privMessageType === ConnectionMessage_1.MessageType.Binary) {
                throw new Error_1.InvalidOperationError("Not supported for binary message");
            }
            return this.privPayload;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RawWebsocketMessage.prototype, "binaryContent", {
        get: function () {
            if (this.privMessageType === ConnectionMessage_1.MessageType.Text) {
                throw new Error_1.InvalidOperationError("Not supported for text message");
            }
            return this.privPayload;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RawWebsocketMessage.prototype, "id", {
        get: function () {
            return this.privId;
        },
        enumerable: false,
        configurable: true
    });
    return RawWebsocketMessage;
}());
exports.RawWebsocketMessage = RawWebsocketMessage;



/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.RiffPcmEncoder = void 0;
var RiffPcmEncoder = /** @class */ (function () {
    function RiffPcmEncoder(actualSampleRate, desiredSampleRate) {
        var _this = this;
        this.encode = function (actualAudioFrame) {
            var audioFrame = _this.downSampleAudioFrame(actualAudioFrame, _this.privActualSampleRate, _this.privDesiredSampleRate);
            if (!audioFrame) {
                return null;
            }
            var audioLength = audioFrame.length * 2;
            var buffer = new ArrayBuffer(audioLength);
            var view = new DataView(buffer);
            _this.floatTo16BitPCM(view, 0, audioFrame);
            return buffer;
        };
        this.setString = function (view, offset, str) {
            for (var i = 0; i < str.length; i++) {
                view.setUint8(offset + i, str.charCodeAt(i));
            }
        };
        this.floatTo16BitPCM = function (view, offset, input) {
            for (var i = 0; i < input.length; i++, offset += 2) {
                var s = Math.max(-1, Math.min(1, input[i]));
                view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
            }
        };
        this.downSampleAudioFrame = function (srcFrame, srcRate, dstRate) {
            if (!srcFrame) {
                return null;
            }
            if (dstRate === srcRate || dstRate > srcRate) {
                return srcFrame;
            }
            var ratio = srcRate / dstRate;
            var dstLength = Math.round(srcFrame.length / ratio);
            var dstFrame = new Float32Array(dstLength);
            var srcOffset = 0;
            var dstOffset = 0;
            while (dstOffset < dstLength) {
                var nextSrcOffset = Math.round((dstOffset + 1) * ratio);
                var accum = 0;
                var count = 0;
                while (srcOffset < nextSrcOffset && srcOffset < srcFrame.length) {
                    accum += srcFrame[srcOffset++];
                    count++;
                }
                dstFrame[dstOffset++] = accum / count;
            }
            return dstFrame;
        };
        this.privActualSampleRate = actualSampleRate;
        this.privDesiredSampleRate = desiredSampleRate;
    }
    return RiffPcmEncoder;
}());
exports.RiffPcmEncoder = RiffPcmEncoder;



/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Stream = void 0;
var Error_1 = __webpack_require__(25);
var Guid_1 = __webpack_require__(7);
var Queue_1 = __webpack_require__(41);
var Stream = /** @class */ (function () {
    function Stream(streamId) {
        var _this = this;
        this.privIsWriteEnded = false;
        this.privIsReadEnded = false;
        this.read = function () {
            if (_this.privIsReadEnded) {
                throw new Error_1.InvalidOperationError("Stream read has already finished");
            }
            return _this.privReaderQueue
                .dequeue()
                .then(function (streamChunk) { return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(streamChunk === undefined || streamChunk.isEnd)) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.privReaderQueue.dispose("End of stream reached")];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2: return [2 /*return*/, streamChunk];
                    }
                });
            }); });
        };
        this.readEnded = function () {
            if (!_this.privIsReadEnded) {
                _this.privIsReadEnded = true;
                _this.privReaderQueue = new Queue_1.Queue();
            }
        };
        this.throwIfClosed = function () {
            if (_this.privIsWriteEnded) {
                throw new Error_1.InvalidOperationError("Stream closed");
            }
        };
        this.privId = streamId ? streamId : Guid_1.createNoDashGuid();
        this.privReaderQueue = new Queue_1.Queue();
    }
    Object.defineProperty(Stream.prototype, "isClosed", {
        get: function () {
            return this.privIsWriteEnded;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Stream.prototype, "isReadEnded", {
        get: function () {
            return this.privIsReadEnded;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Stream.prototype, "id", {
        get: function () {
            return this.privId;
        },
        enumerable: false,
        configurable: true
    });
    Stream.prototype.close = function () {
        if (!this.privIsWriteEnded) {
            this.writeStreamChunk({
                buffer: null,
                isEnd: true,
                timeReceived: Date.now(),
            });
            this.privIsWriteEnded = true;
        }
    };
    Stream.prototype.writeStreamChunk = function (streamChunk) {
        this.throwIfClosed();
        if (!this.privReaderQueue.isDisposed()) {
            try {
                this.privReaderQueue.enqueue(streamChunk);
            }
            catch (e) {
                // Do nothing
            }
        }
    };
    return Stream;
}());
exports.Stream = Stream;



/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationStatus = void 0;
/**
 * Defines translation status.
 * @class TranslationStatus
 */
var TranslationStatus;
(function (TranslationStatus) {
    /**
     * @member TranslationStatus.Success
     */
    TranslationStatus[TranslationStatus["Success"] = 0] = "Success";
    /**
     * @member TranslationStatus.Error
     */
    TranslationStatus[TranslationStatus["Error"] = 1] = "Error";
})(TranslationStatus = exports.TranslationStatus || (exports.TranslationStatus = {}));



/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChunkedArrayBufferStream = void 0;
var Exports_1 = __webpack_require__(4);
var ChunkedArrayBufferStream = /** @class */ (function (_super) {
    __extends(ChunkedArrayBufferStream, _super);
    function ChunkedArrayBufferStream(targetChunkSize, streamId) {
        var _this = _super.call(this, streamId) || this;
        _this.privTargetChunkSize = targetChunkSize;
        _this.privNextBufferReadyBytes = 0;
        return _this;
    }
    ChunkedArrayBufferStream.prototype.writeStreamChunk = function (chunk) {
        // No pending write, and the buffer is the right size so write it.
        if (chunk.isEnd ||
            (0 === this.privNextBufferReadyBytes && chunk.buffer.byteLength === this.privTargetChunkSize)) {
            _super.prototype.writeStreamChunk.call(this, chunk);
            return;
        }
        var bytesCopiedFromBuffer = 0;
        while (bytesCopiedFromBuffer < chunk.buffer.byteLength) {
            // Fill the next buffer.
            if (undefined === this.privNextBufferToWrite) {
                this.privNextBufferToWrite = new ArrayBuffer(this.privTargetChunkSize);
                this.privNextBufferStartTime = chunk.timeReceived;
            }
            // Find out how many bytes we can copy into the read buffer.
            var bytesToCopy = Math.min(chunk.buffer.byteLength - bytesCopiedFromBuffer, this.privTargetChunkSize - this.privNextBufferReadyBytes);
            var targetView = new Uint8Array(this.privNextBufferToWrite);
            var sourceView = new Uint8Array(chunk.buffer.slice(bytesCopiedFromBuffer, bytesToCopy + bytesCopiedFromBuffer));
            targetView.set(sourceView, this.privNextBufferReadyBytes);
            this.privNextBufferReadyBytes += bytesToCopy;
            bytesCopiedFromBuffer += bytesToCopy;
            // Are we ready to write?
            if (this.privNextBufferReadyBytes === this.privTargetChunkSize) {
                _super.prototype.writeStreamChunk.call(this, {
                    buffer: this.privNextBufferToWrite,
                    isEnd: false,
                    timeReceived: this.privNextBufferStartTime,
                });
                this.privNextBufferReadyBytes = 0;
                this.privNextBufferToWrite = undefined;
            }
        }
    };
    ChunkedArrayBufferStream.prototype.close = function () {
        // Send whatever is pending, then close the base class.
        if (0 !== this.privNextBufferReadyBytes && !this.isClosed) {
            _super.prototype.writeStreamChunk.call(this, {
                buffer: this.privNextBufferToWrite.slice(0, this.privNextBufferReadyBytes),
                isEnd: false,
                timeReceived: this.privNextBufferStartTime,
            });
        }
        _super.prototype.close.call(this);
    };
    return ChunkedArrayBufferStream;
}(Exports_1.Stream));
exports.ChunkedArrayBufferStream = ChunkedArrayBufferStream;



/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timeout = void 0;
var Timeout = /** @class */ (function () {
    function Timeout() {
    }
    Timeout.workerTimers = null;
    Timeout.clearTimeout = function (timerId) { return Timeout.timers().clearTimeout(timerId); };
    Timeout.setTimeout = function (func, delay) { return Timeout.timers().setTimeout(func, delay); };
    Timeout.load = function (url) {
        // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification.
        var scheduledTimeoutFunctions = new Map([[0, function () { }]]); // tslint:disable-line no-empty
        var unhandledRequests = new Map();
        var worker = new Worker(url);
        worker.addEventListener("message", function (_a) {
            var data = _a.data;
            if (Timeout.isCallNotification(data)) {
                var timerId = data.params.timerId;
                var idOrFunc = scheduledTimeoutFunctions.get(timerId);
                if (typeof idOrFunc === "number") {
                    var unhandledTimerId = unhandledRequests.get(idOrFunc);
                    if (unhandledTimerId === undefined ||
                        unhandledTimerId !== timerId) {
                        throw new Error("The timer is in an undefined state.");
                    }
                }
                else if (typeof idOrFunc !== "undefined") {
                    idOrFunc();
                    // A timeout can be safely deleted because it is only called once.
                    scheduledTimeoutFunctions.delete(timerId);
                }
                else {
                    throw new Error("The timer is in an undefined state.");
                }
            }
            else if (Timeout.isClearResponse(data)) {
                var id = data.id;
                var unhandledTimerId = unhandledRequests.get(id);
                if (unhandledTimerId === undefined) {
                    throw new Error("The timer is in an undefined state.");
                }
                unhandledRequests.delete(id);
                scheduledTimeoutFunctions.delete(unhandledTimerId);
            }
            else {
                var message = data.error.message;
                throw new Error(message);
            }
        });
        var clearTimeout = function (timerId) {
            var id = Math.random();
            unhandledRequests.set(id, timerId);
            scheduledTimeoutFunctions.set(timerId, id);
            worker.postMessage({
                id: id,
                method: "clear",
                params: { timerId: timerId }
            });
        };
        var setTimeout = function (func, delay) {
            var timerId = Math.random();
            scheduledTimeoutFunctions.set(timerId, func);
            worker.postMessage({
                id: null,
                method: "set",
                params: {
                    delay: delay,
                    now: performance.now(),
                    timerId: timerId
                }
            });
            return timerId;
        };
        return {
            clearTimeout: clearTimeout,
            setTimeout: setTimeout
        };
    };
    Timeout.loadWorkerTimers = function () {
        var worker = "!function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(e,\"__esModule\",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&\"object\"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,\"default\",{enumerable:!0,value:e}),2&t&&\"string\"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,\"a\",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=\"\",n(n.s=14)}([function(e,t,n){\"use strict\";n.d(t,\"a\",(function(){return i})),n.d(t,\"b\",(function(){return u})),n.d(t,\"c\",(function(){return a})),n.d(t,\"d\",(function(){return d}));const r=new Map,o=new Map,i=e=>{const t=r.get(e);if(void 0===t)throw new Error('There is no interval scheduled with the given id \"'.concat(e,'\".'));clearTimeout(t),r.delete(e)},u=e=>{const t=o.get(e);if(void 0===t)throw new Error('There is no timeout scheduled with the given id \"'.concat(e,'\".'));clearTimeout(t),o.delete(e)},f=(e,t)=>{let n,r;if(\"performance\"in self){const o=performance.now();n=o,r=e-Math.max(0,o-t)}else n=Date.now(),r=e;return{expected:n+r,remainingDelay:r}},c=(e,t,n,r)=>{const o=\"performance\"in self?performance.now():Date.now();o>n?postMessage({id:null,method:\"call\",params:{timerId:t}}):e.set(t,setTimeout(c,n-o,e,t,n))},a=(e,t,n)=>{const{expected:o,remainingDelay:i}=f(e,n);r.set(t,setTimeout(c,i,r,t,o))},d=(e,t,n)=>{const{expected:r,remainingDelay:i}=f(e,n);o.set(t,setTimeout(c,i,o,t,r))}},function(e,t,n){\"use strict\";n.r(t);var r=n(2);for(var o in r)\"default\"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(3);for(var o in i)\"default\"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(4);for(var o in u)\"default\"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o);var f=n(5);for(var o in f)\"default\"!==o&&function(e){n.d(t,e,(function(){return f[e]}))}(o);var c=n(6);for(var o in c)\"default\"!==o&&function(e){n.d(t,e,(function(){return c[e]}))}(o);var a=n(7);for(var o in a)\"default\"!==o&&function(e){n.d(t,e,(function(){return a[e]}))}(o);var d=n(8);for(var o in d)\"default\"!==o&&function(e){n.d(t,e,(function(){return d[e]}))}(o);var s=n(9);for(var o in s)\"default\"!==o&&function(e){n.d(t,e,(function(){return s[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){\"use strict\";n.r(t);var r=n(11);for(var o in r)\"default\"!==o&&function(e){n.d(t,e,(function(){return r[e]}))}(o);var i=n(12);for(var o in i)\"default\"!==o&&function(e){n.d(t,e,(function(){return i[e]}))}(o);var u=n(13);for(var o in u)\"default\"!==o&&function(e){n.d(t,e,(function(){return u[e]}))}(o)},function(e,t){},function(e,t){},function(e,t){},function(e,t,n){\"use strict\";n.r(t);var r=n(0),o=n(1);for(var i in o)\"default\"!==i&&function(e){n.d(t,e,(function(){return o[e]}))}(i);var u=n(10);for(var i in u)\"default\"!==i&&function(e){n.d(t,e,(function(){return u[e]}))}(i);addEventListener(\"message\",({data:e})=>{try{if(\"clear\"===e.method){const{id:t,params:{timerId:n}}=e;Object(r.b)(n),postMessage({error:null,id:t})}else{if(\"set\"!==e.method)throw new Error('The given method \"'.concat(e.method,'\" is not supported'));{const{params:{delay:t,now:n,timerId:o}}=e;Object(r.d)(t,o,n)}}}catch(t){postMessage({error:{message:t.message},id:e.id,result:null})}})}]);"; // tslint:disable-line:max-line-length
        return function () {
            if (Timeout.workerTimers !== null) {
                return Timeout.workerTimers;
            }
            var blob = new Blob([worker], { type: "application/javascript; charset=utf-8" });
            var url = URL.createObjectURL(blob);
            Timeout.workerTimers = Timeout.load(url);
            // Edge doesn't like the URL to be revoked directly.
            Timeout.workerTimers.setTimeout(function () { return URL.revokeObjectURL(url); }, 0);
            return Timeout.workerTimers;
        };
    };
    Timeout.timers = Timeout.loadWorkerTimers();
    Timeout.isCallNotification = function (message) {
        return message.method !== undefined && message.method === "call";
    };
    Timeout.isClearResponse = function (message) {
        return message.error === null && typeof message.id === "number";
    };
    return Timeout;
}());
exports.Timeout = Timeout;



/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.OCSPCacheUpdateErrorEvent = exports.OCSPResponseRetrievedEvent = exports.OCSPCacheFetchErrorEvent = exports.OCSPVerificationFailedEvent = exports.OCSPCacheHitEvent = exports.OCSPCacheEntryNeedsRefreshEvent = exports.OCSPCacheEntryExpiredEvent = exports.OCSPWSUpgradeStartedEvent = exports.OCSPStapleReceivedEvent = exports.OCSPCacheUpdateCompleteEvent = exports.OCSPDiskCacheStoreEvent = exports.OCSPMemoryCacheStoreEvent = exports.OCSPCacheUpdateNeededEvent = exports.OCSPDiskCacheHitEvent = exports.OCSPCacheMissEvent = exports.OCSPMemoryCacheHitEvent = exports.OCSPEvent = void 0;
// tslint:disable:max-classes-per-file
var PlatformEvent_1 = __webpack_require__(6);
var OCSPEvent = /** @class */ (function (_super) {
    __extends(OCSPEvent, _super);
    function OCSPEvent(eventName, eventType, signature) {
        var _this = _super.call(this, eventName, eventType) || this;
        _this.privSignature = signature;
        return _this;
    }
    return OCSPEvent;
}(PlatformEvent_1.PlatformEvent));
exports.OCSPEvent = OCSPEvent;
var OCSPMemoryCacheHitEvent = /** @class */ (function (_super) {
    __extends(OCSPMemoryCacheHitEvent, _super);
    function OCSPMemoryCacheHitEvent(signature) {
        return _super.call(this, "OCSPMemoryCacheHitEvent", PlatformEvent_1.EventType.Debug, signature) || this;
    }
    return OCSPMemoryCacheHitEvent;
}(OCSPEvent));
exports.OCSPMemoryCacheHitEvent = OCSPMemoryCacheHitEvent;
var OCSPCacheMissEvent = /** @class */ (function (_super) {
    __extends(OCSPCacheMissEvent, _super);
    function OCSPCacheMissEvent(signature) {
        return _super.call(this, "OCSPCacheMissEvent", PlatformEvent_1.EventType.Debug, signature) || this;
    }
    return OCSPCacheMissEvent;
}(OCSPEvent));
exports.OCSPCacheMissEvent = OCSPCacheMissEvent;
var OCSPDiskCacheHitEvent = /** @class */ (function (_super) {
    __extends(OCSPDiskCacheHitEvent, _super);
    function OCSPDiskCacheHitEvent(signature) {
        return _super.call(this, "OCSPDiskCacheHitEvent", PlatformEvent_1.EventType.Debug, signature) || this;
    }
    return OCSPDiskCacheHitEvent;
}(OCSPEvent));
exports.OCSPDiskCacheHitEvent = OCSPDiskCacheHitEvent;
var OCSPCacheUpdateNeededEvent = /** @class */ (function (_super) {
    __extends(OCSPCacheUpdateNeededEvent, _super);
    function OCSPCacheUpdateNeededEvent(signature) {
        return _super.call(this, "OCSPCacheUpdateNeededEvent", PlatformEvent_1.EventType.Debug, signature) || this;
    }
    return OCSPCacheUpdateNeededEvent;
}(OCSPEvent));
exports.OCSPCacheUpdateNeededEvent = OCSPCacheUpdateNeededEvent;
var OCSPMemoryCacheStoreEvent = /** @class */ (function (_super) {
    __extends(OCSPMemoryCacheStoreEvent, _super);
    function OCSPMemoryCacheStoreEvent(signature) {
        return _super.call(this, "OCSPMemoryCacheStoreEvent", PlatformEvent_1.EventType.Debug, signature) || this;
    }
    return OCSPMemoryCacheStoreEvent;
}(OCSPEvent));
exports.OCSPMemoryCacheStoreEvent = OCSPMemoryCacheStoreEvent;
var OCSPDiskCacheStoreEvent = /** @class */ (function (_super) {
    __extends(OCSPDiskCacheStoreEvent, _super);
    function OCSPDiskCacheStoreEvent(signature) {
        return _super.call(this, "OCSPDiskCacheStoreEvent", PlatformEvent_1.EventType.Debug, signature) || this;
    }
    return OCSPDiskCacheStoreEvent;
}(OCSPEvent));
exports.OCSPDiskCacheStoreEvent = OCSPDiskCacheStoreEvent;
var OCSPCacheUpdateCompleteEvent = /** @class */ (function (_super) {
    __extends(OCSPCacheUpdateCompleteEvent, _super);
    function OCSPCacheUpdateCompleteEvent(signature) {
        return _super.call(this, "OCSPCacheUpdateCompleteEvent", PlatformEvent_1.EventType.Debug, signature) || this;
    }
    return OCSPCacheUpdateCompleteEvent;
}(OCSPEvent));
exports.OCSPCacheUpdateCompleteEvent = OCSPCacheUpdateCompleteEvent;
var OCSPStapleReceivedEvent = /** @class */ (function (_super) {
    __extends(OCSPStapleReceivedEvent, _super);
    function OCSPStapleReceivedEvent() {
        return _super.call(this, "OCSPStapleReceivedEvent", PlatformEvent_1.EventType.Debug, "") || this;
    }
    return OCSPStapleReceivedEvent;
}(OCSPEvent));
exports.OCSPStapleReceivedEvent = OCSPStapleReceivedEvent;
var OCSPWSUpgradeStartedEvent = /** @class */ (function (_super) {
    __extends(OCSPWSUpgradeStartedEvent, _super);
    function OCSPWSUpgradeStartedEvent(serialNumber) {
        return _super.call(this, "OCSPWSUpgradeStartedEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this;
    }
    return OCSPWSUpgradeStartedEvent;
}(OCSPEvent));
exports.OCSPWSUpgradeStartedEvent = OCSPWSUpgradeStartedEvent;
var OCSPCacheEntryExpiredEvent = /** @class */ (function (_super) {
    __extends(OCSPCacheEntryExpiredEvent, _super);
    function OCSPCacheEntryExpiredEvent(serialNumber, expireTime) {
        var _this = _super.call(this, "OCSPCacheEntryExpiredEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this;
        _this.privExpireTime = expireTime;
        return _this;
    }
    return OCSPCacheEntryExpiredEvent;
}(OCSPEvent));
exports.OCSPCacheEntryExpiredEvent = OCSPCacheEntryExpiredEvent;
var OCSPCacheEntryNeedsRefreshEvent = /** @class */ (function (_super) {
    __extends(OCSPCacheEntryNeedsRefreshEvent, _super);
    function OCSPCacheEntryNeedsRefreshEvent(serialNumber, startTime, expireTime) {
        var _this = _super.call(this, "OCSPCacheEntryNeedsRefreshEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this;
        _this.privExpireTime = expireTime;
        _this.privStartTime = startTime;
        return _this;
    }
    return OCSPCacheEntryNeedsRefreshEvent;
}(OCSPEvent));
exports.OCSPCacheEntryNeedsRefreshEvent = OCSPCacheEntryNeedsRefreshEvent;
var OCSPCacheHitEvent = /** @class */ (function (_super) {
    __extends(OCSPCacheHitEvent, _super);
    function OCSPCacheHitEvent(serialNumber, startTime, expireTime) {
        var _this = _super.call(this, "OCSPCacheHitEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this;
        _this.privExpireTime = expireTime;
        _this.privExpireTimeString = new Date(expireTime).toLocaleDateString();
        _this.privStartTime = startTime;
        _this.privStartTimeString = new Date(startTime).toLocaleTimeString();
        return _this;
    }
    return OCSPCacheHitEvent;
}(OCSPEvent));
exports.OCSPCacheHitEvent = OCSPCacheHitEvent;
var OCSPVerificationFailedEvent = /** @class */ (function (_super) {
    __extends(OCSPVerificationFailedEvent, _super);
    function OCSPVerificationFailedEvent(serialNumber, error) {
        var _this = _super.call(this, "OCSPVerificationFailedEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this;
        _this.privError = error;
        return _this;
    }
    return OCSPVerificationFailedEvent;
}(OCSPEvent));
exports.OCSPVerificationFailedEvent = OCSPVerificationFailedEvent;
var OCSPCacheFetchErrorEvent = /** @class */ (function (_super) {
    __extends(OCSPCacheFetchErrorEvent, _super);
    function OCSPCacheFetchErrorEvent(serialNumber, error) {
        var _this = _super.call(this, "OCSPCacheFetchErrorEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this;
        _this.privError = error;
        return _this;
    }
    return OCSPCacheFetchErrorEvent;
}(OCSPEvent));
exports.OCSPCacheFetchErrorEvent = OCSPCacheFetchErrorEvent;
var OCSPResponseRetrievedEvent = /** @class */ (function (_super) {
    __extends(OCSPResponseRetrievedEvent, _super);
    function OCSPResponseRetrievedEvent(serialNumber) {
        return _super.call(this, "OCSPResponseRetrievedEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this;
    }
    return OCSPResponseRetrievedEvent;
}(OCSPEvent));
exports.OCSPResponseRetrievedEvent = OCSPResponseRetrievedEvent;
var OCSPCacheUpdateErrorEvent = /** @class */ (function (_super) {
    __extends(OCSPCacheUpdateErrorEvent, _super);
    function OCSPCacheUpdateErrorEvent(serialNumber, error) {
        var _this = _super.call(this, "OCSPCacheUpdateErrorEvent", PlatformEvent_1.EventType.Debug, serialNumber) || this;
        _this.privError = error;
        return _this;
    }
    return OCSPCacheUpdateErrorEvent;
}(OCSPEvent));
exports.OCSPCacheUpdateErrorEvent = OCSPCacheUpdateErrorEvent;



/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BackgroundEvent = void 0;
var Exports_1 = __webpack_require__(4);
var BackgroundEvent = /** @class */ (function (_super) {
    __extends(BackgroundEvent, _super);
    function BackgroundEvent(error) {
        var _this = _super.call(this, "BackgroundEvent", Exports_1.EventType.Error) || this;
        _this.privError = error;
        return _this;
    }
    Object.defineProperty(BackgroundEvent.prototype, "error", {
        get: function () {
            return this.privError;
        },
        enumerable: false,
        configurable: true
    });
    return BackgroundEvent;
}(Exports_1.PlatformEvent));
exports.BackgroundEvent = BackgroundEvent;



/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MicAudioSource = exports.AudioWorkletSourceURLPropertyName = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var AudioStreamFormat_1 = __webpack_require__(72);
exports.AudioWorkletSourceURLPropertyName = "MICROPHONE-WorkletSourceUrl";
var MicAudioSource = /** @class */ (function () {
    function MicAudioSource(privRecorder, deviceId, audioSourceId, mediaStream) {
        var _this = this;
        this.privRecorder = privRecorder;
        this.deviceId = deviceId;
        this.privStreams = {};
        this.turnOn = function () {
            if (_this.privInitializeDeferral) {
                return _this.privInitializeDeferral.promise;
            }
            _this.privInitializeDeferral = new Exports_2.Deferred();
            try {
                _this.createAudioContext();
            }
            catch (error) {
                if (error instanceof Error) {
                    var typedError = error;
                    _this.privInitializeDeferral.reject(typedError.name + ": " + typedError.message);
                }
                else {
                    _this.privInitializeDeferral.reject(error);
                }
                return _this.privInitializeDeferral.promise;
            }
            var nav = window.navigator;
            var getUserMedia = (nav.getUserMedia ||
                nav.webkitGetUserMedia ||
                nav.mozGetUserMedia ||
                nav.msGetUserMedia);
            if (!!nav.mediaDevices) {
                getUserMedia = function (constraints, successCallback, errorCallback) {
                    nav.mediaDevices
                        .getUserMedia(constraints)
                        .then(successCallback)
                        .catch(errorCallback);
                };
            }
            if (!getUserMedia) {
                var errorMsg = "Browser does not support getUserMedia.";
                _this.privInitializeDeferral.reject(errorMsg);
                _this.onEvent(new Exports_2.AudioSourceErrorEvent(errorMsg, "")); // mic initialized error - no streamid at this point
            }
            else {
                var next = function () {
                    _this.onEvent(new Exports_2.AudioSourceInitializingEvent(_this.privId)); // no stream id
                    if (_this.privMediaStream && _this.privMediaStream.active) {
                        _this.onEvent(new Exports_2.AudioSourceReadyEvent(_this.privId));
                        _this.privInitializeDeferral.resolve();
                    }
                    else {
                        getUserMedia({ audio: _this.deviceId ? { deviceId: _this.deviceId } : true, video: false }, function (mediaStream) {
                            _this.privMediaStream = mediaStream;
                            _this.onEvent(new Exports_2.AudioSourceReadyEvent(_this.privId));
                            _this.privInitializeDeferral.resolve();
                        }, function (error) {
                            var errorMsg = "Error occurred during microphone initialization: " + error;
                            _this.privInitializeDeferral.reject(errorMsg);
                            _this.onEvent(new Exports_2.AudioSourceErrorEvent(_this.privId, errorMsg));
                        });
                    }
                };
                if (_this.privContext.state === "suspended") {
                    // NOTE: On iOS, the Web Audio API requires sounds to be triggered from an explicit user action.
                    // https://github.com/WebAudio/web-audio-api/issues/790
                    _this.privContext.resume()
                        .then(next)
                        .catch(function (reason) {
                        _this.privInitializeDeferral.reject("Failed to initialize audio context: " + reason);
                    });
                }
                else {
                    next();
                }
            }
            return _this.privInitializeDeferral.promise;
        };
        this.id = function () {
            return _this.privId;
        };
        this.attach = function (audioNodeId) {
            _this.onEvent(new Exports_2.AudioStreamNodeAttachingEvent(_this.privId, audioNodeId));
            return _this.listen(audioNodeId).then(function (stream) {
                _this.onEvent(new Exports_2.AudioStreamNodeAttachedEvent(_this.privId, audioNodeId));
                return {
                    detach: function () { return __awaiter(_this, void 0, void 0, function () {
                        return __generator(this, function (_a) {
                            stream.readEnded();
                            delete this.privStreams[audioNodeId];
                            this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
                            return [2 /*return*/, this.turnOff()];
                        });
                    }); },
                    id: function () {
                        return audioNodeId;
                    },
                    read: function () {
                        return stream.read();
                    },
                };
            });
        };
        this.detach = function (audioNodeId) {
            if (audioNodeId && _this.privStreams[audioNodeId]) {
                _this.privStreams[audioNodeId].close();
                delete _this.privStreams[audioNodeId];
                _this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(_this.privId, audioNodeId));
            }
        };
        this.listen = function (audioNodeId) { return __awaiter(_this, void 0, void 0, function () {
            var stream, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.turnOn()];
                    case 1:
                        _a.sent();
                        stream = new Exports_2.ChunkedArrayBufferStream(this.privOutputChunkSize, audioNodeId);
                        this.privStreams[audioNodeId] = stream;
                        try {
                            this.privRecorder.record(this.privContext, this.privMediaStream, stream);
                        }
                        catch (error) {
                            this.onEvent(new Exports_2.AudioStreamNodeErrorEvent(this.privId, audioNodeId, error));
                            throw error;
                        }
                        result = stream;
                        return [2 /*return*/, result];
                }
            });
        }); };
        this.onEvent = function (event) {
            _this.privEvents.onEvent(event);
            Exports_2.Events.instance.onEvent(event);
        };
        this.createAudioContext = function () {
            if (!!_this.privContext) {
                return;
            }
            _this.privContext = AudioStreamFormat_1.AudioStreamFormatImpl.getAudioContext(MicAudioSource.AUDIOFORMAT.samplesPerSec);
        };
        this.privOutputChunkSize = MicAudioSource.AUDIOFORMAT.avgBytesPerSec / 10;
        this.privId = audioSourceId ? audioSourceId : Exports_2.createNoDashGuid();
        this.privEvents = new Exports_2.EventSource();
        this.privMediaStream = mediaStream || null;
        this.privIsClosing = false;
    }
    Object.defineProperty(MicAudioSource.prototype, "format", {
        get: function () {
            return Promise.resolve(MicAudioSource.AUDIOFORMAT);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MicAudioSource.prototype, "blob", {
        get: function () {
            return Promise.reject("Not implemented for Mic input");
        },
        enumerable: false,
        configurable: true
    });
    MicAudioSource.prototype.turnOff = function () {
        return __awaiter(this, void 0, void 0, function () {
            var streamId, stream;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        for (streamId in this.privStreams) {
                            if (streamId) {
                                stream = this.privStreams[streamId];
                                if (stream) {
                                    stream.close();
                                }
                            }
                        }
                        this.onEvent(new Exports_2.AudioSourceOffEvent(this.privId)); // no stream now
                        if (!this.privInitializeDeferral) return [3 /*break*/, 2];
                        // Correctly handle when browser forces mic off before turnOn() completes
                        return [4 /*yield*/, this.privInitializeDeferral];
                    case 1:
                        // Correctly handle when browser forces mic off before turnOn() completes
                        _a.sent();
                        this.privInitializeDeferral = null;
                        _a.label = 2;
                    case 2: return [4 /*yield*/, this.destroyAudioContext()];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    Object.defineProperty(MicAudioSource.prototype, "events", {
        get: function () {
            return this.privEvents;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MicAudioSource.prototype, "deviceInfo", {
        get: function () {
            return this.getMicrophoneLabel().then(function (label) {
                return {
                    bitspersample: MicAudioSource.AUDIOFORMAT.bitsPerSample,
                    channelcount: MicAudioSource.AUDIOFORMAT.channels,
                    connectivity: Exports_1.connectivity.Unknown,
                    manufacturer: "Speech SDK",
                    model: label,
                    samplerate: MicAudioSource.AUDIOFORMAT.samplesPerSec,
                    type: Exports_1.type.Microphones,
                };
            });
        },
        enumerable: false,
        configurable: true
    });
    MicAudioSource.prototype.setProperty = function (name, value) {
        if (name === exports.AudioWorkletSourceURLPropertyName) {
            this.privRecorder.setWorkletUrl(value);
        }
        else {
            throw new Error("Property '" + name + "' is not supported on Microphone.");
        }
    };
    MicAudioSource.prototype.getMicrophoneLabel = function () {
        var _this = this;
        var defaultMicrophoneName = "microphone";
        // If we did this already, return the value.
        if (this.privMicrophoneLabel !== undefined) {
            return Promise.resolve(this.privMicrophoneLabel);
        }
        // If the stream isn't currently running, we can't query devices because security.
        if (this.privMediaStream === undefined || !this.privMediaStream.active) {
            return Promise.resolve(defaultMicrophoneName);
        }
        // Setup a default
        this.privMicrophoneLabel = defaultMicrophoneName;
        // Get the id of the device running the audio track.
        var microphoneDeviceId = this.privMediaStream.getTracks()[0].getSettings().deviceId;
        // If the browser doesn't support getting the device ID, set a default and return.
        if (undefined === microphoneDeviceId) {
            return Promise.resolve(this.privMicrophoneLabel);
        }
        var deferred = new Exports_2.Deferred();
        // Enumerate the media devices.
        navigator.mediaDevices.enumerateDevices().then(function (devices) {
            for (var _i = 0, devices_1 = devices; _i < devices_1.length; _i++) {
                var device = devices_1[_i];
                if (device.deviceId === microphoneDeviceId) {
                    // Found the device
                    _this.privMicrophoneLabel = device.label;
                    break;
                }
            }
            deferred.resolve(_this.privMicrophoneLabel);
        }, function () { return deferred.resolve(_this.privMicrophoneLabel); });
        return deferred.promise;
    };
    MicAudioSource.prototype.destroyAudioContext = function () {
        return __awaiter(this, void 0, void 0, function () {
            var hasClose;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.privContext) {
                            return [2 /*return*/];
                        }
                        this.privRecorder.releaseMediaResources(this.privContext);
                        hasClose = false;
                        if ("close" in this.privContext) {
                            hasClose = true;
                        }
                        if (!hasClose) return [3 /*break*/, 3];
                        if (!!this.privIsClosing) return [3 /*break*/, 2];
                        // The audio context close may take enough time that the close is called twice
                        this.privIsClosing = true;
                        return [4 /*yield*/, this.privContext.close()];
                    case 1:
                        _a.sent();
                        this.privContext = null;
                        this.privIsClosing = false;
                        _a.label = 2;
                    case 2: return [3 /*break*/, 5];
                    case 3:
                        if (!(null !== this.privContext && this.privContext.state === "running")) return [3 /*break*/, 5];
                        // Suspend actually takes a callback, but analogous to the
                        // resume method, it'll be only fired if suspend is called
                        // in a direct response to a user action. The later is not always
                        // the case, as TurnOff is also called, when we receive an
                        // end-of-speech message from the service. So, doing a best effort
                        // fire-and-forget here.
                        return [4 /*yield*/, this.privContext.suspend()];
                    case 4:
                        // Suspend actually takes a callback, but analogous to the
                        // resume method, it'll be only fired if suspend is called
                        // in a direct response to a user action. The later is not always
                        // the case, as TurnOff is also called, when we receive an
                        // end-of-speech message from the service. So, doing a best effort
                        // fire-and-forget here.
                        _a.sent();
                        _a.label = 5;
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    MicAudioSource.AUDIOFORMAT = AudioStreamFormat_1.AudioStreamFormat.getDefaultInputFormat();
    return MicAudioSource;
}());
exports.MicAudioSource = MicAudioSource;



/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutoDetectSourceLanguagesOpenRangeOptionName = exports.ForceDictationPropertyName = exports.ServicePropertiesPropertyName = exports.CancellationErrorCodePropertyName = exports.OutputFormatPropertyName = void 0;
// Make sure not to export internal modules.
//
__exportStar(__webpack_require__(54), exports);
__exportStar(__webpack_require__(57), exports);
__exportStar(__webpack_require__(56), exports);
__exportStar(__webpack_require__(58), exports);
__exportStar(__webpack_require__(59), exports);
__exportStar(__webpack_require__(60), exports);
__exportStar(__webpack_require__(171), exports);
__exportStar(__webpack_require__(172), exports);
__exportStar(__webpack_require__(174), exports);
__exportStar(__webpack_require__(175), exports);
__exportStar(__webpack_require__(176), exports);
__exportStar(__webpack_require__(177), exports);
__exportStar(__webpack_require__(178), exports);
__exportStar(__webpack_require__(179), exports);
__exportStar(__webpack_require__(180), exports);
__exportStar(__webpack_require__(181), exports);
__exportStar(__webpack_require__(182), exports);
__exportStar(__webpack_require__(183), exports);
__exportStar(__webpack_require__(184), exports);
__exportStar(__webpack_require__(185), exports);
__exportStar(__webpack_require__(186), exports);
__exportStar(__webpack_require__(187), exports);
__exportStar(__webpack_require__(188), exports);
__exportStar(__webpack_require__(189), exports);
__exportStar(__webpack_require__(190), exports);
__exportStar(__webpack_require__(191), exports);
__exportStar(__webpack_require__(192), exports);
__exportStar(__webpack_require__(193), exports);
__exportStar(__webpack_require__(194), exports);
__exportStar(__webpack_require__(195), exports);
__exportStar(__webpack_require__(196), exports);
__exportStar(__webpack_require__(197), exports);
__exportStar(__webpack_require__(199), exports);
__exportStar(__webpack_require__(200), exports);
__exportStar(__webpack_require__(201), exports);
__exportStar(__webpack_require__(202), exports);
__exportStar(__webpack_require__(206), exports);
__exportStar(__webpack_require__(207), exports);
__exportStar(__webpack_require__(224), exports);
__exportStar(__webpack_require__(225), exports);
__exportStar(__webpack_require__(226), exports);
__exportStar(__webpack_require__(228), exports);
__exportStar(__webpack_require__(229), exports);
__exportStar(__webpack_require__(230), exports);
__exportStar(__webpack_require__(231), exports);
__exportStar(__webpack_require__(232), exports);
exports.OutputFormatPropertyName = "OutputFormat";
exports.CancellationErrorCodePropertyName = "CancellationErrorCode";
exports.ServicePropertiesPropertyName = "ServiceProperties";
exports.ForceDictationPropertyName = "ForceDictation";
exports.AutoDetectSourceLanguagesOpenRangeOptionName = "OpenRange";



/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CognitiveSubscriptionKeyAuthentication = void 0;
var Exports_1 = __webpack_require__(4);
var HeaderNames_1 = __webpack_require__(55);
var IAuthentication_1 = __webpack_require__(56);
/**
 * @class
 */
var CognitiveSubscriptionKeyAuthentication = /** @class */ (function () {
    /**
     * Creates and initializes an instance of the CognitiveSubscriptionKeyAuthentication class.
     * @constructor
     * @param {string} subscriptionKey - The subscription key
     */
    function CognitiveSubscriptionKeyAuthentication(subscriptionKey) {
        var _this = this;
        /**
         * Fetches the subscription key.
         * @member
         * @function
         * @public
         * @param {string} authFetchEventId - The id to fetch.
         */
        this.fetch = function (authFetchEventId) {
            return Promise.resolve(_this.privAuthInfo);
        };
        /**
         * Fetches the subscription key.
         * @member
         * @function
         * @public
         * @param {string} authFetchEventId - The id to fetch.
         */
        this.fetchOnExpiry = function (authFetchEventId) {
            return Promise.resolve(_this.privAuthInfo);
        };
        if (!subscriptionKey) {
            throw new Exports_1.ArgumentNullError("subscriptionKey");
        }
        this.privAuthInfo = new IAuthentication_1.AuthInfo(HeaderNames_1.HeaderNames.AuthKey, subscriptionKey);
    }
    return CognitiveSubscriptionKeyAuthentication;
}());
exports.CognitiveSubscriptionKeyAuthentication = CognitiveSubscriptionKeyAuthentication;



/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.HeaderNames = void 0;
var HeaderNames = /** @class */ (function () {
    function HeaderNames() {
    }
    HeaderNames.AuthKey = "Ocp-Apim-Subscription-Key";
    HeaderNames.ConnectionId = "X-ConnectionId";
    HeaderNames.ContentType = "Content-Type";
    HeaderNames.CustomCommandsAppId = "X-CommandsAppId";
    HeaderNames.Path = "Path";
    HeaderNames.RequestId = "X-RequestId";
    HeaderNames.RequestStreamId = "X-StreamId";
    HeaderNames.RequestTimestamp = "X-Timestamp";
    return HeaderNames;
}());
exports.HeaderNames = HeaderNames;



/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthInfo = void 0;
var AuthInfo = /** @class */ (function () {
    function AuthInfo(headerName, token) {
        this.privHeaderName = headerName;
        this.privToken = token;
    }
    Object.defineProperty(AuthInfo.prototype, "headerName", {
        get: function () {
            return this.privHeaderName;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AuthInfo.prototype, "token", {
        get: function () {
            return this.privToken;
        },
        enumerable: false,
        configurable: true
    });
    return AuthInfo;
}());
exports.AuthInfo = AuthInfo;



/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CognitiveTokenAuthentication = void 0;
var Exports_1 = __webpack_require__(4);
var IAuthentication_1 = __webpack_require__(56);
var AuthHeader = "Authorization";
var CognitiveTokenAuthentication = /** @class */ (function () {
    function CognitiveTokenAuthentication(fetchCallback, fetchOnExpiryCallback) {
        var _this = this;
        this.fetch = function (authFetchEventId) {
            return _this.privFetchCallback(authFetchEventId).then(function (token) { return new IAuthentication_1.AuthInfo(AuthHeader, CognitiveTokenAuthentication.privTokenPrefix + token); });
        };
        this.fetchOnExpiry = function (authFetchEventId) {
            return _this.privFetchOnExpiryCallback(authFetchEventId).then(function (token) { return new IAuthentication_1.AuthInfo(AuthHeader, CognitiveTokenAuthentication.privTokenPrefix + token); });
        };
        if (!fetchCallback) {
            throw new Exports_1.ArgumentNullError("fetchCallback");
        }
        if (!fetchOnExpiryCallback) {
            throw new Exports_1.ArgumentNullError("fetchOnExpiryCallback");
        }
        this.privFetchCallback = fetchCallback;
        this.privFetchOnExpiryCallback = fetchOnExpiryCallback;
    }
    CognitiveTokenAuthentication.privTokenPrefix = "bearer ";
    return CognitiveTokenAuthentication;
}());
exports.CognitiveTokenAuthentication = CognitiveTokenAuthentication;



/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentConnectionFactory = void 0;
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(61);
var ConnectionFactoryBase_1 = __webpack_require__(123);
var Exports_3 = __webpack_require__(53);
var HeaderNames_1 = __webpack_require__(55);
var IntentConnectionFactory = /** @class */ (function (_super) {
    __extends(IntentConnectionFactory, _super);
    function IntentConnectionFactory() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.create = function (config, authInfo, connectionId) {
            var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint);
            if (!endpoint) {
                var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_IntentRegion);
                var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region);
                var host = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".sr.speech" + hostSuffix);
                endpoint = host + "/speech/recognition/interactive/cognitiveservices/v1";
            }
            var queryParams = {
                format: "simple",
                language: config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage),
            };
            _this.setCommonUrlParams(config, queryParams, endpoint);
            var headers = {};
            if (authInfo.token !== undefined && authInfo.token !== "") {
                headers[authInfo.headerName] = authInfo.token;
            }
            headers[HeaderNames_1.HeaderNames.ConnectionId] = connectionId;
            config.parameters.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Url, endpoint);
            var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
            return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_3.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);
        };
        return _this;
    }
    IntentConnectionFactory.prototype.getSpeechRegionFromIntentRegion = function (intentRegion) {
        switch (intentRegion) {
            case "West US":
            case "US West":
            case "westus":
                return "uswest";
            case "West US 2":
            case "US West 2":
            case "westus2":
                return "uswest2";
            case "South Central US":
            case "US South Central":
            case "southcentralus":
                return "ussouthcentral";
            case "West Central US":
            case "US West Central":
            case "westcentralus":
                return "uswestcentral";
            case "East US":
            case "US East":
            case "eastus":
                return "useast";
            case "East US 2":
            case "US East 2":
            case "eastus2":
                return "useast2";
            case "West Europe":
            case "Europe West":
            case "westeurope":
                return "europewest";
            case "North Europe":
            case "Europe North":
            case "northeurope":
                return "europenorth";
            case "Brazil South":
            case "South Brazil":
            case "southbrazil":
                return "brazilsouth";
            case "Australia East":
            case "East Australia":
            case "eastaustralia":
                return "australiaeast";
            case "Southeast Asia":
            case "Asia Southeast":
            case "southeastasia":
                return "asiasoutheast";
            case "East Asia":
            case "Asia East":
            case "eastasia":
                return "asiaeast";
            default:
                return intentRegion;
        }
    };
    return IntentConnectionFactory;
}(ConnectionFactoryBase_1.ConnectionFactoryBase));
exports.IntentConnectionFactory = IntentConnectionFactory;



/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
var AudioConfig_1 = __webpack_require__(62);
Object.defineProperty(exports, "AudioConfig", { enumerable: true, get: function () { return AudioConfig_1.AudioConfig; } });
var AudioStreamFormat_1 = __webpack_require__(72);
Object.defineProperty(exports, "AudioStreamFormat", { enumerable: true, get: function () { return AudioStreamFormat_1.AudioStreamFormat; } });
Object.defineProperty(exports, "AudioFormatTag", { enumerable: true, get: function () { return AudioStreamFormat_1.AudioFormatTag; } });
var AudioInputStream_1 = __webpack_require__(66);
Object.defineProperty(exports, "AudioInputStream", { enumerable: true, get: function () { return AudioInputStream_1.AudioInputStream; } });
Object.defineProperty(exports, "PullAudioInputStream", { enumerable: true, get: function () { return AudioInputStream_1.PullAudioInputStream; } });
Object.defineProperty(exports, "PushAudioInputStream", { enumerable: true, get: function () { return AudioInputStream_1.PushAudioInputStream; } });
var AudioOutputStream_1 = __webpack_require__(73);
Object.defineProperty(exports, "AudioOutputStream", { enumerable: true, get: function () { return AudioOutputStream_1.AudioOutputStream; } });
Object.defineProperty(exports, "PullAudioOutputStream", { enumerable: true, get: function () { return AudioOutputStream_1.PullAudioOutputStream; } });
Object.defineProperty(exports, "PushAudioOutputStream", { enumerable: true, get: function () { return AudioOutputStream_1.PushAudioOutputStream; } });
var CancellationReason_1 = __webpack_require__(76);
Object.defineProperty(exports, "CancellationReason", { enumerable: true, get: function () { return CancellationReason_1.CancellationReason; } });
var PullAudioInputStreamCallback_1 = __webpack_require__(77);
Object.defineProperty(exports, "PullAudioInputStreamCallback", { enumerable: true, get: function () { return PullAudioInputStreamCallback_1.PullAudioInputStreamCallback; } });
var PushAudioOutputStreamCallback_1 = __webpack_require__(78);
Object.defineProperty(exports, "PushAudioOutputStreamCallback", { enumerable: true, get: function () { return PushAudioOutputStreamCallback_1.PushAudioOutputStreamCallback; } });
var KeywordRecognitionModel_1 = __webpack_require__(79);
Object.defineProperty(exports, "KeywordRecognitionModel", { enumerable: true, get: function () { return KeywordRecognitionModel_1.KeywordRecognitionModel; } });
var SessionEventArgs_1 = __webpack_require__(80);
Object.defineProperty(exports, "SessionEventArgs", { enumerable: true, get: function () { return SessionEventArgs_1.SessionEventArgs; } });
var RecognitionEventArgs_1 = __webpack_require__(81);
Object.defineProperty(exports, "RecognitionEventArgs", { enumerable: true, get: function () { return RecognitionEventArgs_1.RecognitionEventArgs; } });
var OutputFormat_1 = __webpack_require__(82);
Object.defineProperty(exports, "OutputFormat", { enumerable: true, get: function () { return OutputFormat_1.OutputFormat; } });
var IntentRecognitionEventArgs_1 = __webpack_require__(83);
Object.defineProperty(exports, "IntentRecognitionEventArgs", { enumerable: true, get: function () { return IntentRecognitionEventArgs_1.IntentRecognitionEventArgs; } });
var RecognitionResult_1 = __webpack_require__(84);
Object.defineProperty(exports, "RecognitionResult", { enumerable: true, get: function () { return RecognitionResult_1.RecognitionResult; } });
var SpeechRecognitionResult_1 = __webpack_require__(85);
Object.defineProperty(exports, "SpeechRecognitionResult", { enumerable: true, get: function () { return SpeechRecognitionResult_1.SpeechRecognitionResult; } });
var IntentRecognitionResult_1 = __webpack_require__(86);
Object.defineProperty(exports, "IntentRecognitionResult", { enumerable: true, get: function () { return IntentRecognitionResult_1.IntentRecognitionResult; } });
var LanguageUnderstandingModel_1 = __webpack_require__(87);
Object.defineProperty(exports, "LanguageUnderstandingModel", { enumerable: true, get: function () { return LanguageUnderstandingModel_1.LanguageUnderstandingModel; } });
var SpeechRecognitionEventArgs_1 = __webpack_require__(88);
Object.defineProperty(exports, "SpeechRecognitionEventArgs", { enumerable: true, get: function () { return SpeechRecognitionEventArgs_1.SpeechRecognitionEventArgs; } });
Object.defineProperty(exports, "ConversationTranscriptionEventArgs", { enumerable: true, get: function () { return SpeechRecognitionEventArgs_1.ConversationTranscriptionEventArgs; } });
var SpeechRecognitionCanceledEventArgs_1 = __webpack_require__(89);
Object.defineProperty(exports, "SpeechRecognitionCanceledEventArgs", { enumerable: true, get: function () { return SpeechRecognitionCanceledEventArgs_1.SpeechRecognitionCanceledEventArgs; } });
var TranslationRecognitionEventArgs_1 = __webpack_require__(91);
Object.defineProperty(exports, "TranslationRecognitionEventArgs", { enumerable: true, get: function () { return TranslationRecognitionEventArgs_1.TranslationRecognitionEventArgs; } });
var TranslationSynthesisEventArgs_1 = __webpack_require__(92);
Object.defineProperty(exports, "TranslationSynthesisEventArgs", { enumerable: true, get: function () { return TranslationSynthesisEventArgs_1.TranslationSynthesisEventArgs; } });
var TranslationRecognitionResult_1 = __webpack_require__(93);
Object.defineProperty(exports, "TranslationRecognitionResult", { enumerable: true, get: function () { return TranslationRecognitionResult_1.TranslationRecognitionResult; } });
var TranslationSynthesisResult_1 = __webpack_require__(94);
Object.defineProperty(exports, "TranslationSynthesisResult", { enumerable: true, get: function () { return TranslationSynthesisResult_1.TranslationSynthesisResult; } });
var ResultReason_1 = __webpack_require__(95);
Object.defineProperty(exports, "ResultReason", { enumerable: true, get: function () { return ResultReason_1.ResultReason; } });
var SpeechConfig_1 = __webpack_require__(96);
Object.defineProperty(exports, "SpeechConfig", { enumerable: true, get: function () { return SpeechConfig_1.SpeechConfig; } });
Object.defineProperty(exports, "SpeechConfigImpl", { enumerable: true, get: function () { return SpeechConfig_1.SpeechConfigImpl; } });
var SpeechTranslationConfig_1 = __webpack_require__(97);
Object.defineProperty(exports, "SpeechTranslationConfig", { enumerable: true, get: function () { return SpeechTranslationConfig_1.SpeechTranslationConfig; } });
Object.defineProperty(exports, "SpeechTranslationConfigImpl", { enumerable: true, get: function () { return SpeechTranslationConfig_1.SpeechTranslationConfigImpl; } });
var PropertyCollection_1 = __webpack_require__(98);
Object.defineProperty(exports, "PropertyCollection", { enumerable: true, get: function () { return PropertyCollection_1.PropertyCollection; } });
var PropertyId_1 = __webpack_require__(99);
Object.defineProperty(exports, "PropertyId", { enumerable: true, get: function () { return PropertyId_1.PropertyId; } });
var Recognizer_1 = __webpack_require__(100);
Object.defineProperty(exports, "Recognizer", { enumerable: true, get: function () { return Recognizer_1.Recognizer; } });
var SpeechRecognizer_1 = __webpack_require__(101);
Object.defineProperty(exports, "SpeechRecognizer", { enumerable: true, get: function () { return SpeechRecognizer_1.SpeechRecognizer; } });
var IntentRecognizer_1 = __webpack_require__(102);
Object.defineProperty(exports, "IntentRecognizer", { enumerable: true, get: function () { return IntentRecognizer_1.IntentRecognizer; } });
var VoiceProfileType_1 = __webpack_require__(103);
Object.defineProperty(exports, "VoiceProfileType", { enumerable: true, get: function () { return VoiceProfileType_1.VoiceProfileType; } });
var TranslationRecognizer_1 = __webpack_require__(104);
Object.defineProperty(exports, "TranslationRecognizer", { enumerable: true, get: function () { return TranslationRecognizer_1.TranslationRecognizer; } });
var Translations_1 = __webpack_require__(107);
Object.defineProperty(exports, "Translations", { enumerable: true, get: function () { return Translations_1.Translations; } });
var NoMatchReason_1 = __webpack_require__(108);
Object.defineProperty(exports, "NoMatchReason", { enumerable: true, get: function () { return NoMatchReason_1.NoMatchReason; } });
var NoMatchDetails_1 = __webpack_require__(109);
Object.defineProperty(exports, "NoMatchDetails", { enumerable: true, get: function () { return NoMatchDetails_1.NoMatchDetails; } });
var TranslationRecognitionCanceledEventArgs_1 = __webpack_require__(110);
Object.defineProperty(exports, "TranslationRecognitionCanceledEventArgs", { enumerable: true, get: function () { return TranslationRecognitionCanceledEventArgs_1.TranslationRecognitionCanceledEventArgs; } });
var IntentRecognitionCanceledEventArgs_1 = __webpack_require__(111);
Object.defineProperty(exports, "IntentRecognitionCanceledEventArgs", { enumerable: true, get: function () { return IntentRecognitionCanceledEventArgs_1.IntentRecognitionCanceledEventArgs; } });
var CancellationDetailsBase_1 = __webpack_require__(112);
Object.defineProperty(exports, "CancellationDetailsBase", { enumerable: true, get: function () { return CancellationDetailsBase_1.CancellationDetailsBase; } });
var CancellationDetails_1 = __webpack_require__(113);
Object.defineProperty(exports, "CancellationDetails", { enumerable: true, get: function () { return CancellationDetails_1.CancellationDetails; } });
var CancellationErrorCodes_1 = __webpack_require__(114);
Object.defineProperty(exports, "CancellationErrorCode", { enumerable: true, get: function () { return CancellationErrorCodes_1.CancellationErrorCode; } });
var ConnectionEventArgs_1 = __webpack_require__(115);
Object.defineProperty(exports, "ConnectionEventArgs", { enumerable: true, get: function () { return ConnectionEventArgs_1.ConnectionEventArgs; } });
var ServiceEventArgs_1 = __webpack_require__(116);
Object.defineProperty(exports, "ServiceEventArgs", { enumerable: true, get: function () { return ServiceEventArgs_1.ServiceEventArgs; } });
var Connection_1 = __webpack_require__(105);
Object.defineProperty(exports, "Connection", { enumerable: true, get: function () { return Connection_1.Connection; } });
var PhraseListGrammar_1 = __webpack_require__(117);
Object.defineProperty(exports, "PhraseListGrammar", { enumerable: true, get: function () { return PhraseListGrammar_1.PhraseListGrammar; } });
var DialogServiceConfig_1 = __webpack_require__(118);
Object.defineProperty(exports, "DialogServiceConfig", { enumerable: true, get: function () { return DialogServiceConfig_1.DialogServiceConfig; } });
var BotFrameworkConfig_1 = __webpack_require__(119);
Object.defineProperty(exports, "BotFrameworkConfig", { enumerable: true, get: function () { return BotFrameworkConfig_1.BotFrameworkConfig; } });
var CustomCommandsConfig_1 = __webpack_require__(120);
Object.defineProperty(exports, "CustomCommandsConfig", { enumerable: true, get: function () { return CustomCommandsConfig_1.CustomCommandsConfig; } });
var DialogServiceConnector_1 = __webpack_require__(121);
Object.defineProperty(exports, "DialogServiceConnector", { enumerable: true, get: function () { return DialogServiceConnector_1.DialogServiceConnector; } });
var ActivityReceivedEventArgs_1 = __webpack_require__(125);
Object.defineProperty(exports, "ActivityReceivedEventArgs", { enumerable: true, get: function () { return ActivityReceivedEventArgs_1.ActivityReceivedEventArgs; } });
var TurnStatusReceivedEventArgs_1 = __webpack_require__(126);
Object.defineProperty(exports, "TurnStatusReceivedEventArgs", { enumerable: true, get: function () { return TurnStatusReceivedEventArgs_1.TurnStatusReceivedEventArgs; } });
var ServicePropertyChannel_1 = __webpack_require__(128);
Object.defineProperty(exports, "ServicePropertyChannel", { enumerable: true, get: function () { return ServicePropertyChannel_1.ServicePropertyChannel; } });
var ProfanityOption_1 = __webpack_require__(129);
Object.defineProperty(exports, "ProfanityOption", { enumerable: true, get: function () { return ProfanityOption_1.ProfanityOption; } });
var BaseAudioPlayer_1 = __webpack_require__(130);
Object.defineProperty(exports, "BaseAudioPlayer", { enumerable: true, get: function () { return BaseAudioPlayer_1.BaseAudioPlayer; } });
var ConnectionMessageEventArgs_1 = __webpack_require__(131);
Object.defineProperty(exports, "ConnectionMessageEventArgs", { enumerable: true, get: function () { return ConnectionMessageEventArgs_1.ConnectionMessageEventArgs; } });
var ConnectionMessage_1 = __webpack_require__(106);
Object.defineProperty(exports, "ConnectionMessage", { enumerable: true, get: function () { return ConnectionMessage_1.ConnectionMessage; } });
var VoiceProfile_1 = __webpack_require__(132);
Object.defineProperty(exports, "VoiceProfile", { enumerable: true, get: function () { return VoiceProfile_1.VoiceProfile; } });
var VoiceProfileEnrollmentResult_1 = __webpack_require__(133);
Object.defineProperty(exports, "VoiceProfileEnrollmentResult", { enumerable: true, get: function () { return VoiceProfileEnrollmentResult_1.VoiceProfileEnrollmentResult; } });
Object.defineProperty(exports, "VoiceProfileEnrollmentCancellationDetails", { enumerable: true, get: function () { return VoiceProfileEnrollmentResult_1.VoiceProfileEnrollmentCancellationDetails; } });
var VoiceProfileResult_1 = __webpack_require__(134);
Object.defineProperty(exports, "VoiceProfileResult", { enumerable: true, get: function () { return VoiceProfileResult_1.VoiceProfileResult; } });
Object.defineProperty(exports, "VoiceProfileCancellationDetails", { enumerable: true, get: function () { return VoiceProfileResult_1.VoiceProfileCancellationDetails; } });
var VoiceProfilePhraseResult_1 = __webpack_require__(135);
Object.defineProperty(exports, "VoiceProfilePhraseResult", { enumerable: true, get: function () { return VoiceProfilePhraseResult_1.VoiceProfilePhraseResult; } });
var VoiceProfileClient_1 = __webpack_require__(136);
Object.defineProperty(exports, "VoiceProfileClient", { enumerable: true, get: function () { return VoiceProfileClient_1.VoiceProfileClient; } });
var SpeakerRecognizer_1 = __webpack_require__(137);
Object.defineProperty(exports, "SpeakerRecognizer", { enumerable: true, get: function () { return SpeakerRecognizer_1.SpeakerRecognizer; } });
var SpeakerIdentificationModel_1 = __webpack_require__(138);
Object.defineProperty(exports, "SpeakerIdentificationModel", { enumerable: true, get: function () { return SpeakerIdentificationModel_1.SpeakerIdentificationModel; } });
var SpeakerVerificationModel_1 = __webpack_require__(139);
Object.defineProperty(exports, "SpeakerVerificationModel", { enumerable: true, get: function () { return SpeakerVerificationModel_1.SpeakerVerificationModel; } });
var AutoDetectSourceLanguageConfig_1 = __webpack_require__(140);
Object.defineProperty(exports, "AutoDetectSourceLanguageConfig", { enumerable: true, get: function () { return AutoDetectSourceLanguageConfig_1.AutoDetectSourceLanguageConfig; } });
var AutoDetectSourceLanguageResult_1 = __webpack_require__(141);
Object.defineProperty(exports, "AutoDetectSourceLanguageResult", { enumerable: true, get: function () { return AutoDetectSourceLanguageResult_1.AutoDetectSourceLanguageResult; } });
var SourceLanguageConfig_1 = __webpack_require__(142);
Object.defineProperty(exports, "SourceLanguageConfig", { enumerable: true, get: function () { return SourceLanguageConfig_1.SourceLanguageConfig; } });
var SpeakerRecognitionResult_1 = __webpack_require__(143);
Object.defineProperty(exports, "SpeakerRecognitionResult", { enumerable: true, get: function () { return SpeakerRecognitionResult_1.SpeakerRecognitionResult; } });
Object.defineProperty(exports, "SpeakerRecognitionResultType", { enumerable: true, get: function () { return SpeakerRecognitionResult_1.SpeakerRecognitionResultType; } });
Object.defineProperty(exports, "SpeakerRecognitionCancellationDetails", { enumerable: true, get: function () { return SpeakerRecognitionResult_1.SpeakerRecognitionCancellationDetails; } });
var Exports_1 = __webpack_require__(144);
Object.defineProperty(exports, "Conversation", { enumerable: true, get: function () { return Exports_1.Conversation; } });
Object.defineProperty(exports, "ConversationExpirationEventArgs", { enumerable: true, get: function () { return Exports_1.ConversationExpirationEventArgs; } });
Object.defineProperty(exports, "ConversationParticipantsChangedEventArgs", { enumerable: true, get: function () { return Exports_1.ConversationParticipantsChangedEventArgs; } });
Object.defineProperty(exports, "ConversationTranslationCanceledEventArgs", { enumerable: true, get: function () { return Exports_1.ConversationTranslationCanceledEventArgs; } });
Object.defineProperty(exports, "ConversationTranslationEventArgs", { enumerable: true, get: function () { return Exports_1.ConversationTranslationEventArgs; } });
Object.defineProperty(exports, "ConversationTranslationResult", { enumerable: true, get: function () { return Exports_1.ConversationTranslationResult; } });
Object.defineProperty(exports, "ConversationTranslator", { enumerable: true, get: function () { return Exports_1.ConversationTranslator; } });
Object.defineProperty(exports, "ConversationTranscriber", { enumerable: true, get: function () { return Exports_1.ConversationTranscriber; } });
Object.defineProperty(exports, "Participant", { enumerable: true, get: function () { return Exports_1.Participant; } });
Object.defineProperty(exports, "ParticipantChangedReason", { enumerable: true, get: function () { return Exports_1.ParticipantChangedReason; } });
Object.defineProperty(exports, "User", { enumerable: true, get: function () { return Exports_1.User; } });
var SpeechSynthesisOutputFormat_1 = __webpack_require__(75);
Object.defineProperty(exports, "SpeechSynthesisOutputFormat", { enumerable: true, get: function () { return SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat; } });
var SpeechSynthesizer_1 = __webpack_require__(156);
Object.defineProperty(exports, "SpeechSynthesizer", { enumerable: true, get: function () { return SpeechSynthesizer_1.SpeechSynthesizer; } });
var SynthesisResult_1 = __webpack_require__(157);
Object.defineProperty(exports, "SynthesisResult", { enumerable: true, get: function () { return SynthesisResult_1.SynthesisResult; } });
var SpeechSynthesisResult_1 = __webpack_require__(158);
Object.defineProperty(exports, "SpeechSynthesisResult", { enumerable: true, get: function () { return SpeechSynthesisResult_1.SpeechSynthesisResult; } });
var SpeechSynthesisEventArgs_1 = __webpack_require__(159);
Object.defineProperty(exports, "SpeechSynthesisEventArgs", { enumerable: true, get: function () { return SpeechSynthesisEventArgs_1.SpeechSynthesisEventArgs; } });
var SpeechSynthesisWordBoundaryEventArgs_1 = __webpack_require__(160);
Object.defineProperty(exports, "SpeechSynthesisWordBoundaryEventArgs", { enumerable: true, get: function () { return SpeechSynthesisWordBoundaryEventArgs_1.SpeechSynthesisWordBoundaryEventArgs; } });
var SpeechSynthesisBookmarkEventArgs_1 = __webpack_require__(161);
Object.defineProperty(exports, "SpeechSynthesisBookmarkEventArgs", { enumerable: true, get: function () { return SpeechSynthesisBookmarkEventArgs_1.SpeechSynthesisBookmarkEventArgs; } });
var SpeechSynthesisVisemeEventArgs_1 = __webpack_require__(162);
Object.defineProperty(exports, "SpeechSynthesisVisemeEventArgs", { enumerable: true, get: function () { return SpeechSynthesisVisemeEventArgs_1.SpeechSynthesisVisemeEventArgs; } });
var SynthesisVoicesResult_1 = __webpack_require__(163);
Object.defineProperty(exports, "SynthesisVoicesResult", { enumerable: true, get: function () { return SynthesisVoicesResult_1.SynthesisVoicesResult; } });
var VoiceInfo_1 = __webpack_require__(164);
Object.defineProperty(exports, "VoiceInfo", { enumerable: true, get: function () { return VoiceInfo_1.VoiceInfo; } });
var SpeakerAudioDestination_1 = __webpack_require__(165);
Object.defineProperty(exports, "SpeakerAudioDestination", { enumerable: true, get: function () { return SpeakerAudioDestination_1.SpeakerAudioDestination; } });
var ConversationTranscriptionCanceledEventArgs_1 = __webpack_require__(166);
Object.defineProperty(exports, "ConversationTranscriptionCanceledEventArgs", { enumerable: true, get: function () { return ConversationTranscriptionCanceledEventArgs_1.ConversationTranscriptionCanceledEventArgs; } });
var PronunciationAssessmentGradingSystem_1 = __webpack_require__(167);
Object.defineProperty(exports, "PronunciationAssessmentGradingSystem", { enumerable: true, get: function () { return PronunciationAssessmentGradingSystem_1.PronunciationAssessmentGradingSystem; } });
var PronunciationAssessmentGranularity_1 = __webpack_require__(168);
Object.defineProperty(exports, "PronunciationAssessmentGranularity", { enumerable: true, get: function () { return PronunciationAssessmentGranularity_1.PronunciationAssessmentGranularity; } });
var PronunciationAssessmentConfig_1 = __webpack_require__(169);
Object.defineProperty(exports, "PronunciationAssessmentConfig", { enumerable: true, get: function () { return PronunciationAssessmentConfig_1.PronunciationAssessmentConfig; } });
var PronunciationAssessmentResult_1 = __webpack_require__(170);
Object.defineProperty(exports, "PronunciationAssessmentResult", { enumerable: true, get: function () { return PronunciationAssessmentResult_1.PronunciationAssessmentResult; } });



/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AudioOutputConfigImpl = exports.AudioConfigImpl = exports.AudioConfig = void 0;
var Exports_1 = __webpack_require__(2);
var Contracts_1 = __webpack_require__(63);
var Exports_2 = __webpack_require__(61);
var AudioFileWriter_1 = __webpack_require__(64);
var AudioInputStream_1 = __webpack_require__(66);
var AudioOutputStream_1 = __webpack_require__(73);
/**
 * Represents audio input configuration used for specifying what type of input to use (microphone, file, stream).
 * @class AudioConfig
 * Updated in version 1.11.0
 */
var AudioConfig = /** @class */ (function () {
    function AudioConfig() {
    }
    /**
     * Creates an AudioConfig object representing the default microphone on the system.
     * @member AudioConfig.fromDefaultMicrophoneInput
     * @function
     * @public
     * @returns {AudioConfig} The audio input configuration being created.
     */
    AudioConfig.fromDefaultMicrophoneInput = function () {
        var pcmRecorder = new Exports_1.PcmRecorder(true);
        return new AudioConfigImpl(new Exports_1.MicAudioSource(pcmRecorder));
    };
    /**
     * Creates an AudioConfig object representing a microphone with the specified device ID.
     * @member AudioConfig.fromMicrophoneInput
     * @function
     * @public
     * @param {string | undefined} deviceId - Specifies the device ID of the microphone to be used.
     *        Default microphone is used the value is omitted.
     * @returns {AudioConfig} The audio input configuration being created.
     */
    AudioConfig.fromMicrophoneInput = function (deviceId) {
        var pcmRecorder = new Exports_1.PcmRecorder(true);
        return new AudioConfigImpl(new Exports_1.MicAudioSource(pcmRecorder, deviceId));
    };
    /**
     * Creates an AudioConfig object representing the specified file.
     * @member AudioConfig.fromWavFileInput
     * @function
     * @public
     * @param {File} fileName - Specifies the audio input file. Currently, only WAV / PCM is supported.
     * @returns {AudioConfig} The audio input configuration being created.
     */
    AudioConfig.fromWavFileInput = function (file, name) {
        if (name === void 0) { name = "unnamedBuffer.wav"; }
        return new AudioConfigImpl(new Exports_1.FileAudioSource(file, name));
    };
    /**
     * Creates an AudioConfig object representing the specified stream.
     * @member AudioConfig.fromStreamInput
     * @function
     * @public
     * @param {AudioInputStream | PullAudioInputStreamCallback | MediaStream} audioStream - Specifies the custom audio input
     *        stream. Currently, only WAV / PCM is supported.
     * @returns {AudioConfig} The audio input configuration being created.
     */
    AudioConfig.fromStreamInput = function (audioStream) {
        if (audioStream instanceof Exports_2.PullAudioInputStreamCallback) {
            return new AudioConfigImpl(new AudioInputStream_1.PullAudioInputStreamImpl(audioStream));
        }
        if (audioStream instanceof Exports_2.AudioInputStream) {
            return new AudioConfigImpl(audioStream);
        }
        if (typeof MediaStream !== "undefined" && audioStream instanceof MediaStream) {
            var pcmRecorder = new Exports_1.PcmRecorder(false);
            return new AudioConfigImpl(new Exports_1.MicAudioSource(pcmRecorder, null, null, audioStream));
        }
        throw new Error("Not Supported Type");
    };
    /**
     * Creates an AudioConfig object representing the default speaker.
     * @member AudioConfig.fromDefaultSpeakerOutput
     * @function
     * @public
     * @returns {AudioConfig} The audio output configuration being created.
     * Added in version 1.11.0
     */
    AudioConfig.fromDefaultSpeakerOutput = function () {
        return new AudioOutputConfigImpl(new Exports_2.SpeakerAudioDestination());
    };
    /**
     * Creates an AudioConfig object representing the custom IPlayer object.
     * You can use the IPlayer object to control pause, resume, etc.
     * @member AudioConfig.fromSpeakerOutput
     * @function
     * @public
     * @param {IPlayer} player - the IPlayer object for playback.
     * @returns {AudioConfig} The audio output configuration being created.
     * Added in version 1.12.0
     */
    AudioConfig.fromSpeakerOutput = function (player) {
        if (player === undefined) {
            return AudioConfig.fromDefaultSpeakerOutput();
        }
        if (player instanceof Exports_2.SpeakerAudioDestination) {
            return new AudioOutputConfigImpl(player);
        }
        throw new Error("Not Supported Type");
    };
    /**
     * Creates an AudioConfig object representing a specified output audio file
     * @member AudioConfig.fromAudioFileOutput
     * @function
     * @public
     * @param {PathLike} filename - the filename of the output audio file
     * @returns {AudioConfig} The audio output configuration being created.
     * Added in version 1.11.0
     */
    AudioConfig.fromAudioFileOutput = function (filename) {
        return new AudioOutputConfigImpl(new AudioFileWriter_1.AudioFileWriter(filename));
    };
    /**
     * Creates an AudioConfig object representing a specified audio output stream
     * @member AudioConfig.fromStreamOutput
     * @function
     * @public
     * @param {AudioOutputStream | PushAudioOutputStreamCallback} audioStream - Specifies the custom audio output
     *        stream.
     * @returns {AudioConfig} The audio output configuration being created.
     * Added in version 1.11.0
     */
    AudioConfig.fromStreamOutput = function (audioStream) {
        if (audioStream instanceof Exports_2.PushAudioOutputStreamCallback) {
            return new AudioOutputConfigImpl(new AudioOutputStream_1.PushAudioOutputStreamImpl(audioStream));
        }
        if (audioStream instanceof Exports_2.PushAudioOutputStream) {
            return new AudioOutputConfigImpl(audioStream);
        }
        if (audioStream instanceof Exports_2.PullAudioOutputStream) {
            return new AudioOutputConfigImpl(audioStream);
        }
        throw new Error("Not Supported Type");
    };
    return AudioConfig;
}());
exports.AudioConfig = AudioConfig;
/**
 * Represents audio input stream used for custom audio input configurations.
 * @private
 * @class AudioConfigImpl
 */
var AudioConfigImpl = /** @class */ (function (_super) {
    __extends(AudioConfigImpl, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {IAudioSource} source - An audio source.
     */
    function AudioConfigImpl(source) {
        var _this = _super.call(this) || this;
        _this.privSource = source;
        return _this;
    }
    Object.defineProperty(AudioConfigImpl.prototype, "format", {
        /**
         * Format information for the audio
         */
        get: function () {
            return this.privSource.format;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * @member AudioConfigImpl.prototype.close
     * @function
     * @public
     */
    AudioConfigImpl.prototype.close = function (cb, err) {
        this.privSource.turnOff().then(function () {
            if (!!cb) {
                cb();
            }
        }, function (error) {
            if (!!err) {
                err(error);
            }
        });
    };
    /**
     * @member AudioConfigImpl.prototype.id
     * @function
     * @public
     */
    AudioConfigImpl.prototype.id = function () {
        return this.privSource.id();
    };
    Object.defineProperty(AudioConfigImpl.prototype, "blob", {
        /**
         * @member AudioConfigImpl.prototype.blob
         * @function
         * @public
         */
        get: function () {
            return this.privSource.blob;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * @member AudioConfigImpl.prototype.turnOn
     * @function
     * @public
     * @returns {Promise<void>} A promise.
     */
    AudioConfigImpl.prototype.turnOn = function () {
        return this.privSource.turnOn();
    };
    /**
     * @member AudioConfigImpl.prototype.attach
     * @function
     * @public
     * @param {string} audioNodeId - The audio node id.
     * @returns {Promise<IAudioStreamNode>} A promise.
     */
    AudioConfigImpl.prototype.attach = function (audioNodeId) {
        return this.privSource.attach(audioNodeId);
    };
    /**
     * @member AudioConfigImpl.prototype.detach
     * @function
     * @public
     * @param {string} audioNodeId - The audio node id.
     */
    AudioConfigImpl.prototype.detach = function (audioNodeId) {
        return this.privSource.detach(audioNodeId);
    };
    /**
     * @member AudioConfigImpl.prototype.turnOff
     * @function
     * @public
     * @returns {Promise<void>} A promise.
     */
    AudioConfigImpl.prototype.turnOff = function () {
        return this.privSource.turnOff();
    };
    Object.defineProperty(AudioConfigImpl.prototype, "events", {
        /**
         * @member AudioConfigImpl.prototype.events
         * @function
         * @public
         * @returns {EventSource<AudioSourceEvent>} An event source for audio events.
         */
        get: function () {
            return this.privSource.events;
        },
        enumerable: false,
        configurable: true
    });
    AudioConfigImpl.prototype.setProperty = function (name, value) {
        Contracts_1.Contracts.throwIfNull(value, "value");
        if (undefined !== this.privSource.setProperty) {
            this.privSource.setProperty(name, value);
        }
        else {
            throw new Error("This AudioConfig instance does not support setting properties.");
        }
    };
    AudioConfigImpl.prototype.getProperty = function (name, def) {
        if (undefined !== this.privSource.getProperty) {
            return this.privSource.getProperty(name, def);
        }
        else {
            throw new Error("This AudioConfig instance does not support getting properties.");
        }
        return def;
    };
    Object.defineProperty(AudioConfigImpl.prototype, "deviceInfo", {
        get: function () {
            return this.privSource.deviceInfo;
        },
        enumerable: false,
        configurable: true
    });
    return AudioConfigImpl;
}(AudioConfig));
exports.AudioConfigImpl = AudioConfigImpl;
var AudioOutputConfigImpl = /** @class */ (function (_super) {
    __extends(AudioOutputConfigImpl, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {IAudioDestination} destination - An audio destination.
     */
    function AudioOutputConfigImpl(destination) {
        var _this = _super.call(this) || this;
        _this.privDestination = destination;
        return _this;
    }
    Object.defineProperty(AudioOutputConfigImpl.prototype, "format", {
        set: function (format) {
            this.privDestination.format = format;
        },
        enumerable: false,
        configurable: true
    });
    AudioOutputConfigImpl.prototype.write = function (buffer) {
        this.privDestination.write(buffer);
    };
    AudioOutputConfigImpl.prototype.close = function () {
        this.privDestination.close();
    };
    AudioOutputConfigImpl.prototype.id = function () {
        return this.privDestination.id();
    };
    AudioOutputConfigImpl.prototype.setProperty = function (name, value) {
        throw new Error("This AudioConfig instance does not support setting properties.");
    };
    AudioOutputConfigImpl.prototype.getProperty = function (name, def) {
        throw new Error("This AudioConfig instance does not support getting properties.");
    };
    return AudioOutputConfigImpl;
}(AudioConfig));
exports.AudioOutputConfigImpl = AudioOutputConfigImpl;



/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Contracts = void 0;
/**
 * @class Contracts
 * @private
 */
var Contracts = /** @class */ (function () {
    function Contracts() {
    }
    Contracts.throwIfNullOrUndefined = function (param, name) {
        if (param === undefined || param === null) {
            throw new Error("throwIfNullOrUndefined:" + name);
        }
    };
    Contracts.throwIfNull = function (param, name) {
        if (param === null) {
            throw new Error("throwIfNull:" + name);
        }
    };
    Contracts.throwIfNullOrWhitespace = function (param, name) {
        Contracts.throwIfNullOrUndefined(param, name);
        if (("" + param).trim().length < 1) {
            throw new Error("throwIfNullOrWhitespace:" + name);
        }
    };
    Contracts.throwIfDisposed = function (isDisposed) {
        if (isDisposed) {
            throw new Error("the object is already disposed");
        }
    };
    Contracts.throwIfArrayEmptyOrWhitespace = function (array, name) {
        Contracts.throwIfNullOrUndefined(array, name);
        if (array.length === 0) {
            throw new Error("throwIfArrayEmptyOrWhitespace:" + name);
        }
        for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
            var item = array_1[_i];
            Contracts.throwIfNullOrWhitespace(item, name);
        }
    };
    Contracts.throwIfFileDoesNotExist = function (param, name) {
        Contracts.throwIfNullOrWhitespace(param, name);
        // TODO check for file existence.
    };
    Contracts.throwIfNotUndefined = function (param, name) {
        if (param !== undefined) {
            throw new Error("throwIfNotUndefined:" + name);
        }
    };
    return Contracts;
}());
exports.Contracts = Contracts;



/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AudioFileWriter = void 0;
var fs = __importStar(__webpack_require__(65));
var Contracts_1 = __webpack_require__(63);
var AudioFileWriter = /** @class */ (function () {
    function AudioFileWriter(filename) {
        var _this = this;
        this.id = function () {
            return _this.privId;
        };
        Contracts_1.Contracts.throwIfNullOrUndefined(fs.openSync, "\nFile System access not available, please use Push or PullAudioOutputStream");
        this.privFd = fs.openSync(filename, "w");
    }
    Object.defineProperty(AudioFileWriter.prototype, "format", {
        set: function (format) {
            Contracts_1.Contracts.throwIfNotUndefined(this.privAudioFormat, "format is already set");
            this.privAudioFormat = format;
            var headerOffset = 0;
            if (this.privAudioFormat.hasHeader) {
                headerOffset = this.privAudioFormat.header.byteLength;
            }
            if (this.privFd !== undefined) {
                this.privWriteStream = fs.createWriteStream("", { fd: this.privFd, start: headerOffset, autoClose: false });
            }
        },
        enumerable: false,
        configurable: true
    });
    AudioFileWriter.prototype.write = function (buffer) {
        Contracts_1.Contracts.throwIfNullOrUndefined(this.privAudioFormat, "must set format before writing.");
        if (this.privWriteStream !== undefined) {
            this.privWriteStream.write(new Uint8Array(buffer.slice(0)));
        }
    };
    AudioFileWriter.prototype.close = function () {
        var _this = this;
        if (this.privFd !== undefined) {
            this.privWriteStream.on("finish", function () {
                if (_this.privAudioFormat.hasHeader) {
                    _this.privAudioFormat.updateHeader(_this.privWriteStream.bytesWritten);
                    fs.writeSync(_this.privFd, new Int8Array(_this.privAudioFormat.header), 0, _this.privAudioFormat.header.byteLength, 0);
                }
                fs.closeSync(_this.privFd);
                _this.privFd = undefined;
            });
            this.privWriteStream.end();
        }
    };
    return AudioFileWriter;
}());
exports.AudioFileWriter = AudioFileWriter;



/***/ }),
/* 65 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PullAudioInputStreamImpl = exports.PullAudioInputStream = exports.PushAudioInputStreamImpl = exports.PushAudioInputStream = exports.AudioInputStream = void 0;
// tslint:disable:max-classes-per-file
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var Guid_1 = __webpack_require__(7);
var Exports_3 = __webpack_require__(61);
var AudioStreamFormat_1 = __webpack_require__(72);
/**
 * Represents audio input stream used for custom audio input configurations.
 * @class AudioInputStream
 */
var AudioInputStream = /** @class */ (function () {
    /**
     * Creates and initializes an instance.
     * @constructor
     */
    function AudioInputStream() {
    }
    /**
     * Creates a memory backed PushAudioInputStream with the specified audio format.
     * @member AudioInputStream.createPushStream
     * @function
     * @public
     * @param {AudioStreamFormat} format - The audio data format in which audio will be
     *        written to the push audio stream's write() method (Required if format is not 16 kHz 16bit mono PCM).
     * @returns {PushAudioInputStream} The audio input stream being created.
     */
    AudioInputStream.createPushStream = function (format) {
        return PushAudioInputStream.create(format);
    };
    /**
     * Creates a PullAudioInputStream that delegates to the specified callback interface for read()
     * and close() methods.
     * @member AudioInputStream.createPullStream
     * @function
     * @public
     * @param {PullAudioInputStreamCallback} callback - The custom audio input object, derived from
     *        PullAudioInputStreamCallback
     * @param {AudioStreamFormat} format - The audio data format in which audio will be returned from
     *        the callback's read() method (Required if format is not 16 kHz 16bit mono PCM).
     * @returns {PullAudioInputStream} The audio input stream being created.
     */
    AudioInputStream.createPullStream = function (callback, format) {
        return PullAudioInputStream.create(callback, format);
        // throw new Error("Oops");
    };
    return AudioInputStream;
}());
exports.AudioInputStream = AudioInputStream;
/**
 * Represents memory backed push audio input stream used for custom audio input configurations.
 * @class PushAudioInputStream
 */
var PushAudioInputStream = /** @class */ (function (_super) {
    __extends(PushAudioInputStream, _super);
    function PushAudioInputStream() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Creates a memory backed PushAudioInputStream with the specified audio format.
     * @member PushAudioInputStream.create
     * @function
     * @public
     * @param {AudioStreamFormat} format - The audio data format in which audio will be written to the
     *        push audio stream's write() method (Required if format is not 16 kHz 16bit mono PCM).
     * @returns {PushAudioInputStream} The push audio input stream being created.
     */
    PushAudioInputStream.create = function (format) {
        return new PushAudioInputStreamImpl(format);
    };
    return PushAudioInputStream;
}(AudioInputStream));
exports.PushAudioInputStream = PushAudioInputStream;
/**
 * Represents memory backed push audio input stream used for custom audio input configurations.
 * @private
 * @class PushAudioInputStreamImpl
 */
var PushAudioInputStreamImpl = /** @class */ (function (_super) {
    __extends(PushAudioInputStreamImpl, _super);
    /**
     * Creates and initalizes an instance with the given values.
     * @constructor
     * @param {AudioStreamFormat} format - The audio stream format.
     */
    function PushAudioInputStreamImpl(format) {
        var _this = _super.call(this) || this;
        _this.onEvent = function (event) {
            _this.privEvents.onEvent(event);
            Exports_2.Events.instance.onEvent(event);
        };
        if (format === undefined) {
            _this.privFormat = AudioStreamFormat_1.AudioStreamFormatImpl.getDefaultInputFormat();
        }
        else {
            _this.privFormat = format;
        }
        _this.privEvents = new Exports_2.EventSource();
        _this.privId = Guid_1.createNoDashGuid();
        _this.privStream = new Exports_2.ChunkedArrayBufferStream(_this.privFormat.avgBytesPerSec / 10);
        return _this;
    }
    Object.defineProperty(PushAudioInputStreamImpl.prototype, "format", {
        /**
         * Format information for the audio
         */
        get: function () {
            return Promise.resolve(this.privFormat);
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Writes the audio data specified by making an internal copy of the data.
     * @member PushAudioInputStreamImpl.prototype.write
     * @function
     * @public
     * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy.
     */
    PushAudioInputStreamImpl.prototype.write = function (dataBuffer) {
        this.privStream.writeStreamChunk({
            buffer: dataBuffer,
            isEnd: false,
            timeReceived: Date.now()
        });
    };
    /**
     * Closes the stream.
     * @member PushAudioInputStreamImpl.prototype.close
     * @function
     * @public
     */
    PushAudioInputStreamImpl.prototype.close = function () {
        this.privStream.close();
    };
    PushAudioInputStreamImpl.prototype.id = function () {
        return this.privId;
    };
    Object.defineProperty(PushAudioInputStreamImpl.prototype, "blob", {
        get: function () {
            var _this = this;
            return this.attach("id").then(function (audioNode) {
                var data = [];
                var bufferData = Buffer.from("");
                var readCycle = function () {
                    return audioNode.read().then(function (audioStreamChunk) {
                        if (!audioStreamChunk || audioStreamChunk.isEnd) {
                            if (typeof (XMLHttpRequest) !== "undefined" && typeof (Blob) !== "undefined") {
                                return Promise.resolve(new Blob(data));
                            }
                            else {
                                return Promise.resolve(Buffer.from(bufferData));
                            }
                        }
                        else {
                            if (typeof (Blob) !== "undefined") {
                                data.push(audioStreamChunk.buffer);
                            }
                            else {
                                bufferData = Buffer.concat([bufferData, _this.toBuffer(audioStreamChunk.buffer)]);
                            }
                            return readCycle();
                        }
                    });
                };
                return readCycle();
            });
        },
        enumerable: false,
        configurable: true
    });
    PushAudioInputStreamImpl.prototype.turnOn = function () {
        this.onEvent(new Exports_2.AudioSourceInitializingEvent(this.privId)); // no stream id
        this.onEvent(new Exports_2.AudioSourceReadyEvent(this.privId));
        return;
    };
    PushAudioInputStreamImpl.prototype.attach = function (audioNodeId) {
        return __awaiter(this, void 0, void 0, function () {
            var stream;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.onEvent(new Exports_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId));
                        return [4 /*yield*/, this.turnOn()];
                    case 1:
                        _a.sent();
                        stream = this.privStream;
                        this.onEvent(new Exports_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId));
                        return [2 /*return*/, {
                                detach: function () { return __awaiter(_this, void 0, void 0, function () {
                                    return __generator(this, function (_a) {
                                        this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
                                        return [2 /*return*/, this.turnOff()];
                                    });
                                }); },
                                id: function () {
                                    return audioNodeId;
                                },
                                read: function () {
                                    return stream.read();
                                },
                            }];
                }
            });
        });
    };
    PushAudioInputStreamImpl.prototype.detach = function (audioNodeId) {
        this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
    };
    PushAudioInputStreamImpl.prototype.turnOff = function () {
        return;
    };
    Object.defineProperty(PushAudioInputStreamImpl.prototype, "events", {
        get: function () {
            return this.privEvents;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PushAudioInputStreamImpl.prototype, "deviceInfo", {
        get: function () {
            return Promise.resolve({
                bitspersample: this.privFormat.bitsPerSample,
                channelcount: this.privFormat.channels,
                connectivity: Exports_1.connectivity.Unknown,
                manufacturer: "Speech SDK",
                model: "PushStream",
                samplerate: this.privFormat.samplesPerSec,
                type: Exports_1.type.Stream,
            });
        },
        enumerable: false,
        configurable: true
    });
    PushAudioInputStreamImpl.prototype.toBuffer = function (arrayBuffer) {
        var buf = Buffer.alloc(arrayBuffer.byteLength);
        var view = new Uint8Array(arrayBuffer);
        for (var i = 0; i < buf.length; ++i) {
            buf[i] = view[i];
        }
        return buf;
    };
    return PushAudioInputStreamImpl;
}(PushAudioInputStream));
exports.PushAudioInputStreamImpl = PushAudioInputStreamImpl;
/*
 * Represents audio input stream used for custom audio input configurations.
 * @class PullAudioInputStream
 */
var PullAudioInputStream = /** @class */ (function (_super) {
    __extends(PullAudioInputStream, _super);
    /**
     * Creates and initializes and instance.
     * @constructor
     */
    function PullAudioInputStream() {
        return _super.call(this) || this;
    }
    /**
     * Creates a PullAudioInputStream that delegates to the specified callback interface for
     * read() and close() methods, using the default format (16 kHz 16bit mono PCM).
     * @member PullAudioInputStream.create
     * @function
     * @public
     * @param {PullAudioInputStreamCallback} callback - The custom audio input object,
     *        derived from PullAudioInputStreamCustomCallback
     * @param {AudioStreamFormat} format - The audio data format in which audio will be
     *        returned from the callback's read() method (Required if format is not 16 kHz 16bit mono PCM).
     * @returns {PullAudioInputStream} The push audio input stream being created.
     */
    PullAudioInputStream.create = function (callback, format) {
        return new PullAudioInputStreamImpl(callback, format);
    };
    return PullAudioInputStream;
}(AudioInputStream));
exports.PullAudioInputStream = PullAudioInputStream;
/**
 * Represents audio input stream used for custom audio input configurations.
 * @private
 * @class PullAudioInputStreamImpl
 */
var PullAudioInputStreamImpl = /** @class */ (function (_super) {
    __extends(PullAudioInputStreamImpl, _super);
    /**
     * Creates a PullAudioInputStream that delegates to the specified callback interface for
     * read() and close() methods, using the default format (16 kHz 16bit mono PCM).
     * @constructor
     * @param {PullAudioInputStreamCallback} callback - The custom audio input object,
     *        derived from PullAudioInputStreamCustomCallback
     * @param {AudioStreamFormat} format - The audio data format in which audio will be
     *        returned from the callback's read() method (Required if format is not 16 kHz 16bit mono PCM).
     */
    function PullAudioInputStreamImpl(callback, format) {
        var _this = _super.call(this) || this;
        _this.onEvent = function (event) {
            _this.privEvents.onEvent(event);
            Exports_2.Events.instance.onEvent(event);
        };
        if (undefined === format) {
            _this.privFormat = Exports_3.AudioStreamFormat.getDefaultInputFormat();
        }
        else {
            _this.privFormat = format;
        }
        _this.privEvents = new Exports_2.EventSource();
        _this.privId = Guid_1.createNoDashGuid();
        _this.privCallback = callback;
        _this.privIsClosed = false;
        _this.privBufferSize = _this.privFormat.avgBytesPerSec / 10;
        return _this;
    }
    Object.defineProperty(PullAudioInputStreamImpl.prototype, "format", {
        /**
         * Format information for the audio
         */
        get: function () {
            return Promise.resolve(this.privFormat);
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Closes the stream.
     * @member PullAudioInputStreamImpl.prototype.close
     * @function
     * @public
     */
    PullAudioInputStreamImpl.prototype.close = function () {
        this.privIsClosed = true;
        this.privCallback.close();
    };
    PullAudioInputStreamImpl.prototype.id = function () {
        return this.privId;
    };
    Object.defineProperty(PullAudioInputStreamImpl.prototype, "blob", {
        get: function () {
            return Promise.reject("Not implemented");
        },
        enumerable: false,
        configurable: true
    });
    PullAudioInputStreamImpl.prototype.turnOn = function () {
        this.onEvent(new Exports_2.AudioSourceInitializingEvent(this.privId)); // no stream id
        this.onEvent(new Exports_2.AudioSourceReadyEvent(this.privId));
        return;
    };
    PullAudioInputStreamImpl.prototype.attach = function (audioNodeId) {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.onEvent(new Exports_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId));
                        return [4 /*yield*/, this.turnOn()];
                    case 1:
                        _a.sent();
                        this.onEvent(new Exports_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId));
                        return [2 /*return*/, {
                                detach: function () {
                                    _this.privCallback.close();
                                    _this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(_this.privId, audioNodeId));
                                    return _this.turnOff();
                                },
                                id: function () {
                                    return audioNodeId;
                                },
                                read: function () {
                                    var totalBytes = 0;
                                    var transmitBuff;
                                    // Until we have the minimum number of bytes to send in a transmission, keep asking for more.
                                    while (totalBytes < _this.privBufferSize) {
                                        // Sizing the read buffer to the delta between the perfect size and what's left means we won't ever get too much
                                        // data back.
                                        var readBuff = new ArrayBuffer(_this.privBufferSize - totalBytes);
                                        var pulledBytes = _this.privCallback.read(readBuff);
                                        // If there is no return buffer yet defined, set the return buffer to the that was just populated.
                                        // This was, if we have enough data there's no copy penalty, but if we don't we have a buffer that's the
                                        // preferred size allocated.
                                        if (undefined === transmitBuff) {
                                            transmitBuff = readBuff;
                                        }
                                        else {
                                            // Not the first bite at the apple, so fill the return buffer with the data we got back.
                                            var intView = new Int8Array(transmitBuff);
                                            intView.set(new Int8Array(readBuff), totalBytes);
                                        }
                                        // If there are no bytes to read, just break out and be done.
                                        if (0 === pulledBytes) {
                                            break;
                                        }
                                        totalBytes += pulledBytes;
                                    }
                                    return Promise.resolve({
                                        buffer: transmitBuff.slice(0, totalBytes),
                                        isEnd: _this.privIsClosed || totalBytes === 0,
                                        timeReceived: Date.now(),
                                    });
                                },
                            }];
                }
            });
        });
    };
    PullAudioInputStreamImpl.prototype.detach = function (audioNodeId) {
        this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
    };
    PullAudioInputStreamImpl.prototype.turnOff = function () {
        return;
    };
    Object.defineProperty(PullAudioInputStreamImpl.prototype, "events", {
        get: function () {
            return this.privEvents;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PullAudioInputStreamImpl.prototype, "deviceInfo", {
        get: function () {
            return Promise.resolve({
                bitspersample: this.privFormat.bitsPerSample,
                channelcount: this.privFormat.channels,
                connectivity: Exports_1.connectivity.Unknown,
                manufacturer: "Speech SDK",
                model: "PullStream",
                samplerate: this.privFormat.samplesPerSec,
                type: Exports_1.type.Stream,
            });
        },
        enumerable: false,
        configurable: true
    });
    return PullAudioInputStreamImpl;
}(PullAudioInputStream));
exports.PullAudioInputStreamImpl = PullAudioInputStreamImpl;


/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(67).Buffer))

/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <http://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */



var base64 = __webpack_require__(69)
var ieee754 = __webpack_require__(70)
var isArray = __webpack_require__(71)

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 () { 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() < length) {
    throw new RangeError('Invalid typed array length')
  }
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    // Return an augmented `Uint8Array` instance, for best performance
    that = new Uint8Array(length)
    that.__proto__ = Buffer.prototype
  } else {
    // Fallback: Return an object instance of the Buffer class
    if (that === null) {
      that = new Buffer(length)
    }
    that.length = length
  }

  return that
}

/**
 * The Buffer constructor returns instances of `Uint8Array` that have their
 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 * returns a single octet.
 *
 * The `Uint8Array` prototype remains unmodified.
 */

function Buffer (arg, encodingOrOffset, length) {
  if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
    return new Buffer(arg, encodingOrOffset, length)
  }

  // Common case.
  if (typeof arg === 'number') {
    if (typeof encodingOrOffset === 'string') {
      throw new Error(
        'If encoding is specified then the first argument must be a string'
      )
    }
    return allocUnsafe(this, arg)
  }
  return from(this, arg, encodingOrOffset, length)
}

Buffer.poolSize = 8192 // not used by this implementation

// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
  arr.__proto__ = Buffer.prototype
  return arr
}

function from (that, value, encodingOrOffset, length) {
  if (typeof value === 'number') {
    throw new TypeError('"value" argument must not be a number')
  }

  if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
    return fromArrayBuffer(that, value, encodingOrOffset, length)
  }

  if (typeof value === 'string') {
    return fromString(that, value, encodingOrOffset)
  }

  return fromObject(that, value)
}

/**
 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 * if value is a number.
 * Buffer.from(str[, encoding])
 * Buffer.from(array)
 * Buffer.from(buffer)
 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 **/
Buffer.from = function (value, encodingOrOffset, length) {
  return from(null, value, encodingOrOffset, length)
}

if (Buffer.TYPED_ARRAY_SUPPORT) {
  Buffer.prototype.__proto__ = Uint8Array.prototype
  Buffer.__proto__ = Uint8Array
  if (typeof Symbol !== 'undefined' && Symbol.species &&
      Buffer[Symbol.species] === Buffer) {
    // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
    Object.defineProperty(Buffer, Symbol.species, {
      value: null,
      configurable: true
    })
  }
}

function assertSize (size) {
  if (typeof size !== 'number') {
    throw new TypeError('"size" argument must be a number')
  } else if (size < 0) {
    throw new RangeError('"size" argument must not be negative')
  }
}

function alloc (that, size, fill, encoding) {
  assertSize(size)
  if (size <= 0) {
    return createBuffer(that, size)
  }
  if (fill !== undefined) {
    // Only pay attention to encoding if it's a string. This
    // prevents accidentally sending in a number that would
    // be interpretted as a start offset.
    return typeof encoding === 'string'
      ? createBuffer(that, size).fill(fill, encoding)
      : createBuffer(that, size).fill(fill)
  }
  return createBuffer(that, size)
}

/**
 * Creates a new filled Buffer instance.
 * alloc(size[, fill[, encoding]])
 **/
Buffer.alloc = function (size, fill, encoding) {
  return alloc(null, size, fill, encoding)
}

function allocUnsafe (that, size) {
  assertSize(size)
  that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  if (!Buffer.TYPED_ARRAY_SUPPORT) {
    for (var i = 0; i < size; ++i) {
      that[i] = 0
    }
  }
  return that
}

/**
 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 * */
Buffer.allocUnsafe = function (size) {
  return allocUnsafe(null, size)
}
/**
 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 */
Buffer.allocUnsafeSlow = function (size) {
  return allocUnsafe(null, size)
}

function fromString (that, string, encoding) {
  if (typeof encoding !== 'string' || encoding === '') {
    encoding = 'utf8'
  }

  if (!Buffer.isEncoding(encoding)) {
    throw new TypeError('"encoding" must be a valid string encoding')
  }

  var length = byteLength(string, encoding) | 0
  that = createBuffer(that, length)

  var actual = that.write(string, encoding)

  if (actual !== length) {
    // Writing a hex string, for example, that contains invalid characters will
    // cause everything after the first invalid character to be ignored. (e.g.
    // 'abxxcd' will be treated as 'ab')
    that = that.slice(0, actual)
  }

  return that
}

function fromArrayLike (that, array) {
  var length = array.length < 0 ? 0 : checked(array.length) | 0
  that = createBuffer(that, length)
  for (var i = 0; i < length; i += 1) {
    that[i] = array[i] & 255
  }
  return that
}

function fromArrayBuffer (that, array, byteOffset, length) {
  array.byteLength // this throws if `array` is not a valid ArrayBuffer

  if (byteOffset < 0 || array.byteLength < byteOffset) {
    throw new RangeError('\'offset\' is out of bounds')
  }

  if (array.byteLength < byteOffset + (length || 0)) {
    throw new RangeError('\'length\' is out of bounds')
  }

  if (byteOffset === undefined && length === undefined) {
    array = new Uint8Array(array)
  } else if (length === undefined) {
    array = new Uint8Array(array, byteOffset)
  } else {
    array = new Uint8Array(array, byteOffset, length)
  }

  if (Buffer.TYPED_ARRAY_SUPPORT) {
    // Return an augmented `Uint8Array` instance, for best performance
    that = array
    that.__proto__ = Buffer.prototype
  } else {
    // Fallback: Return an object instance of the Buffer class
    that = fromArrayLike(that, array)
  }
  return that
}

function fromObject (that, obj) {
  if (Buffer.isBuffer(obj)) {
    var len = checked(obj.length) | 0
    that = createBuffer(that, len)

    if (that.length === 0) {
      return that
    }

    obj.copy(that, 0, 0, len)
    return that
  }

  if (obj) {
    if ((typeof ArrayBuffer !== 'undefined' &&
        obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
      if (typeof obj.length !== 'number' || isnan(obj.length)) {
        return createBuffer(that, 0)
      }
      return fromArrayLike(that, obj)
    }

    if (obj.type === 'Buffer' && isArray(obj.data)) {
      return fromArrayLike(that, obj.data)
    }
  }

  throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}

function checked (length) {
  // Note: cannot use `length < kMaxLength()` here because that fails when
  // length is NaN (which is otherwise coerced to zero.)
  if (length >= 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 < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i]
      y = b[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

Buffer.isEncoding = function isEncoding (encoding) {
  switch (String(encoding).toLowerCase()) {
    case 'hex':
    case 'utf8':
    case 'utf-8':
    case 'ascii':
    case 'latin1':
    case 'binary':
    case 'base64':
    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return true
    default:
      return false
  }
}

Buffer.concat = function concat (list, length) {
  if (!isArray(list)) {
    throw new TypeError('"list" argument must be an Array of Buffers')
  }

  if (list.length === 0) {
    return Buffer.alloc(0)
  }

  var i
  if (length === undefined) {
    length = 0
    for (i = 0; i < list.length; ++i) {
      length += list[i].length
    }
  }

  var buffer = Buffer.allocUnsafe(length)
  var pos = 0
  for (i = 0; i < list.length; ++i) {
    var buf = list[i]
    if (!Buffer.isBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers')
    }
    buf.copy(buffer, pos)
    pos += buf.length
  }
  return buffer
}

function byteLength (string, encoding) {
  if (Buffer.isBuffer(string)) {
    return string.length
  }
  if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
      (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
    return string.byteLength
  }
  if (typeof string !== 'string') {
    string = '' + string
  }

  var len = string.length
  if (len === 0) return 0

  // Use a for loop to avoid recursion
  var loweredCase = false
  for (;;) {
    switch (encoding) {
      case 'ascii':
      case 'latin1':
      case 'binary':
        return len
      case 'utf8':
      case 'utf-8':
      case undefined:
        return utf8ToBytes(string).length
      case 'ucs2':
      case 'ucs-2':
      case 'utf16le':
      case 'utf-16le':
        return len * 2
      case 'hex':
        return len >>> 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; i < len; i += 2) {
    swap(this, i, i + 1)
  }
  return this
}

Buffer.prototype.swap32 = function swap32 () {
  var len = this.length
  if (len % 4 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 32-bits')
  }
  for (var i = 0; i < len; i += 4) {
    swap(this, i, i + 3)
    swap(this, i + 1, i + 2)
  }
  return this
}

Buffer.prototype.swap64 = function swap64 () {
  var len = this.length
  if (len % 8 !== 0) {
    throw new RangeError('Buffer size must be a multiple of 64-bits')
  }
  for (var i = 0; i < len; i += 8) {
    swap(this, i, i + 7)
    swap(this, i + 1, i + 6)
    swap(this, i + 2, i + 5)
    swap(this, i + 3, i + 4)
  }
  return this
}

Buffer.prototype.toString = function toString () {
  var length = this.length | 0
  if (length === 0) return ''
  if (arguments.length === 0) return utf8Slice(this, 0, length)
  return slowToString.apply(this, arguments)
}

Buffer.prototype.equals = function equals (b) {
  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  if (this === b) return true
  return Buffer.compare(this, b) === 0
}

Buffer.prototype.inspect = function inspect () {
  var str = ''
  var max = exports.INSPECT_MAX_BYTES
  if (this.length > 0) {
    str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
    if (this.length > max) str += ' ... '
  }
  return '<Buffer ' + str + '>'
}

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 < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i]
      y = targetCopy[i]
      break
    }
  }

  if (x < y) return -1
  if (y < x) return 1
  return 0
}

// Finds either the first index of `val` in `buffer` at offset >= `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; i < arrLength; i++) {
      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1) foundIndex = i
        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
      } else {
        if (foundIndex !== -1) i -= i - foundIndex
        foundIndex = -1
      }
    }
  } else {
    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
    for (i = byteOffset; i >= 0; i--) {
      var found = true
      for (var j = 0; j < valLength; j++) {
        if (read(arr, i + j) !== read(val, j)) {
          found = false
          break
        }
      }
      if (found) return i
    }
  }

  return -1
}

Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1
}

Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}

Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}

function hexWrite (buf, string, offset, length) {
  offset = Number(offset) || 0
  var remaining = buf.length - offset
  if (!length) {
    length = remaining
  } else {
    length = Number(length)
    if (length > remaining) {
      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; i < length; ++i) {
    var parsed = parseInt(string.substr(i * 2, 2), 16)
    if (isNaN(parsed)) return i
    buf[offset + i] = parsed
  }
  return i
}

function utf8Write (buf, string, offset, length) {
  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}

function asciiWrite (buf, string, offset, length) {
  return blitBuffer(asciiToBytes(string), buf, offset, length)
}

function latin1Write (buf, string, offset, length) {
  return asciiWrite(buf, string, offset, length)
}

function base64Write (buf, string, offset, length) {
  return blitBuffer(base64ToBytes(string), buf, offset, length)
}

function ucs2Write (buf, string, offset, length) {
  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}

Buffer.prototype.write = function write (string, offset, length, encoding) {
  // Buffer#write(string)
  if (offset === undefined) {
    encoding = 'utf8'
    length = this.length
    offset = 0
  // Buffer#write(string, encoding)
  } else if (length === undefined && typeof offset === 'string') {
    encoding = offset
    length = this.length
    offset = 0
  // Buffer#write(string, offset[, length][, encoding])
  } else if (isFinite(offset)) {
    offset = offset | 0
    if (isFinite(length)) {
      length = length | 0
      if (encoding === undefined) encoding = 'utf8'
    } else {
      encoding = length
      length = undefined
    }
  // legacy write(string, encoding, offset, length) - remove in v0.13
  } else {
    throw new Error(
      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
    )
  }

  var remaining = this.length - offset
  if (length === undefined || length > remaining) 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 (i < end) {
    var firstByte = buf[i]
    var codePoint = null
    var bytesPerSequence = (firstByte > 0xEF) ? 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 (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    )
  }
  return res
}

function asciiSlice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 0x7F)
  }
  return ret
}

function latin1Slice (buf, start, end) {
  var ret = ''
  end = Math.min(buf.length, end)

  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i])
  }
  return ret
}

function hexSlice (buf, start, end) {
  var len = buf.length

  if (!start || start < 0) start = 0
  if (!end || end < 0 || end > len) end = len

  var out = ''
  for (var i = start; i < end; ++i) {
    out += toHex(buf[i])
  }
  return out
}

function utf16leSlice (buf, start, end) {
  var bytes = buf.slice(start, end)
  var res = ''
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  }
  return res
}

Buffer.prototype.slice = function slice (start, end) {
  var len = this.length
  start = ~~start
  end = end === undefined ? len : ~~end

  if (start < 0) {
    start += len
    if (start < 0) start = 0
  } else if (start > len) {
    start = len
  }

  if (end < 0) {
    end += len
    if (end < 0) end = 0
  } else if (end > len) {
    end = len
  }

  if (end < start) end = start

  var newBuf
  if (Buffer.TYPED_ARRAY_SUPPORT) {
    newBuf = this.subarray(start, end)
    newBuf.__proto__ = Buffer.prototype
  } else {
    var sliceLen = end - start
    newBuf = new Buffer(sliceLen, undefined)
    for (var i = 0; i < sliceLen; ++i) {
      newBuf[i] = this[i + start]
    }
  }

  return newBuf
}

/*
 * Need to make sure that buffer isn't trying to write out of bounds.
 */
function checkOffset (offset, ext, length) {
  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  if (offset + ext > length) 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 (++i < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }

  return val
}

Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  offset = offset | 0
  byteLength = byteLength | 0
  if (!noAssert) {
    checkOffset(offset, byteLength, this.length)
  }

  var val = this[offset + --byteLength]
  var mul = 1
  while (byteLength > 0 && (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 < byteLength && (mul *= 0x100)) {
    val += this[offset + i] * mul
  }
  mul *= 0x80

  if (val >= 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 || value < min) throw new RangeError('"value" argument is out of bounds')
  if (offset + ext > buf.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 < byteLength && (mul *= 0x100)) {
    this[offset + i] = (value / mul) & 0xFF
  }

  return offset + byteLength
}

Buffer.prototype.writeUIntBE = function writeUIntBE (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 i = byteLength - 1
  var mul = 1
  this[offset + i] = 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 < j; ++i) {
    buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - 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 < j; ++i) {
    buf[offset + i] = (value >>> (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 < byteLength && (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.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 < start) end = start

  // Copy 0 bytes; we're done
  if (end === start) return 0
  if (target.length === 0 || this.length === 0) return 0

  // Fatal error conditions
  if (targetStart < 0) {
    throw new RangeError('targetStart out of bounds')
  }
  if (start < 0 || start >= 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 < end - start) {
    end = target.length - targetStart + start
  }

  var len = end - start
  var i

  if (this === target && start < targetStart && targetStart < end) {
    // descending copy from end
    for (i = len - 1; i >= 0; --i) {
      target[i + targetStart] = this[i + start]
    }
  } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
    // ascending copy from start
    for (i = 0; i < len; ++i) {
      target[i + targetStart] = this[i + start]
    }
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, start + len),
      targetStart
    )
  }

  return len
}

// Usage:
//    buffer.fill(number[, offset[, end]])
//    buffer.fill(buffer[, offset[, end]])
//    buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
  // Handle string cases:
  if (typeof val === 'string') {
    if (typeof start === 'string') {
      encoding = start
      start = 0
      end = this.length
    } else if (typeof end === 'string') {
      encoding = end
      end = this.length
    }
    if (val.length === 1) {
      var code = val.charCodeAt(0)
      if (code < 256) {
        val = code
      }
    }
    if (encoding !== undefined && typeof encoding !== 'string') {
      throw new TypeError('encoding must be a string')
    }
    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
      throw new TypeError('Unknown encoding: ' + encoding)
    }
  } else if (typeof val === 'number') {
    val = val & 255
  }

  // Invalid ranges are not set to a default, so can range check early.
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError('Out of range index')
  }

  if (end <= start) {
    return this
  }

  start = start >>> 0
  end = end === undefined ? this.length : end >>> 0

  if (!val) val = 0

  var i
  if (typeof val === 'number') {
    for (i = start; i < end; ++i) {
      this[i] = val
    }
  } else {
    var bytes = Buffer.isBuffer(val)
      ? val
      : utf8ToBytes(new Buffer(val, encoding).toString())
    var len = bytes.length
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len]
    }
  }

  return this
}

// HELPER FUNCTIONS
// ================

var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g

function base64clean (str) {
  // Node strips out invalid characters like \n and \t from the string, base64-js does not
  str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  // Node converts strings with length < 2 to ''
  if (str.length < 2) return ''
  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  while (str.length % 4 !== 0) {
    str = str + '='
  }
  return str
}

function stringtrim (str) {
  if (str.trim) return str.trim()
  return str.replace(/^\s+|\s+$/g, '')
}

function toHex (n) {
  if (n < 16) return '0' + n.toString(16)
  return n.toString(16)
}

function utf8ToBytes (string, units) {
  units = units || Infinity
  var codePoint
  var length = string.length
  var leadSurrogate = null
  var bytes = []

  for (var i = 0; i < length; ++i) {
    codePoint = string.charCodeAt(i)

    // is surrogate component
    if (codePoint > 0xD7FF && 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 < str.length; ++i) {
    // Node's code seems to be doing this and not & 0x7F..
    byteArray.push(str.charCodeAt(i) & 0xFF)
  }
  return byteArray
}

function utf16leToBytes (str, units) {
  var c, hi, lo
  var byteArray = []
  for (var i = 0; i < str.length; ++i) {
    if ((units -= 2) < 0) break

    c = str.charCodeAt(i)
    hi = c >> 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 < length; ++i) {
    if ((i + offset >= 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
}

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(68)))

/***/ }),
/* 68 */
/***/ (function(module, exports) {

var g;

// This works in non-strict mode
g = (function() {
	return this;
})();

try {
	// This works if eval is allowed (see CSP)
	g = g || new Function("return this")();
} catch (e) {
	// This works if the window reference is available
	if (typeof window === "object") g = window;
}

// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}

module.exports = g;


/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {

"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; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    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 < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 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; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? 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('')
}


/***/ }),
/* 70 */
/***/ (function(module, exports) {

/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 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 << eLen) - 1
  var eBias = eMax >> 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 << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}


/***/ }),
/* 71 */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};


/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.AudioStreamFormatImpl = exports.AudioStreamFormat = exports.AudioFormatTag = void 0;
var AudioFormatTag;
(function (AudioFormatTag) {
    AudioFormatTag[AudioFormatTag["PCM"] = 1] = "PCM";
    AudioFormatTag[AudioFormatTag["MuLaw"] = 2] = "MuLaw";
    AudioFormatTag[AudioFormatTag["Siren"] = 3] = "Siren";
    AudioFormatTag[AudioFormatTag["MP3"] = 4] = "MP3";
    AudioFormatTag[AudioFormatTag["SILKSkype"] = 5] = "SILKSkype";
    AudioFormatTag[AudioFormatTag["OGG_OPUS"] = 6] = "OGG_OPUS";
    AudioFormatTag[AudioFormatTag["WEBM_OPUS"] = 7] = "WEBM_OPUS";
    AudioFormatTag[AudioFormatTag["ALaw"] = 8] = "ALaw";
    AudioFormatTag[AudioFormatTag["FLAC"] = 9] = "FLAC";
    AudioFormatTag[AudioFormatTag["OPUS"] = 10] = "OPUS";
})(AudioFormatTag = exports.AudioFormatTag || (exports.AudioFormatTag = {}));
/**
 * Represents audio stream format used for custom audio input configurations.
 * @class AudioStreamFormat
 */
var AudioStreamFormat = /** @class */ (function () {
    function AudioStreamFormat() {
    }
    /**
     * Creates an audio stream format object representing the default audio stream
     * format (16KHz 16bit mono PCM).
     * @member AudioStreamFormat.getDefaultInputFormat
     * @function
     * @public
     * @returns {AudioStreamFormat} The audio stream format being created.
     */
    AudioStreamFormat.getDefaultInputFormat = function () {
        return AudioStreamFormatImpl.getDefaultInputFormat();
    };
    /**
     * Creates an audio stream format object with the specified format characteristics.
     * @member AudioStreamFormat.getWaveFormat
     * @function
     * @public
     * @param {number} samplesPerSecond - Sample rate, in samples per second (Hertz).
     * @param {number} bitsPerSample - Bits per sample, typically 16.
     * @param {number} channels - Number of channels in the waveform-audio data. Monaural data
     *        uses one channel and stereo data uses two channels.
     * @param {AudioFormatTag} format - Audio format (PCM, alaw or mulaw).
     * @returns {AudioStreamFormat} The audio stream format being created.
     */
    AudioStreamFormat.getWaveFormat = function (samplesPerSecond, bitsPerSample, channels, format) {
        return new AudioStreamFormatImpl(samplesPerSecond, bitsPerSample, channels, format);
    };
    /**
     * Creates an audio stream format object with the specified pcm waveformat characteristics.
     * @member AudioStreamFormat.getWaveFormatPCM
     * @function
     * @public
     * @param {number} samplesPerSecond - Sample rate, in samples per second (Hertz).
     * @param {number} bitsPerSample - Bits per sample, typically 16.
     * @param {number} channels - Number of channels in the waveform-audio data. Monaural data
     *        uses one channel and stereo data uses two channels.
     * @returns {AudioStreamFormat} The audio stream format being created.
     */
    AudioStreamFormat.getWaveFormatPCM = function (samplesPerSecond, bitsPerSample, channels) {
        return new AudioStreamFormatImpl(samplesPerSecond, bitsPerSample, channels);
    };
    return AudioStreamFormat;
}());
exports.AudioStreamFormat = AudioStreamFormat;
/**
 * @private
 * @class AudioStreamFormatImpl
 */
// tslint:disable-next-line:max-classes-per-file
var AudioStreamFormatImpl = /** @class */ (function (_super) {
    __extends(AudioStreamFormatImpl, _super);
    /**
     * Creates an instance with the given values.
     * @constructor
     * @param {number} samplesPerSec - Samples per second.
     * @param {number} bitsPerSample - Bits per sample.
     * @param {number} channels - Number of channels.
     * @param {AudioFormatTag} format - Audio format (PCM, alaw or mulaw).
     */
    function AudioStreamFormatImpl(samplesPerSec, bitsPerSample, channels, format) {
        if (samplesPerSec === void 0) { samplesPerSec = 16000; }
        if (bitsPerSample === void 0) { bitsPerSample = 16; }
        if (channels === void 0) { channels = 1; }
        if (format === void 0) { format = AudioFormatTag.PCM; }
        var _this = _super.call(this) || this;
        _this.setString = function (view, offset, str) {
            for (var i = 0; i < str.length; i++) {
                view.setUint8(offset + i, str.charCodeAt(i));
            }
        };
        var isWavFormat = true;
        /* 1 for PCM; 6 for alaw; 7 for mulaw */
        switch (format) {
            case AudioFormatTag.PCM:
                _this.formatTag = 1;
                break;
            case AudioFormatTag.ALaw:
                _this.formatTag = 6;
                break;
            case AudioFormatTag.MuLaw:
                _this.formatTag = 7;
                break;
            default:
                isWavFormat = false;
        }
        _this.bitsPerSample = bitsPerSample;
        _this.samplesPerSec = samplesPerSec;
        _this.channels = channels;
        _this.avgBytesPerSec = _this.samplesPerSec * _this.channels * (_this.bitsPerSample / 8);
        _this.blockAlign = _this.channels * Math.max(_this.bitsPerSample, 8);
        if (isWavFormat) {
            _this.privHeader = new ArrayBuffer(44);
            // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
            var view = new DataView(_this.privHeader);
            /* RIFF identifier */
            _this.setString(view, 0, "RIFF");
            /* file length */
            view.setUint32(4, 0, true);
            /* RIFF type & Format */
            _this.setString(view, 8, "WAVEfmt ");
            /* format chunk length */
            view.setUint32(16, 16, true);
            /* audio format */
            view.setUint16(20, _this.formatTag, true);
            /* channel count */
            view.setUint16(22, _this.channels, true);
            /* sample rate */
            view.setUint32(24, _this.samplesPerSec, true);
            /* byte rate (sample rate * block align) */
            view.setUint32(28, _this.avgBytesPerSec, true);
            /* block align (channel count * bytes per sample) */
            view.setUint16(32, _this.channels * (_this.bitsPerSample / 8), true);
            /* bits per sample */
            view.setUint16(34, _this.bitsPerSample, true);
            /* data chunk identifier */
            _this.setString(view, 36, "data");
            /* data chunk length */
            view.setUint32(40, 0, true);
        }
        return _this;
    }
    /**
     * Retrieves the default input format.
     * @member AudioStreamFormatImpl.getDefaultInputFormat
     * @function
     * @public
     * @returns {AudioStreamFormatImpl} The default input format.
     */
    AudioStreamFormatImpl.getDefaultInputFormat = function () {
        return new AudioStreamFormatImpl();
    };
    /**
     * Creates an audio context appropriate to current browser
     * @member AudioStreamFormatImpl.getAudioContext
     * @function
     * @public
     * @returns {AudioContext} An audio context instance
     */
    AudioStreamFormatImpl.getAudioContext = function (sampleRate) {
        // Workaround for Speech SDK bug in Safari.
        var AudioContext = window.AudioContext // our preferred impl
            || window.webkitAudioContext // fallback, mostly when on Safari
            || false; // could not find.
        // https://developer.mozilla.org/en-US/docs/Web/API/AudioContext
        if (!!AudioContext) {
            if (sampleRate !== undefined && navigator.mediaDevices.getSupportedConstraints().sampleRate) {
                return new AudioContext({ sampleRate: sampleRate });
            }
            else {
                return new AudioContext();
            }
        }
        else {
            throw new Error("Browser does not support Web Audio API (AudioContext is not available).");
        }
    };
    /**
     * Closes the configuration object.
     * @member AudioStreamFormatImpl.prototype.close
     * @function
     * @public
     */
    AudioStreamFormatImpl.prototype.close = function () { return; };
    Object.defineProperty(AudioStreamFormatImpl.prototype, "header", {
        get: function () {
            return this.privHeader;
        },
        enumerable: false,
        configurable: true
    });
    return AudioStreamFormatImpl;
}(AudioStreamFormat));
exports.AudioStreamFormatImpl = AudioStreamFormatImpl;



/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PushAudioOutputStreamImpl = exports.PushAudioOutputStream = exports.PullAudioOutputStreamImpl = exports.PullAudioOutputStream = exports.AudioOutputStream = void 0;
// tslint:disable:max-classes-per-file
var Exports_1 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var AudioOutputFormat_1 = __webpack_require__(74);
/**
 * Represents audio output stream used for custom audio output configurations.
 * @class AudioOutputStream
 */
var AudioOutputStream = /** @class */ (function () {
    /**
     * Creates and initializes an instance.
     * @constructor
     */
    function AudioOutputStream() {
    }
    /**
     * Creates a memory backed PullAudioOutputStream with the specified audio format.
     * @member AudioOutputStream.createPullStream
     * @function
     * @public
     * @returns {PullAudioOutputStream} The audio output stream being created.
     */
    AudioOutputStream.createPullStream = function () {
        return PullAudioOutputStream.create();
    };
    return AudioOutputStream;
}());
exports.AudioOutputStream = AudioOutputStream;
/**
 * Represents memory backed push audio output stream used for custom audio output configurations.
 * @class PullAudioOutputStream
 */
var PullAudioOutputStream = /** @class */ (function (_super) {
    __extends(PullAudioOutputStream, _super);
    function PullAudioOutputStream() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /**
     * Creates a memory backed PullAudioOutputStream with the specified audio format.
     * @member PullAudioOutputStream.create
     * @function
     * @public
     * @returns {PullAudioOutputStream} The push audio output stream being created.
     */
    PullAudioOutputStream.create = function () {
        return new PullAudioOutputStreamImpl();
    };
    return PullAudioOutputStream;
}(AudioOutputStream));
exports.PullAudioOutputStream = PullAudioOutputStream;
/**
 * Represents memory backed push audio output stream used for custom audio output configurations.
 * @private
 * @class PullAudioOutputStreamImpl
 */
var PullAudioOutputStreamImpl = /** @class */ (function (_super) {
    __extends(PullAudioOutputStreamImpl, _super);
    /**
     * Creates and initializes an instance with the given values.
     * @constructor
     */
    function PullAudioOutputStreamImpl() {
        var _this = _super.call(this) || this;
        _this.privId = Exports_1.createNoDashGuid();
        _this.privStream = new Exports_1.Stream();
        return _this;
    }
    Object.defineProperty(PullAudioOutputStreamImpl.prototype, "format", {
        /**
         * Format information for the audio
         */
        get: function () {
            return this.privFormat;
        },
        /**
         * Sets the format information to the stream. For internal use only.
         * @param {AudioStreamFormat} format - the format to be set.
         */
        set: function (format) {
            if (format === undefined || format === null) {
                this.privFormat = AudioOutputFormat_1.AudioOutputFormatImpl.getDefaultOutputFormat();
            }
            this.privFormat = format;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PullAudioOutputStreamImpl.prototype, "isClosed", {
        /**
         * Checks if the stream is closed
         * @member PullAudioOutputStreamImpl.prototype.isClosed
         * @property
         * @public
         */
        get: function () {
            return this.privStream.isClosed;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Gets the id of the stream
     * @member PullAudioOutputStreamImpl.prototype.id
     * @property
     * @public
     */
    PullAudioOutputStreamImpl.prototype.id = function () {
        return this.privId;
    };
    /**
     * Reads audio data from the internal buffer.
     * @member PullAudioOutputStreamImpl.prototype.read
     * @function
     * @public
     * @param {ArrayBuffer} dataBuffer - An ArrayBuffer to store the read data.
     * @returns {Promise<number>} - Audio buffer length has been read.
     */
    PullAudioOutputStreamImpl.prototype.read = function (dataBuffer) {
        return __awaiter(this, void 0, void 0, function () {
            var intView, totalBytes, chunk, tmpBuffer;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        intView = new Int8Array(dataBuffer);
                        totalBytes = 0;
                        if (this.privLastChunkView !== undefined) {
                            if (this.privLastChunkView.length > dataBuffer.byteLength) {
                                intView.set(this.privLastChunkView.slice(0, dataBuffer.byteLength));
                                this.privLastChunkView = this.privLastChunkView.slice(dataBuffer.byteLength);
                                return [2 /*return*/, Promise.resolve(dataBuffer.byteLength)];
                            }
                            intView.set(this.privLastChunkView);
                            totalBytes = this.privLastChunkView.length;
                            this.privLastChunkView = undefined;
                        }
                        _a.label = 1;
                    case 1:
                        if (!(totalBytes < dataBuffer.byteLength && !this.privStream.isReadEnded)) return [3 /*break*/, 6];
                        return [4 /*yield*/, this.privStream.read()];
                    case 2:
                        chunk = _a.sent();
                        if (!(chunk !== undefined && !chunk.isEnd)) return [3 /*break*/, 3];
                        tmpBuffer = void 0;
                        if (chunk.buffer.byteLength > dataBuffer.byteLength - totalBytes) {
                            tmpBuffer = chunk.buffer.slice(0, dataBuffer.byteLength - totalBytes);
                            this.privLastChunkView = new Int8Array(chunk.buffer.slice(dataBuffer.byteLength - totalBytes));
                        }
                        else {
                            tmpBuffer = chunk.buffer;
                        }
                        intView.set(new Int8Array(tmpBuffer), totalBytes);
                        totalBytes += tmpBuffer.byteLength;
                        return [3 /*break*/, 5];
                    case 3: return [4 /*yield*/, this.privStream.readEnded()];
                    case 4:
                        _a.sent();
                        _a.label = 5;
                    case 5: return [3 /*break*/, 1];
                    case 6: return [2 /*return*/, totalBytes];
                }
            });
        });
    };
    /**
     * Writes the audio data specified by making an internal copy of the data.
     * @member PullAudioOutputStreamImpl.prototype.write
     * @function
     * @public
     * @param {ArrayBuffer} dataBuffer - The audio buffer of which this function will make a copy.
     */
    PullAudioOutputStreamImpl.prototype.write = function (dataBuffer) {
        Contracts_1.Contracts.throwIfNullOrUndefined(this.privStream, "must set format before writing");
        this.privStream.writeStreamChunk({
            buffer: dataBuffer,
            isEnd: false,
            timeReceived: Date.now()
        });
    };
    /**
     * Closes the stream.
     * @member PullAudioOutputStreamImpl.prototype.close
     * @function
     * @public
     */
    PullAudioOutputStreamImpl.prototype.close = function () {
        this.privStream.close();
    };
    return PullAudioOutputStreamImpl;
}(PullAudioOutputStream));
exports.PullAudioOutputStreamImpl = PullAudioOutputStreamImpl;
/*
 * Represents audio output stream used for custom audio output configurations.
 * @class PushAudioOutputStream
 */
var PushAudioOutputStream = /** @class */ (function (_super) {
    __extends(PushAudioOutputStream, _super);
    /**
     * Creates and initializes and instance.
     * @constructor
     */
    function PushAudioOutputStream() {
        return _super.call(this) || this;
    }
    /**
     * Creates a PushAudioOutputStream that delegates to the specified callback interface for
     * write() and close() methods.
     * @member PushAudioOutputStream.create
     * @function
     * @public
     * @param {PushAudioOutputStreamCallback} callback - The custom audio output object,
     *        derived from PushAudioOutputStreamCallback
     * @returns {PushAudioOutputStream} The push audio output stream being created.
     */
    PushAudioOutputStream.create = function (callback) {
        return new PushAudioOutputStreamImpl(callback);
    };
    return PushAudioOutputStream;
}(AudioOutputStream));
exports.PushAudioOutputStream = PushAudioOutputStream;
/**
 * Represents audio output stream used for custom audio output configurations.
 * @private
 * @class PushAudioOutputStreamImpl
 */
var PushAudioOutputStreamImpl = /** @class */ (function (_super) {
    __extends(PushAudioOutputStreamImpl, _super);
    /**
     * Creates a PushAudioOutputStream that delegates to the specified callback interface for
     * read() and close() methods.
     * @constructor
     * @param {PushAudioOutputStreamCallback} callback - The custom audio output object,
     *        derived from PushAudioOutputStreamCallback
     */
    function PushAudioOutputStreamImpl(callback) {
        var _this = _super.call(this) || this;
        _this.privId = Exports_1.createNoDashGuid();
        _this.privCallback = callback;
        return _this;
    }
    Object.defineProperty(PushAudioOutputStreamImpl.prototype, "format", {
        // tslint:disable-next-line:no-empty
        set: function (format) { },
        enumerable: false,
        configurable: true
    });
    PushAudioOutputStreamImpl.prototype.write = function (buffer) {
        if (!!this.privCallback.write) {
            this.privCallback.write(buffer);
        }
    };
    PushAudioOutputStreamImpl.prototype.close = function () {
        if (!!this.privCallback.close) {
            this.privCallback.close();
        }
    };
    PushAudioOutputStreamImpl.prototype.id = function () {
        return this.privId;
    };
    return PushAudioOutputStreamImpl;
}(PushAudioOutputStream));
exports.PushAudioOutputStreamImpl = PushAudioOutputStreamImpl;



/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AudioOutputFormatImpl = void 0;
var SpeechSynthesisOutputFormat_1 = __webpack_require__(75);
var AudioStreamFormat_1 = __webpack_require__(72);
/**
 * @private
 * @class AudioOutputFormatImpl
 * Updated in version 1.17.0
 */
// tslint:disable-next-line:max-classes-per-file
var AudioOutputFormatImpl = /** @class */ (function (_super) {
    __extends(AudioOutputFormatImpl, _super);
    /**
     * Creates an instance with the given values.
     * @constructor
     * @param formatTag
     * @param {number} channels - Number of channels.
     * @param {number} samplesPerSec - Samples per second.
     * @param {number} avgBytesPerSec - Average bytes per second.
     * @param {number} blockAlign - Block alignment.
     * @param {number} bitsPerSample - Bits per sample.
     * @param {string} audioFormatString - Audio format string
     * @param {string} requestAudioFormatString - Audio format string sent to service.
     * @param {boolean} hasHeader - If the format has header or not.
     */
    function AudioOutputFormatImpl(formatTag, channels, samplesPerSec, avgBytesPerSec, blockAlign, bitsPerSample, audioFormatString, requestAudioFormatString, hasHeader) {
        var _this = _super.call(this, samplesPerSec, bitsPerSample, channels, formatTag) || this;
        _this.formatTag = formatTag;
        _this.avgBytesPerSec = avgBytesPerSec;
        _this.blockAlign = blockAlign;
        _this.priAudioFormatString = audioFormatString;
        _this.priRequestAudioFormatString = requestAudioFormatString;
        _this.priHasHeader = hasHeader;
        return _this;
    }
    AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat = function (speechSynthesisOutputFormat) {
        if (speechSynthesisOutputFormat === undefined) {
            return AudioOutputFormatImpl.getDefaultOutputFormat();
        }
        return AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(AudioOutputFormatImpl.SpeechSynthesisOutputFormatToString[speechSynthesisOutputFormat]);
    };
    AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString = function (speechSynthesisOutputFormatString) {
        switch (speechSynthesisOutputFormatString) {
            case "raw-8khz-8bit-mono-mulaw":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MuLaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "riff-16khz-16kbps-mono-siren":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.Siren, 1, 16000, 2000, 40, 0, speechSynthesisOutputFormatString, "audio-16khz-16kbps-mono-siren", true);
            case "audio-16khz-16kbps-mono-siren":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.Siren, 1, 16000, 2000, 40, 0, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-16khz-32kbitrate-mono-mp3":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 16000, 32 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-16khz-128kbitrate-mono-mp3":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 16000, 128 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-16khz-64kbitrate-mono-mp3":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 16000, 64 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-24khz-48kbitrate-mono-mp3":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 24000, 48 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-24khz-96kbitrate-mono-mp3":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 24000, 96 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-24khz-160kbitrate-mono-mp3":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 24000, 160 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "raw-16khz-16bit-mono-truesilk":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.SILKSkype, 1, 16000, 32000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "riff-8khz-16bit-mono-pcm":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 8000, 16000, 2, 16, speechSynthesisOutputFormatString, "raw-8khz-16bit-mono-pcm", true);
            case "riff-24khz-16bit-mono-pcm":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 24000, 48000, 2, 16, speechSynthesisOutputFormatString, "raw-24khz-16bit-mono-pcm", true);
            case "riff-8khz-8bit-mono-mulaw":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MuLaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, "raw-8khz-8bit-mono-mulaw", true);
            case "raw-16khz-16bit-mono-pcm":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 16000, 32000, 2, 16, speechSynthesisOutputFormatString, "raw-16khz-16bit-mono-pcm", false);
            case "raw-24khz-16bit-mono-pcm":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 24000, 48000, 2, 16, speechSynthesisOutputFormatString, "raw-24khz-16bit-mono-pcm", false);
            case "raw-8khz-16bit-mono-pcm":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 8000, 16000, 2, 16, speechSynthesisOutputFormatString, "raw-8khz-16bit-mono-pcm", false);
            case "ogg-16khz-16bit-mono-opus":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OGG_OPUS, 1, 16000, 8192, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "ogg-24khz-16bit-mono-opus":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OGG_OPUS, 1, 24000, 8192, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "raw-48khz-16bit-mono-pcm":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 48000, 96000, 2, 16, speechSynthesisOutputFormatString, "raw-48khz-16bit-mono-pcm", false);
            case "riff-48khz-16bit-mono-pcm":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 48000, 96000, 2, 16, speechSynthesisOutputFormatString, "raw-48khz-16bit-mono-pcm", true);
            case "audio-48khz-96kbitrate-mono-mp3":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 48000, 96 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-48khz-192kbitrate-mono-mp3":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.MP3, 1, 48000, 192 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "ogg-48khz-16bit-mono-opus":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OGG_OPUS, 1, 48000, 12000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "webm-16khz-16bit-mono-opus":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.WEBM_OPUS, 1, 16000, 4000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "webm-24khz-16bit-mono-opus":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.WEBM_OPUS, 1, 24000, 6000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "webm-24khz-16bit-24kbps-mono-opus":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.WEBM_OPUS, 1, 24000, 3000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-16khz-16bit-32kbps-mono-opus":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OPUS, 1, 16000, 4000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-24khz-16bit-48kbps-mono-opus":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OPUS, 1, 24000, 6000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-24khz-16bit-24kbps-mono-opus":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.OPUS, 1, 24000, 3000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-24khz-16bit-mono-flac":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.FLAC, 1, 24000, 24000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "audio-48khz-16bit-mono-flac":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.FLAC, 1, 48000, 30000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "raw-24khz-16bit-mono-truesilk":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.SILKSkype, 1, 24000, 48000, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "raw-8khz-8bit-mono-alaw":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.ALaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
            case "riff-8khz-8bit-mono-alaw":
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.ALaw, 1, 8000, 8000, 1, 8, speechSynthesisOutputFormatString, "raw-8khz-8bit-mono-alaw", true);
            case "riff-16khz-16bit-mono-pcm":
            default:
                return new AudioOutputFormatImpl(AudioStreamFormat_1.AudioFormatTag.PCM, 1, 16000, 32000, 2, 16, "riff-16khz-16bit-mono-pcm", "raw-16khz-16bit-mono-pcm", true);
        }
    };
    AudioOutputFormatImpl.getDefaultOutputFormat = function () {
        return AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString((typeof window !== "undefined") ? "audio-24khz-48kbitrate-mono-mp3" : "riff-16khz-16bit-mono-pcm");
    };
    Object.defineProperty(AudioOutputFormatImpl.prototype, "hasHeader", {
        /**
         * Specifies if this audio output format has a header
         * @boolean AudioOutputFormatImpl.prototype.hasHeader
         * @function
         * @public
         */
        get: function () {
            return this.priHasHeader;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AudioOutputFormatImpl.prototype, "header", {
        /**
         * Specifies the header of this format
         * @ArrayBuffer AudioOutputFormatImpl.prototype.header
         * @function
         * @public
         */
        get: function () {
            if (this.hasHeader) {
                return this.privHeader;
            }
            return undefined;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Updates the header based on the audio length
     * @member AudioOutputFormatImpl.updateHeader
     * @function
     * @public
     * @param {number} audioLength - the audio length
     */
    AudioOutputFormatImpl.prototype.updateHeader = function (audioLength) {
        if (this.priHasHeader) {
            var view = new DataView(this.privHeader);
            view.setUint32(40, audioLength, true);
        }
    };
    Object.defineProperty(AudioOutputFormatImpl.prototype, "requestAudioFormatString", {
        /**
         * Specifies the audio format string to be sent to the service
         * @string AudioOutputFormatImpl.prototype.requestAudioFormatString
         * @function
         * @public
         */
        get: function () {
            return this.priRequestAudioFormatString;
        },
        enumerable: false,
        configurable: true
    });
    AudioOutputFormatImpl.SpeechSynthesisOutputFormatToString = (_a = {},
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoMULaw] = "raw-8khz-8bit-mono-mulaw",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff16Khz16KbpsMonoSiren] = "riff-16khz-16kbps-mono-siren",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio16Khz16KbpsMonoSiren] = "audio-16khz-16kbps-mono-siren",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3] = "audio-16khz-32kbitrate-mono-mp3",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3] = "audio-16khz-128kbitrate-mono-mp3",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio16Khz64KBitRateMonoMp3] = "audio-16khz-64kbitrate-mono-mp3",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3] = "audio-24khz-48kbitrate-mono-mp3",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio24Khz96KBitRateMonoMp3] = "audio-24khz-96kbitrate-mono-mp3",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3] = "audio-24khz-160kbitrate-mono-mp3",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoTrueSilk] = "raw-16khz-16bit-mono-truesilk",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm] = "riff-16khz-16bit-mono-pcm",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff8Khz16BitMonoPcm] = "riff-8khz-16bit-mono-pcm",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm] = "riff-24khz-16bit-mono-pcm",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoMULaw] = "riff-8khz-8bit-mono-mulaw",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm] = "raw-16khz-16bit-mono-pcm",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm] = "raw-24khz-16bit-mono-pcm",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm] = "raw-8khz-16bit-mono-pcm",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus] = "ogg-16khz-16bit-mono-opus",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus] = "ogg-24khz-16bit-mono-opus",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw48Khz16BitMonoPcm] = "raw-48khz-16bit-mono-pcm",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff48Khz16BitMonoPcm] = "riff-48khz-16bit-mono-pcm",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio48Khz96KBitRateMonoMp3] = "audio-48khz-96kbitrate-mono-mp3",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3] = "audio-48khz-192kbitrate-mono-mp3",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus] = "ogg-48khz-16bit-mono-opus",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Webm16Khz16BitMonoOpus] = "webm-16khz-16bit-mono-opus",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Webm24Khz16BitMonoOpus] = "webm-24khz-16bit-mono-opus",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Webm24Khz16Bit24KbpsMonoOpus] = "webm-24khz-16bit-24kbps-mono-opus",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoTrueSilk] = "raw-24khz-16bit-mono-truesilk",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoALaw] = "raw-8khz-8bit-mono-alaw",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoALaw] = "riff-8khz-8bit-mono-alaw",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio16Khz16Bit32KbpsMonoOpus] = "audio-16khz-16bit-32kbps-mono-opus",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio24Khz16Bit48KbpsMonoOpus] = "audio-24khz-16bit-48kbps-mono-opus",
        _a[SpeechSynthesisOutputFormat_1.SpeechSynthesisOutputFormat.Audio24Khz16Bit24KbpsMonoOpus] = "audio-24khz-16bit-24kbps-mono-opus",
        _a);
    return AudioOutputFormatImpl;
}(AudioStreamFormat_1.AudioStreamFormatImpl));
exports.AudioOutputFormatImpl = AudioOutputFormatImpl;



/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisOutputFormat = void 0;
/**
 * Define speech synthesis audio output formats.
 * @enum SpeechSynthesisOutputFormat
 * Updated in version 1.17.0
 */
var SpeechSynthesisOutputFormat;
(function (SpeechSynthesisOutputFormat) {
    /**
     * raw-8khz-8bit-mono-mulaw
     * @member SpeechSynthesisOutputFormat.Raw8Khz8BitMonoMULaw,
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Raw8Khz8BitMonoMULaw"] = 0] = "Raw8Khz8BitMonoMULaw";
    /**
     * riff-16khz-16kbps-mono-siren
     * @note Unsupported by the service. Do not use this value.
     * @member SpeechSynthesisOutputFormat.Riff16Khz16KbpsMonoSiren
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Riff16Khz16KbpsMonoSiren"] = 1] = "Riff16Khz16KbpsMonoSiren";
    /**
     * audio-16khz-16kbps-mono-siren
     * @note Unsupported by the service. Do not use this value.
     * @member SpeechSynthesisOutputFormat.Audio16Khz16KbpsMonoSiren
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio16Khz16KbpsMonoSiren"] = 2] = "Audio16Khz16KbpsMonoSiren";
    /**
     * audio-16khz-32kbitrate-mono-mp3
     * @member SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio16Khz32KBitRateMonoMp3"] = 3] = "Audio16Khz32KBitRateMonoMp3";
    /**
     * audio-16khz-128kbitrate-mono-mp3
     * @member SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio16Khz128KBitRateMonoMp3"] = 4] = "Audio16Khz128KBitRateMonoMp3";
    /**
     * audio-16khz-64kbitrate-mono-mp3
     * @member SpeechSynthesisOutputFormat.Audio16Khz64KBitRateMonoMp3
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio16Khz64KBitRateMonoMp3"] = 5] = "Audio16Khz64KBitRateMonoMp3";
    /**
     * audio-24khz-48kbitrate-mono-mp3
     * @member SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio24Khz48KBitRateMonoMp3"] = 6] = "Audio24Khz48KBitRateMonoMp3";
    /**
     * audio-24khz-96kbitrate-mono-mp3
     * @member SpeechSynthesisOutputFormat.Audio24Khz96KBitRateMonoMp3
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio24Khz96KBitRateMonoMp3"] = 7] = "Audio24Khz96KBitRateMonoMp3";
    /**
     * audio-24khz-160kbitrate-mono-mp3
     * @member SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio24Khz160KBitRateMonoMp3"] = 8] = "Audio24Khz160KBitRateMonoMp3";
    /**
     * raw-16khz-16bit-mono-truesilk
     * @member SpeechSynthesisOutputFormat.Raw16Khz16BitMonoTrueSilk
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Raw16Khz16BitMonoTrueSilk"] = 9] = "Raw16Khz16BitMonoTrueSilk";
    /**
     * riff-16khz-16bit-mono-pcm
     * @member SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Riff16Khz16BitMonoPcm"] = 10] = "Riff16Khz16BitMonoPcm";
    /**
     * riff-8khz-16bit-mono-pcm
     * @member SpeechSynthesisOutputFormat.Riff8Khz16BitMonoPcm
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Riff8Khz16BitMonoPcm"] = 11] = "Riff8Khz16BitMonoPcm";
    /**
     * riff-24khz-16bit-mono-pcm
     * @member SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Riff24Khz16BitMonoPcm"] = 12] = "Riff24Khz16BitMonoPcm";
    /**
     * riff-8khz-8bit-mono-mulaw
     * @member SpeechSynthesisOutputFormat.Riff8Khz8BitMonoMULaw
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Riff8Khz8BitMonoMULaw"] = 13] = "Riff8Khz8BitMonoMULaw";
    /**
     * raw-16khz-16bit-mono-pcm
     * @member SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Raw16Khz16BitMonoPcm"] = 14] = "Raw16Khz16BitMonoPcm";
    /**
     * raw-24khz-16bit-mono-pcm
     * @member SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Raw24Khz16BitMonoPcm"] = 15] = "Raw24Khz16BitMonoPcm";
    /**
     * raw-8khz-16bit-mono-pcm
     * @member SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Raw8Khz16BitMonoPcm"] = 16] = "Raw8Khz16BitMonoPcm";
    /**
     * ogg-16khz-16bit-mono-opus
     * @member SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Ogg16Khz16BitMonoOpus"] = 17] = "Ogg16Khz16BitMonoOpus";
    /**
     * ogg-24khz-16bit-mono-opus
     * @member SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Ogg24Khz16BitMonoOpus"] = 18] = "Ogg24Khz16BitMonoOpus";
    /**
     * raw-48khz-16bit-mono-pcm
     * @member SpeechSynthesisOutputFormat.Raw48Khz16BitMonoPcm
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Raw48Khz16BitMonoPcm"] = 19] = "Raw48Khz16BitMonoPcm";
    /**
     * riff-48khz-16bit-mono-pcm
     * @member SpeechSynthesisOutputFormat.Riff48Khz16BitMonoPcm
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Riff48Khz16BitMonoPcm"] = 20] = "Riff48Khz16BitMonoPcm";
    /**
     * audio-48khz-96kbitrate-mono-mp3
     * @member SpeechSynthesisOutputFormat.Audio48Khz96KBitRateMonoMp3
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio48Khz96KBitRateMonoMp3"] = 21] = "Audio48Khz96KBitRateMonoMp3";
    /**
     * audio-48khz-192kbitrate-mono-mp3
     * @member SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio48Khz192KBitRateMonoMp3"] = 22] = "Audio48Khz192KBitRateMonoMp3";
    /**
     * ogg-48khz-16bit-mono-opus
     * Added in version 1.16.0
     * @member SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Ogg48Khz16BitMonoOpus"] = 23] = "Ogg48Khz16BitMonoOpus";
    /**
     * webm-16khz-16bit-mono-opus
     * Added in version 1.16.0
     * @member SpeechSynthesisOutputFormat.Webm16Khz16BitMonoOpus
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Webm16Khz16BitMonoOpus"] = 24] = "Webm16Khz16BitMonoOpus";
    /**
     * webm-24khz-16bit-mono-opus
     * Added in version 1.16.0
     * @member SpeechSynthesisOutputFormat.Webm24Khz16BitMonoOpus
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Webm24Khz16BitMonoOpus"] = 25] = "Webm24Khz16BitMonoOpus";
    /**
     * raw-24khz-16bit-mono-truesilk
     * Added in version 1.17.0
     * @member SpeechSynthesisOutputFormat.Raw24Khz16BitMonoTrueSilk
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Raw24Khz16BitMonoTrueSilk"] = 26] = "Raw24Khz16BitMonoTrueSilk";
    /**
     * raw-8khz-8bit-mono-alaw
     * Added in version 1.17.0
     * @member SpeechSynthesisOutputFormat.Raw8Khz8BitMonoALaw
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Raw8Khz8BitMonoALaw"] = 27] = "Raw8Khz8BitMonoALaw";
    /**
     * riff-8khz-8bit-mono-alaw
     * Added in version 1.17.0
     * @member SpeechSynthesisOutputFormat.Riff8Khz8BitMonoALaw
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Riff8Khz8BitMonoALaw"] = 28] = "Riff8Khz8BitMonoALaw";
    /**
     * webm-24khz-16bit-24kbps-mono-opus
     * Audio compressed by OPUS codec in a webm container, with bitrate of 24kbps, optimized for IoT scenario.
     * Added in version 1.19.0
     * @member SpeechSynthesisOutputFormat.Webm24Khz16Bit24KbpsMonoOpus
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Webm24Khz16Bit24KbpsMonoOpus"] = 29] = "Webm24Khz16Bit24KbpsMonoOpus";
    /**
     * audio-16khz-16bit-32kbps-mono-opus
     * Audio compressed by OPUS codec without container, with bitrate of 32kbps.
     * Added in version 1.20.0
     * @member SpeechSynthesisOutputFormat.Audio16Khz16Bit32KbpsMonoOpus
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio16Khz16Bit32KbpsMonoOpus"] = 30] = "Audio16Khz16Bit32KbpsMonoOpus";
    /**
     * audio-24khz-16bit-48kbps-mono-opus
     * Audio compressed by OPUS codec without container, with bitrate of 48kbps.
     * Added in version 1.20.0
     * @member SpeechSynthesisOutputFormat.Audio24Khz16Bit48KbpsMonoOpus
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio24Khz16Bit48KbpsMonoOpus"] = 31] = "Audio24Khz16Bit48KbpsMonoOpus";
    /**
     * audio-24khz-16bit-24kbps-mono-opus
     * Audio compressed by OPUS codec without container, with bitrate of 24kbps.
     * Added in version 1.20.0
     * @member SpeechSynthesisOutputFormat.Audio24Khz16Bit24KbpsMonoOpus
     */
    SpeechSynthesisOutputFormat[SpeechSynthesisOutputFormat["Audio24Khz16Bit24KbpsMonoOpus"] = 32] = "Audio24Khz16Bit24KbpsMonoOpus";
})(SpeechSynthesisOutputFormat = exports.SpeechSynthesisOutputFormat || (exports.SpeechSynthesisOutputFormat = {}));



/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancellationReason = void 0;
/**
 * Defines the possible reasons a recognition result might be canceled.
 * @class CancellationReason
 */
var CancellationReason;
(function (CancellationReason) {
    /**
     * Indicates that an error occurred during speech recognition.
     * @member CancellationReason.Error
     */
    CancellationReason[CancellationReason["Error"] = 0] = "Error";
    /**
     * Indicates that the end of the audio stream was reached.
     * @member CancellationReason.EndOfStream
     */
    CancellationReason[CancellationReason["EndOfStream"] = 1] = "EndOfStream";
})(CancellationReason = exports.CancellationReason || (exports.CancellationReason = {}));



/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.PullAudioInputStreamCallback = void 0;
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
/**
 * An abstract base class that defines callback methods (read() and close()) for
 * custom audio input streams).
 * @class PullAudioInputStreamCallback
 */
var PullAudioInputStreamCallback = /** @class */ (function () {
    function PullAudioInputStreamCallback() {
    }
    return PullAudioInputStreamCallback;
}());
exports.PullAudioInputStreamCallback = PullAudioInputStreamCallback;



/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.PushAudioOutputStreamCallback = void 0;
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
/**
 * An abstract base class that defines callback methods (write() and close()) for
 * custom audio output streams).
 * @class PushAudioOutputStreamCallback
 */
var PushAudioOutputStreamCallback = /** @class */ (function () {
    function PushAudioOutputStreamCallback() {
    }
    return PushAudioOutputStreamCallback;
}());
exports.PushAudioOutputStreamCallback = PushAudioOutputStreamCallback;



/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeywordRecognitionModel = void 0;
var Contracts_1 = __webpack_require__(63);
/**
 * Represents a keyword recognition model for recognizing when
 * the user says a keyword to initiate further speech recognition.
 * @class KeywordRecognitionModel
 */
var KeywordRecognitionModel = /** @class */ (function () {
    /**
     * Create and initializes a new instance.
     * @constructor
     */
    function KeywordRecognitionModel() {
        this.privDisposed = false;
    }
    /**
     * Creates a keyword recognition model using the specified filename.
     * @member KeywordRecognitionModel.fromFile
     * @function
     * @public
     * @param {string} fileName - A string that represents file name for the keyword recognition model.
     *        Note, the file can point to a zip file in which case the model
     *        will be extracted from the zip.
     * @returns {KeywordRecognitionModel} The keyword recognition model being created.
     */
    KeywordRecognitionModel.fromFile = function (fileName) {
        Contracts_1.Contracts.throwIfFileDoesNotExist(fileName, "fileName");
        throw new Error("Not yet implemented.");
    };
    /**
     * Creates a keyword recognition model using the specified filename.
     * @member KeywordRecognitionModel.fromStream
     * @function
     * @public
     * @param {string} file - A File that represents file for the keyword recognition model.
     *        Note, the file can point to a zip file in which case the model will be extracted from the zip.
     * @returns {KeywordRecognitionModel} The keyword recognition model being created.
     */
    KeywordRecognitionModel.fromStream = function (file) {
        Contracts_1.Contracts.throwIfNull(file, "file");
        throw new Error("Not yet implemented.");
    };
    /**
     * Dispose of associated resources.
     * @member KeywordRecognitionModel.prototype.close
     * @function
     * @public
     */
    KeywordRecognitionModel.prototype.close = function () {
        if (this.privDisposed) {
            return;
        }
        this.privDisposed = true;
    };
    return KeywordRecognitionModel;
}());
exports.KeywordRecognitionModel = KeywordRecognitionModel;



/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionEventArgs = void 0;
/**
 * Defines content for session events like SessionStarted/Stopped, SoundStarted/Stopped.
 * @class SessionEventArgs
 */
var SessionEventArgs = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {string} sessionId - The session id.
     */
    function SessionEventArgs(sessionId) {
        this.privSessionId = sessionId;
    }
    Object.defineProperty(SessionEventArgs.prototype, "sessionId", {
        /**
         * Represents the session identifier.
         * @member SessionEventArgs.prototype.sessionId
         * @function
         * @public
         * @returns {string} Represents the session identifier.
         */
        get: function () {
            return this.privSessionId;
        },
        enumerable: false,
        configurable: true
    });
    return SessionEventArgs;
}());
exports.SessionEventArgs = SessionEventArgs;



/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecognitionEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Defines payload for session events like Speech Start/End Detected
 * @class
 */
var RecognitionEventArgs = /** @class */ (function (_super) {
    __extends(RecognitionEventArgs, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {number} offset - The offset.
     * @param {string} sessionId - The session id.
     */
    function RecognitionEventArgs(offset, sessionId) {
        var _this = _super.call(this, sessionId) || this;
        _this.privOffset = offset;
        return _this;
    }
    Object.defineProperty(RecognitionEventArgs.prototype, "offset", {
        /**
         * Represents the message offset
         * @member RecognitionEventArgs.prototype.offset
         * @function
         * @public
         */
        get: function () {
            return this.privOffset;
        },
        enumerable: false,
        configurable: true
    });
    return RecognitionEventArgs;
}(Exports_1.SessionEventArgs));
exports.RecognitionEventArgs = RecognitionEventArgs;



/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.OutputFormat = void 0;
/**
 * Define Speech Recognizer output formats.
 * @class OutputFormat
 */
var OutputFormat;
(function (OutputFormat) {
    /**
     * @member OutputFormat.Simple
     */
    OutputFormat[OutputFormat["Simple"] = 0] = "Simple";
    /**
     * @member OutputFormat.Detailed
     */
    OutputFormat[OutputFormat["Detailed"] = 1] = "Detailed";
})(OutputFormat = exports.OutputFormat || (exports.OutputFormat = {}));



/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentRecognitionEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Intent recognition result event arguments.
 * @class
 */
var IntentRecognitionEventArgs = /** @class */ (function (_super) {
    __extends(IntentRecognitionEventArgs, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param result - The result of the intent recognition.
     * @param offset - The offset.
     * @param sessionId - The session id.
     */
    function IntentRecognitionEventArgs(result, offset, sessionId) {
        var _this = _super.call(this, offset, sessionId) || this;
        _this.privResult = result;
        return _this;
    }
    Object.defineProperty(IntentRecognitionEventArgs.prototype, "result", {
        /**
         * Represents the intent recognition result.
         * @member IntentRecognitionEventArgs.prototype.result
         * @function
         * @public
         * @returns {IntentRecognitionResult} Represents the intent recognition result.
         */
        get: function () {
            return this.privResult;
        },
        enumerable: false,
        configurable: true
    });
    return IntentRecognitionEventArgs;
}(Exports_1.RecognitionEventArgs));
exports.IntentRecognitionEventArgs = IntentRecognitionEventArgs;



/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecognitionResult = void 0;
/**
 * Defines result of speech recognition.
 * @class RecognitionResult
 */
var RecognitionResult = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {string} resultId - The result id.
     * @param {ResultReason} reason - The reason.
     * @param {string} text - The recognized text.
     * @param {number} duration - The duration.
     * @param {number} offset - The offset into the stream.
     * @param {string} language - Primary Language detected, if provided.
     * @param {string} languageDetectionConfidence - Primary Language confidence ("Unknown," "Low," "Medium," "High"...), if provided.
     * @param {string} errorDetails - Error details, if provided.
     * @param {string} json - Additional Json, if provided.
     * @param {PropertyCollection} properties - Additional properties, if provided.
     */
    function RecognitionResult(resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties) {
        this.privResultId = resultId;
        this.privReason = reason;
        this.privText = text;
        this.privDuration = duration;
        this.privOffset = offset;
        this.privLanguage = language;
        this.privLanguageDetectionConfidence = languageDetectionConfidence;
        this.privErrorDetails = errorDetails;
        this.privJson = json;
        this.privProperties = properties;
    }
    Object.defineProperty(RecognitionResult.prototype, "resultId", {
        /**
         * Specifies the result identifier.
         * @member RecognitionResult.prototype.resultId
         * @function
         * @public
         * @returns {string} Specifies the result identifier.
         */
        get: function () {
            return this.privResultId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionResult.prototype, "reason", {
        /**
         * Specifies status of the result.
         * @member RecognitionResult.prototype.reason
         * @function
         * @public
         * @returns {ResultReason} Specifies status of the result.
         */
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionResult.prototype, "text", {
        /**
         * Presents the recognized text in the result.
         * @member RecognitionResult.prototype.text
         * @function
         * @public
         * @returns {string} Presents the recognized text in the result.
         */
        get: function () {
            return this.privText;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionResult.prototype, "duration", {
        /**
         * Duration of recognized speech in 100 nano second increments.
         * @member RecognitionResult.prototype.duration
         * @function
         * @public
         * @returns {number} Duration of recognized speech in 100 nano second increments.
         */
        get: function () {
            return this.privDuration;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionResult.prototype, "offset", {
        /**
         * Offset of recognized speech in 100 nano second increments.
         * @member RecognitionResult.prototype.offset
         * @function
         * @public
         * @returns {number} Offset of recognized speech in 100 nano second increments.
         */
        get: function () {
            return this.privOffset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionResult.prototype, "language", {
        /**
         * Primary Language detected.
         * @member RecognitionResult.prototype.language
         * @function
         * @public
         * @returns {string} language detected.
         */
        get: function () {
            return this.privLanguage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionResult.prototype, "languageDetectionConfidence", {
        /**
         * Primary Language detection confidence (Unknown, Low, Medium, High).
         * @member RecognitionResult.prototype.languageDetectionConfidence
         * @function
         * @public
         * @returns {string} detection confidence strength.
         */
        get: function () {
            return this.privLanguageDetectionConfidence;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionResult.prototype, "errorDetails", {
        /**
         * In case of an unsuccessful recognition, provides details of the occurred error.
         * @member RecognitionResult.prototype.errorDetails
         * @function
         * @public
         * @returns {string} a brief description of an error.
         */
        get: function () {
            return this.privErrorDetails;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionResult.prototype, "json", {
        /**
         * A string containing Json serialized recognition result as it was received from the service.
         * @member RecognitionResult.prototype.json
         * @function
         * @private
         * @returns {string} Json serialized representation of the result.
         */
        get: function () {
            return this.privJson;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionResult.prototype, "properties", {
        /**
         *  The set of properties exposed in the result.
         * @member RecognitionResult.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The set of properties exposed in the result.
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    return RecognitionResult;
}());
exports.RecognitionResult = RecognitionResult;



/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechRecognitionResult = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Defines result of speech recognition.
 * @class SpeechRecognitionResult
 */
var SpeechRecognitionResult = /** @class */ (function (_super) {
    __extends(SpeechRecognitionResult, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @public
     * @param {string} resultId - The result id.
     * @param {ResultReason} reason - The reason.
     * @param {string} text - The recognized text.
     * @param {number} duration - The duration.
     * @param {number} offset - The offset into the stream.
     * @param {string} language - Primary Language detected, if provided.
     * @param {string} languageDetectionConfidence - Primary Language confidence ("Unknown," "Low," "Medium," "High"...), if provided.
     * @param {string} speakerId - speaker id for conversation transcription, if provided.
     * @param {string} errorDetails - Error details, if provided.
     * @param {string} json - Additional Json, if provided.
     * @param {PropertyCollection} properties - Additional properties, if provided.
     */
    function SpeechRecognitionResult(resultId, reason, text, duration, offset, language, languageDetectionConfidence, speakerId, errorDetails, json, properties) {
        var _this = _super.call(this, resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties) || this;
        _this.privSpeakerId = speakerId;
        return _this;
    }
    Object.defineProperty(SpeechRecognitionResult.prototype, "speakerId", {
        /**
         * speaker id from conversation transcription/id scenarios
         * @member SpeechRecognitionResult.prototype.speakerId
         * @function
         * @public
         * @returns {string} id of speaker in given result
         */
        get: function () {
            return this.privSpeakerId;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechRecognitionResult;
}(Exports_1.RecognitionResult));
exports.SpeechRecognitionResult = SpeechRecognitionResult;



/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentRecognitionResult = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Intent recognition result.
 * @class
 */
var IntentRecognitionResult = /** @class */ (function (_super) {
    __extends(IntentRecognitionResult, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param intentId - The intent id.
     * @param resultId - The result id.
     * @param reason - The reason.
     * @param text - The recognized text.
     * @param duration - The duration.
     * @param offset - The offset into the stream.
     * @param language - Primary Language detected, if provided.
     * @param languageDetectionConfidence - Primary Language confidence ("Unknown," "Low," "Medium," "High"...), if provided.
     * @param errorDetails - Error details, if provided.
     * @param json - Additional Json, if provided.
     * @param properties - Additional properties, if provided.
     */
    function IntentRecognitionResult(intentId, resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties) {
        var _this = _super.call(this, resultId, reason, text, duration, offset, language, languageDetectionConfidence, undefined, errorDetails, json, properties) || this;
        _this.privIntentId = intentId;
        return _this;
    }
    Object.defineProperty(IntentRecognitionResult.prototype, "intentId", {
        /**
         * A String that represents the intent identifier being recognized.
         * @member IntentRecognitionResult.prototype.intentId
         * @function
         * @public
         * @returns {string} A String that represents the intent identifier being recognized.
         */
        get: function () {
            return this.privIntentId;
        },
        enumerable: false,
        configurable: true
    });
    return IntentRecognitionResult;
}(Exports_1.SpeechRecognitionResult));
exports.IntentRecognitionResult = IntentRecognitionResult;



/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.LanguageUnderstandingModelImpl = exports.LanguageUnderstandingModel = void 0;
var Contracts_1 = __webpack_require__(63);
/**
 * Language understanding model
 * @class LanguageUnderstandingModel
 */
var LanguageUnderstandingModel = /** @class */ (function () {
    /**
     * Creates and initializes a new instance
     * @constructor
     */
    function LanguageUnderstandingModel() {
    }
    /**
     * Creates an language understanding model using the specified endpoint.
     * @member LanguageUnderstandingModel.fromEndpoint
     * @function
     * @public
     * @param {URL} uri - A String that represents the endpoint of the language understanding model.
     * @returns {LanguageUnderstandingModel} The language understanding model being created.
     */
    LanguageUnderstandingModel.fromEndpoint = function (uri) {
        Contracts_1.Contracts.throwIfNull(uri, "uri");
        Contracts_1.Contracts.throwIfNullOrWhitespace(uri.hostname, "uri");
        var langModelImp = new LanguageUnderstandingModelImpl();
        // Need to extract the app ID from the URL.
        // URL is in the format: https://<region>.api.cognitive.microsoft.com/luis/v2.0/apps/<Guid>?subscription-key=<key>&timezoneOffset=-360
        // Start tearing the string apart.
        // region can be extracted from the host name.
        var firstDot = uri.host.indexOf(".");
        if (-1 === firstDot) {
            throw new Error("Could not determine region from endpoint");
        }
        langModelImp.region = uri.host.substr(0, firstDot);
        // Now the app ID.
        var lastSegment = uri.pathname.lastIndexOf("/") + 1;
        if (-1 === lastSegment) {
            throw new Error("Could not determine appId from endpoint");
        }
        langModelImp.appId = uri.pathname.substr(lastSegment);
        // And finally the key.
        langModelImp.subscriptionKey = uri.searchParams.get("subscription-key");
        if (undefined === langModelImp.subscriptionKey) {
            throw new Error("Could not determine subscription key from endpoint");
        }
        return langModelImp;
    };
    /**
     * Creates an language understanding model using the application id of Language Understanding service.
     * @member LanguageUnderstandingModel.fromAppId
     * @function
     * @public
     * @param {string} appId - A String that represents the application id of Language Understanding service.
     * @returns {LanguageUnderstandingModel} The language understanding model being created.
     */
    LanguageUnderstandingModel.fromAppId = function (appId) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(appId, "appId");
        var langModelImp = new LanguageUnderstandingModelImpl();
        langModelImp.appId = appId;
        return langModelImp;
    };
    /**
     * Creates a language understanding model using hostname, subscription key and application
     * id of Language Understanding service.
     * @member LanguageUnderstandingModel.fromSubscription
     * @function
     * @public
     * @param {string} subscriptionKey - A String that represents the subscription key of
     *        Language Understanding service.
     * @param {string} appId - A String that represents the application id of Language
     *        Understanding service.
     * @param {LanguageUnderstandingModel} region - A String that represents the region
     *        of the Language Understanding service (see the <a href="https://aka.ms/csspeech/region">region page</a>).
     * @returns {LanguageUnderstandingModel} The language understanding model being created.
     */
    LanguageUnderstandingModel.fromSubscription = function (subscriptionKey, appId, region) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey");
        Contracts_1.Contracts.throwIfNullOrWhitespace(appId, "appId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region");
        var langModelImp = new LanguageUnderstandingModelImpl();
        langModelImp.appId = appId;
        langModelImp.region = region;
        langModelImp.subscriptionKey = subscriptionKey;
        return langModelImp;
    };
    return LanguageUnderstandingModel;
}());
exports.LanguageUnderstandingModel = LanguageUnderstandingModel;
/**
 * @private
 * @class LanguageUnderstandingModelImpl
 */
// tslint:disable-next-line:max-classes-per-file
var LanguageUnderstandingModelImpl = /** @class */ (function (_super) {
    __extends(LanguageUnderstandingModelImpl, _super);
    function LanguageUnderstandingModelImpl() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return LanguageUnderstandingModelImpl;
}(LanguageUnderstandingModel));
exports.LanguageUnderstandingModelImpl = LanguageUnderstandingModelImpl;



/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranscriptionEventArgs = exports.SpeechRecognitionEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Defines contents of speech recognizing/recognized event.
 * @class SpeechRecognitionEventArgs
 */
var SpeechRecognitionEventArgs = /** @class */ (function (_super) {
    __extends(SpeechRecognitionEventArgs, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {SpeechRecognitionResult} result - The speech recognition result.
     * @param {number} offset - The offset.
     * @param {string} sessionId - The session id.
     */
    function SpeechRecognitionEventArgs(result, offset, sessionId) {
        var _this = _super.call(this, offset, sessionId) || this;
        _this.privResult = result;
        return _this;
    }
    Object.defineProperty(SpeechRecognitionEventArgs.prototype, "result", {
        /**
         * Specifies the recognition result.
         * @member SpeechRecognitionEventArgs.prototype.result
         * @function
         * @public
         * @returns {SpeechRecognitionResult} the recognition result.
         */
        get: function () {
            return this.privResult;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechRecognitionEventArgs;
}(Exports_1.RecognitionEventArgs));
exports.SpeechRecognitionEventArgs = SpeechRecognitionEventArgs;
/**
 * Defines contents of conversation transcribed/transcribing event.
 * @class ConversationTranscriptionEventArgs
 */
// tslint:disable-next-line:max-classes-per-file
var ConversationTranscriptionEventArgs = /** @class */ (function (_super) {
    __extends(ConversationTranscriptionEventArgs, _super);
    function ConversationTranscriptionEventArgs() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ConversationTranscriptionEventArgs;
}(SpeechRecognitionEventArgs));
exports.ConversationTranscriptionEventArgs = ConversationTranscriptionEventArgs;



/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechRecognitionCanceledEventArgs = void 0;
var CancellationEventArgsBase_1 = __webpack_require__(90);
var SpeechRecognitionCanceledEventArgs = /** @class */ (function (_super) {
    __extends(SpeechRecognitionCanceledEventArgs, _super);
    function SpeechRecognitionCanceledEventArgs() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return SpeechRecognitionCanceledEventArgs;
}(CancellationEventArgsBase_1.CancellationEventArgsBase));
exports.SpeechRecognitionCanceledEventArgs = SpeechRecognitionCanceledEventArgs;



/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancellationEventArgsBase = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Defines content of a CancellationEvent.
 * @class CancellationEventArgsBase
 */
var CancellationEventArgsBase = /** @class */ (function (_super) {
    __extends(CancellationEventArgsBase, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {CancellationReason} reason - The cancellation reason.
     * @param {string} errorDetails - Error details, if provided.
     * @param {number} offset - The offset.
     * @param {string} sessionId - The session id.
     */
    function CancellationEventArgsBase(reason, errorDetails, errorCode, offset, sessionId) {
        var _this = _super.call(this, offset, sessionId) || this;
        _this.privReason = reason;
        _this.privErrorDetails = errorDetails;
        _this.privErrorCode = errorCode;
        return _this;
    }
    Object.defineProperty(CancellationEventArgsBase.prototype, "reason", {
        /**
         * The reason the recognition was canceled.
         * @member CancellationEventArgsBase.prototype.reason
         * @function
         * @public
         * @returns {CancellationReason} Specifies the reason canceled.
         */
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CancellationEventArgsBase.prototype, "errorCode", {
        /**
         * The error code in case of an unsuccessful operation.
         * @return An error code that represents the error reason.
         */
        get: function () {
            return this.privErrorCode;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CancellationEventArgsBase.prototype, "errorDetails", {
        /**
         * In case of an unsuccessful operation, provides details of the occurred error.
         * @member CancellationEventArgsBase.prototype.errorDetails
         * @function
         * @public
         * @returns {string} A String that represents the error details.
         */
        get: function () {
            return this.privErrorDetails;
        },
        enumerable: false,
        configurable: true
    });
    return CancellationEventArgsBase;
}(Exports_1.RecognitionEventArgs));
exports.CancellationEventArgsBase = CancellationEventArgsBase;



/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationRecognitionEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Translation text result event arguments.
 * @class TranslationRecognitionEventArgs
 */
var TranslationRecognitionEventArgs = /** @class */ (function (_super) {
    __extends(TranslationRecognitionEventArgs, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {TranslationRecognitionResult} result - The translation recognition result.
     * @param {number} offset - The offset.
     * @param {string} sessionId - The session id.
     */
    function TranslationRecognitionEventArgs(result, offset, sessionId) {
        var _this = _super.call(this, offset, sessionId) || this;
        _this.privResult = result;
        return _this;
    }
    Object.defineProperty(TranslationRecognitionEventArgs.prototype, "result", {
        /**
         * Specifies the recognition result.
         * @member TranslationRecognitionEventArgs.prototype.result
         * @function
         * @public
         * @returns {TranslationRecognitionResult} the recognition result.
         */
        get: function () {
            return this.privResult;
        },
        enumerable: false,
        configurable: true
    });
    return TranslationRecognitionEventArgs;
}(Exports_1.RecognitionEventArgs));
exports.TranslationRecognitionEventArgs = TranslationRecognitionEventArgs;



/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationSynthesisEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Translation Synthesis event arguments
 * @class TranslationSynthesisEventArgs
 */
var TranslationSynthesisEventArgs = /** @class */ (function (_super) {
    __extends(TranslationSynthesisEventArgs, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {TranslationSynthesisResult} result - The translation synthesis result.
     * @param {string} sessionId - The session id.
     */
    function TranslationSynthesisEventArgs(result, sessionId) {
        var _this = _super.call(this, sessionId) || this;
        _this.privResult = result;
        return _this;
    }
    Object.defineProperty(TranslationSynthesisEventArgs.prototype, "result", {
        /**
         * Specifies the translation synthesis result.
         * @member TranslationSynthesisEventArgs.prototype.result
         * @function
         * @public
         * @returns {TranslationSynthesisResult} Specifies the translation synthesis result.
         */
        get: function () {
            return this.privResult;
        },
        enumerable: false,
        configurable: true
    });
    return TranslationSynthesisEventArgs;
}(Exports_1.SessionEventArgs));
exports.TranslationSynthesisEventArgs = TranslationSynthesisEventArgs;



/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationRecognitionResult = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Translation text result.
 * @class TranslationRecognitionResult
 */
var TranslationRecognitionResult = /** @class */ (function (_super) {
    __extends(TranslationRecognitionResult, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {Translations} translations - The translations.
     * @param {string} resultId - The result id.
     * @param {ResultReason} reason - The reason.
     * @param {string} text - The recognized text.
     * @param {number} duration - The duration.
     * @param {number} offset - The offset into the stream.
     * @param {string} errorDetails - Error details, if provided.
     * @param {string} json - Additional Json, if provided.
     * @param {PropertyCollection} properties - Additional properties, if provided.
     */
    function TranslationRecognitionResult(translations, resultId, reason, text, duration, offset, errorDetails, json, properties) {
        var _this = _super.call(this, resultId, reason, text, duration, offset, undefined, undefined, undefined, errorDetails, json, properties) || this;
        _this.privTranslations = translations;
        return _this;
    }
    Object.defineProperty(TranslationRecognitionResult.prototype, "translations", {
        /**
         * Presents the translation results. Each item in the dictionary represents
         * a translation result in one of target languages, where the key is the name
         * of the target language, in BCP-47 format, and the value is the translation
         * text in the specified language.
         * @member TranslationRecognitionResult.prototype.translations
         * @function
         * @public
         * @returns {Translations} the current translation map that holds all translations requested.
         */
        get: function () {
            return this.privTranslations;
        },
        enumerable: false,
        configurable: true
    });
    return TranslationRecognitionResult;
}(Exports_1.SpeechRecognitionResult));
exports.TranslationRecognitionResult = TranslationRecognitionResult;



/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationSynthesisResult = void 0;
/**
 * Defines translation synthesis result, i.e. the voice output of the translated
 * text in the target language.
 * @class TranslationSynthesisResult
 */
var TranslationSynthesisResult = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {ResultReason} reason - The synthesis reason.
     * @param {ArrayBuffer} audio - The audio data.
     */
    function TranslationSynthesisResult(reason, audio) {
        this.privReason = reason;
        this.privAudio = audio;
    }
    Object.defineProperty(TranslationSynthesisResult.prototype, "audio", {
        /**
         * Translated text in the target language.
         * @member TranslationSynthesisResult.prototype.audio
         * @function
         * @public
         * @returns {ArrayBuffer} Translated audio in the target language.
         */
        get: function () {
            return this.privAudio;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationSynthesisResult.prototype, "reason", {
        /**
         * The synthesis status.
         * @member TranslationSynthesisResult.prototype.reason
         * @function
         * @public
         * @returns {ResultReason} The synthesis status.
         */
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    return TranslationSynthesisResult;
}());
exports.TranslationSynthesisResult = TranslationSynthesisResult;



/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResultReason = void 0;
/**
 * Defines the possible reasons a recognition result might be generated.
 * @class ResultReason
 */
var ResultReason;
(function (ResultReason) {
    /**
     * Indicates speech could not be recognized. More details
     * can be found in the NoMatchDetails object.
     * @member ResultReason.NoMatch
     */
    ResultReason[ResultReason["NoMatch"] = 0] = "NoMatch";
    /**
     * Indicates that the recognition was canceled. More details
     * can be found using the CancellationDetails object.
     * @member ResultReason.Canceled
     */
    ResultReason[ResultReason["Canceled"] = 1] = "Canceled";
    /**
     * Indicates the speech result contains hypothesis text.
     * @member ResultReason.RecognizedSpeech
     */
    ResultReason[ResultReason["RecognizingSpeech"] = 2] = "RecognizingSpeech";
    /**
     * Indicates the speech result contains final text that has been recognized.
     * Speech Recognition is now complete for this phrase.
     * @member ResultReason.RecognizedSpeech
     */
    ResultReason[ResultReason["RecognizedSpeech"] = 3] = "RecognizedSpeech";
    /**
     * Indicates the speech result contains a finalized acceptance of a provided keyword.
     * Speech recognition will continue unless otherwise configured.
     * @member ResultReason.RecognizedKeyword
     */
    ResultReason[ResultReason["RecognizedKeyword"] = 4] = "RecognizedKeyword";
    /**
     * Indicates the intent result contains hypothesis text and intent.
     * @member ResultReason.RecognizingIntent
     */
    ResultReason[ResultReason["RecognizingIntent"] = 5] = "RecognizingIntent";
    /**
     * Indicates the intent result contains final text and intent.
     * Speech Recognition and Intent determination are now complete for this phrase.
     * @member ResultReason.RecognizedIntent
     */
    ResultReason[ResultReason["RecognizedIntent"] = 6] = "RecognizedIntent";
    /**
     * Indicates the translation result contains hypothesis text and its translation(s).
     * @member ResultReason.TranslatingSpeech
     */
    ResultReason[ResultReason["TranslatingSpeech"] = 7] = "TranslatingSpeech";
    /**
     * Indicates the translation result contains final text and corresponding translation(s).
     * Speech Recognition and Translation are now complete for this phrase.
     * @member ResultReason.TranslatedSpeech
     */
    ResultReason[ResultReason["TranslatedSpeech"] = 8] = "TranslatedSpeech";
    /**
     * Indicates the synthesized audio result contains a non-zero amount of audio data
     * @member ResultReason.SynthesizingAudio
     */
    ResultReason[ResultReason["SynthesizingAudio"] = 9] = "SynthesizingAudio";
    /**
     * Indicates the synthesized audio is now complete for this phrase.
     * @member ResultReason.SynthesizingAudioCompleted
     */
    ResultReason[ResultReason["SynthesizingAudioCompleted"] = 10] = "SynthesizingAudioCompleted";
    /**
     * Indicates the speech synthesis is now started
     * @member ResultReason.SynthesizingAudioStarted
     */
    ResultReason[ResultReason["SynthesizingAudioStarted"] = 11] = "SynthesizingAudioStarted";
    /**
     * Indicates the voice profile is being enrolled and customers need to send more audio to create a voice profile.
     * @member ResultReason.EnrollingVoiceProfile
     */
    ResultReason[ResultReason["EnrollingVoiceProfile"] = 12] = "EnrollingVoiceProfile";
    /**
     * Indicates the voice profile has been enrolled.
     * @member ResultReason.EnrolledVoiceProfile
     */
    ResultReason[ResultReason["EnrolledVoiceProfile"] = 13] = "EnrolledVoiceProfile";
    /**
     * Indicates successful identification of some speakers.
     * @member ResultReason.RecognizedSpeakers
     */
    ResultReason[ResultReason["RecognizedSpeakers"] = 14] = "RecognizedSpeakers";
    /**
     * Indicates successfully verified one speaker.
     * @member ResultReason.RecognizedSpeaker
     */
    ResultReason[ResultReason["RecognizedSpeaker"] = 15] = "RecognizedSpeaker";
    /**
     * Indicates a voice profile has been reset successfully.
     * @member ResultReason.ResetVoiceProfile
     */
    ResultReason[ResultReason["ResetVoiceProfile"] = 16] = "ResetVoiceProfile";
    /**
     * Indicates a voice profile has been deleted successfully.
     * @member ResultReason.DeletedVoiceProfile
     */
    ResultReason[ResultReason["DeletedVoiceProfile"] = 17] = "DeletedVoiceProfile";
    /**
     * Indicates synthesis voices list has been successfully retrieved.
     * @member ResultReason.VoicesListRetrieved
     */
    ResultReason[ResultReason["VoicesListRetrieved"] = 18] = "VoicesListRetrieved";
})(ResultReason = exports.ResultReason || (exports.ResultReason = {}));



/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechConfigImpl = exports.SpeechConfig = void 0;
var Exports_1 = __webpack_require__(53);
var Contracts_1 = __webpack_require__(63);
var Exports_2 = __webpack_require__(61);
/**
 * Speech configuration.
 * @class SpeechConfig
 */
var SpeechConfig = /** @class */ (function () {
    /**
     * Creates and initializes an instance.
     * @constructor
     */
    function SpeechConfig() {
    }
    /**
     * Static instance of SpeechConfig returned by passing subscriptionKey and service region.
     * Note: Please use your LanguageUnderstanding subscription key in case you want to use the Intent recognizer.
     * @member SpeechConfig.fromSubscription
     * @function
     * @public
     * @param {string} subscriptionKey - The subscription key.
     * @param {string} region - The region name (see the <a href="https://aka.ms/csspeech/region">region page</a>).
     * @returns {SpeechConfig} The speech factory
     */
    SpeechConfig.fromSubscription = function (subscriptionKey, region) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey");
        Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region");
        var speechImpl = new SpeechConfigImpl();
        speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, region);
        speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_IntentRegion, region);
        speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
        return speechImpl;
    };
    /**
     * Creates an instance of the speech config with specified endpoint and subscription key.
     * This method is intended only for users who use a non-standard service endpoint or parameters.
     * Note: Please use your LanguageUnderstanding subscription key in case you want to use the Intent recognizer.
     * Note: The query parameters specified in the endpoint URL are not changed, even if they are set by any other APIs.
     * For example, if language is defined in the uri as query parameter "language=de-DE", and also set by
     *              SpeechConfig.speechRecognitionLanguage = "en-US", the language setting in uri takes precedence,
     *              and the effective language is "de-DE". Only the parameters that are not specified in the
     *              endpoint URL can be set by other APIs.
     * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the
     *       fromEndpoint method, and then set authorizationToken="token" on the created SpeechConfig instance to
     *       use the authorization token.
     * @member SpeechConfig.fromEndpoint
     * @function
     * @public
     * @param {URL} endpoint - The service endpoint to connect to.
     * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set.
     * @returns {SpeechConfig} A speech factory instance.
     */
    SpeechConfig.fromEndpoint = function (endpoint, subscriptionKey) {
        Contracts_1.Contracts.throwIfNull(endpoint, "endpoint");
        var speechImpl = new SpeechConfigImpl();
        speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, endpoint.href);
        if (undefined !== subscriptionKey) {
            speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
        }
        return speechImpl;
    };
    /**
     * Creates an instance of the speech config with specified host and subscription key.
     * This method is intended only for users who use a non-default service host. Standard resource path will be assumed.
     * For services with a non-standard resource path or no path at all, use fromEndpoint instead.
     * Note: Query parameters are not allowed in the host URI and must be set by other APIs.
     * Note: To use an authorization token with fromHost, use fromHost(URL),
     * and then set the AuthorizationToken property on the created SpeechConfig instance.
     * Note: Added in version 1.9.0.
     * @member SpeechConfig.fromHost
     * @function
     * @public
     * @param {URL} host - The service endpoint to connect to. Format is "protocol://host:port" where ":port" is optional.
     * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set.
     * @returns {SpeechConfig} A speech factory instance.
     */
    SpeechConfig.fromHost = function (hostName, subscriptionKey) {
        Contracts_1.Contracts.throwIfNull(hostName, "hostName");
        var speechImpl = new SpeechConfigImpl();
        speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, hostName.protocol + "//" + hostName.hostname + (hostName.port === "" ? "" : ":" + hostName.port));
        if (undefined !== subscriptionKey) {
            speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
        }
        return speechImpl;
    };
    /**
     * Creates an instance of the speech factory with specified initial authorization token and region.
     * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token
     *       expires, the caller needs to refresh it by calling this setter with a new valid token.
     * Note: Please use a token derived from your LanguageUnderstanding subscription key in case you want
     *       to use the Intent recognizer. As configuration values are copied when creating a new recognizer,
     *       the new token value will not apply to recognizers that have already been created. For recognizers
     *       that have been created before, you need to set authorization token of the corresponding recognizer
     *       to refresh the token. Otherwise, the recognizers will encounter errors during recognition.
     * @member SpeechConfig.fromAuthorizationToken
     * @function
     * @public
     * @param {string} authorizationToken - The initial authorization token.
     * @param {string} region - The region name (see the <a href="https://aka.ms/csspeech/region">region page</a>).
     * @returns {SpeechConfig} A speech factory instance.
     */
    SpeechConfig.fromAuthorizationToken = function (authorizationToken, region) {
        Contracts_1.Contracts.throwIfNull(authorizationToken, "authorizationToken");
        Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region");
        var speechImpl = new SpeechConfigImpl();
        speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, region);
        speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_IntentRegion, region);
        speechImpl.authorizationToken = authorizationToken;
        return speechImpl;
    };
    /**
     * Closes the configuration.
     * @member SpeechConfig.prototype.close
     * @function
     * @public
     */
    /* tslint:disable:no-empty */
    SpeechConfig.prototype.close = function () { };
    return SpeechConfig;
}());
exports.SpeechConfig = SpeechConfig;
/**
 * @public
 * @class SpeechConfigImpl
 */
// tslint:disable-next-line:max-classes-per-file
var SpeechConfigImpl = /** @class */ (function (_super) {
    __extends(SpeechConfigImpl, _super);
    function SpeechConfigImpl() {
        var _this = _super.call(this) || this;
        _this.privProperties = new Exports_2.PropertyCollection();
        _this.speechRecognitionLanguage = "en-US"; // Should we have a default?
        _this.outputFormat = Exports_2.OutputFormat.Simple;
        return _this;
    }
    Object.defineProperty(SpeechConfigImpl.prototype, "properties", {
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConfigImpl.prototype, "endPoint", {
        get: function () {
            return new URL(this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint));
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConfigImpl.prototype, "subscriptionKey", {
        get: function () {
            return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Key);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConfigImpl.prototype, "region", {
        get: function () {
            return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConfigImpl.prototype, "authorizationToken", {
        get: function () {
            return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token);
        },
        set: function (value) {
            this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConfigImpl.prototype, "speechRecognitionLanguage", {
        get: function () {
            return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage);
        },
        set: function (value) {
            this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage, value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConfigImpl.prototype, "autoDetectSourceLanguages", {
        get: function () {
            return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages);
        },
        set: function (value) {
            this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConfigImpl.prototype, "outputFormat", {
        get: function () {
            return Exports_2.OutputFormat[this.privProperties.getProperty(Exports_1.OutputFormatPropertyName, undefined)];
        },
        set: function (value) {
            this.privProperties.setProperty(Exports_1.OutputFormatPropertyName, Exports_2.OutputFormat[value]);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConfigImpl.prototype, "endpointId", {
        get: function () {
            return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId);
        },
        set: function (value) {
            this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId, value);
        },
        enumerable: false,
        configurable: true
    });
    SpeechConfigImpl.prototype.setProperty = function (name, value) {
        Contracts_1.Contracts.throwIfNull(value, "value");
        this.privProperties.setProperty(name, value);
    };
    SpeechConfigImpl.prototype.getProperty = function (name, def) {
        return this.privProperties.getProperty(name, def);
    };
    SpeechConfigImpl.prototype.setProxy = function (proxyHostName, proxyPort, proxyUserName, proxyPassword) {
        this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName);
        this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyPort], proxyPort);
        this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName);
        this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyPassword], proxyPassword);
    };
    SpeechConfigImpl.prototype.setServiceProperty = function (name, value, channel) {
        var currentProperties = JSON.parse(this.privProperties.getProperty(Exports_1.ServicePropertiesPropertyName, "{}"));
        currentProperties[name] = value;
        this.privProperties.setProperty(Exports_1.ServicePropertiesPropertyName, JSON.stringify(currentProperties));
    };
    SpeechConfigImpl.prototype.setProfanity = function (profanity) {
        this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceResponse_ProfanityOption, Exports_2.ProfanityOption[profanity]);
    };
    SpeechConfigImpl.prototype.enableAudioLogging = function () {
        this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, "true");
    };
    SpeechConfigImpl.prototype.requestWordLevelTimestamps = function () {
        this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "true");
    };
    SpeechConfigImpl.prototype.enableDictation = function () {
        this.privProperties.setProperty(Exports_1.ForceDictationPropertyName, "true");
    };
    SpeechConfigImpl.prototype.clone = function () {
        var ret = new SpeechConfigImpl();
        ret.privProperties = this.privProperties.clone();
        return ret;
    };
    Object.defineProperty(SpeechConfigImpl.prototype, "speechSynthesisLanguage", {
        get: function () {
            return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthLanguage);
        },
        set: function (language) {
            this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthLanguage, language);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConfigImpl.prototype, "speechSynthesisVoiceName", {
        get: function () {
            return this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthVoice);
        },
        set: function (voice) {
            this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthVoice, voice);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConfigImpl.prototype, "speechSynthesisOutputFormat", {
        get: function () {
            return Exports_2.SpeechSynthesisOutputFormat[this.privProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)];
        },
        set: function (format) {
            this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, Exports_2.SpeechSynthesisOutputFormat[format]);
        },
        enumerable: false,
        configurable: true
    });
    return SpeechConfigImpl;
}(SpeechConfig));
exports.SpeechConfigImpl = SpeechConfigImpl;



/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechTranslationConfigImpl = exports.SpeechTranslationConfig = void 0;
var Exports_1 = __webpack_require__(53);
var Contracts_1 = __webpack_require__(63);
var Exports_2 = __webpack_require__(61);
/**
 * Speech translation configuration.
 * @class SpeechTranslationConfig
 */
var SpeechTranslationConfig = /** @class */ (function (_super) {
    __extends(SpeechTranslationConfig, _super);
    /**
     * Creates an instance of recognizer config.
     */
    function SpeechTranslationConfig() {
        return _super.call(this) || this;
    }
    /**
     * Static instance of SpeechTranslationConfig returned by passing a subscription key and service region.
     * @member SpeechTranslationConfig.fromSubscription
     * @function
     * @public
     * @param {string} subscriptionKey - The subscription key.
     * @param {string} region - The region name (see the <a href="https://aka.ms/csspeech/region">region page</a>).
     * @returns {SpeechTranslationConfig} The speech translation config.
     */
    SpeechTranslationConfig.fromSubscription = function (subscriptionKey, region) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey");
        Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region");
        var ret = new SpeechTranslationConfigImpl();
        ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
        ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, region);
        return ret;
    };
    /**
     * Static instance of SpeechTranslationConfig returned by passing authorization token and service region.
     * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token
     *       expires, the caller needs to refresh it by setting the property authorizationToken with a new
     *       valid token. Otherwise, all the recognizers created by this SpeechTranslationConfig instance
     *       will encounter errors during recognition.
     * As configuration values are copied when creating a new recognizer, the new token value will not apply
     * to recognizers that have already been created.
     * For recognizers that have been created before, you need to set authorization token of the corresponding recognizer
     * to refresh the token. Otherwise, the recognizers will encounter errors during recognition.
     * @member SpeechTranslationConfig.fromAuthorizationToken
     * @function
     * @public
     * @param {string} authorizationToken - The authorization token.
     * @param {string} region - The region name (see the <a href="https://aka.ms/csspeech/region">region page</a>).
     * @returns {SpeechTranslationConfig} The speech translation config.
     */
    SpeechTranslationConfig.fromAuthorizationToken = function (authorizationToken, region) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken");
        Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region");
        var ret = new SpeechTranslationConfigImpl();
        ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, authorizationToken);
        ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, region);
        return ret;
    };
    /**
     * Creates an instance of the speech config with specified host and subscription key.
     * This method is intended only for users who use a non-default service host. Standard resource path will be assumed.
     * For services with a non-standard resource path or no path at all, use fromEndpoint instead.
     * Note: Query parameters are not allowed in the host URI and must be set by other APIs.
     * Note: To use an authorization token with fromHost, use fromHost(URL),
     * and then set the AuthorizationToken property on the created SpeechConfig instance.
     * Note: Added in version 1.9.0.
     * @member SpeechConfig.fromHost
     * @function
     * @public
     * @param {URL} host - The service endpoint to connect to. Format is "protocol://host:port" where ":port" is optional.
     * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization token must be set.
     * @returns {SpeechConfig} A speech factory instance.
     */
    SpeechTranslationConfig.fromHost = function (hostName, subscriptionKey) {
        Contracts_1.Contracts.throwIfNull(hostName, "hostName");
        var speechImpl = new SpeechTranslationConfigImpl();
        speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, hostName.protocol + "//" + hostName.hostname + (hostName.port === "" ? "" : ":" + hostName.port));
        if (undefined !== subscriptionKey) {
            speechImpl.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
        }
        return speechImpl;
    };
    /**
     * Creates an instance of the speech translation config with specified endpoint and subscription key.
     * This method is intended only for users who use a non-standard service endpoint or paramters.
     * Note: The query properties specified in the endpoint URL are not changed, even if they are
     *       set by any other APIs. For example, if language is defined in the uri as query parameter
     *       "language=de-DE", and also set by the speechRecognitionLanguage property, the language
     *       setting in uri takes precedence, and the effective language is "de-DE".
     * Only the properties that are not specified in the endpoint URL can be set by other APIs.
     * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the
     *       fromEndpoint method, and then set authorizationToken="token" on the created SpeechConfig instance to
     *       use the authorization token.
     * @member SpeechTranslationConfig.fromEndpoint
     * @function
     * @public
     * @param {URL} endpoint - The service endpoint to connect to.
     * @param {string} subscriptionKey - The subscription key.
     * @returns {SpeechTranslationConfig} A speech config instance.
     */
    SpeechTranslationConfig.fromEndpoint = function (endpoint, subscriptionKey) {
        Contracts_1.Contracts.throwIfNull(endpoint, "endpoint");
        Contracts_1.Contracts.throwIfNull(subscriptionKey, "subscriptionKey");
        var ret = new SpeechTranslationConfigImpl();
        ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, endpoint.href);
        ret.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
        return ret;
    };
    return SpeechTranslationConfig;
}(Exports_2.SpeechConfig));
exports.SpeechTranslationConfig = SpeechTranslationConfig;
/**
 * @private
 * @class SpeechTranslationConfigImpl
 */
// tslint:disable-next-line:max-classes-per-file
var SpeechTranslationConfigImpl = /** @class */ (function (_super) {
    __extends(SpeechTranslationConfigImpl, _super);
    function SpeechTranslationConfigImpl() {
        var _this = _super.call(this) || this;
        _this.privSpeechProperties = new Exports_2.PropertyCollection();
        _this.outputFormat = Exports_2.OutputFormat.Simple;
        return _this;
    }
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "authorizationToken", {
        /**
         * Gets/Sets the authorization token.
         * If this is set, subscription key is ignored.
         * User needs to make sure the provided authorization token is valid and not expired.
         * @member SpeechTranslationConfigImpl.prototype.authorizationToken
         * @function
         * @public
         * @param {string} value - The authorization token.
         */
        set: function (value) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value");
            this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "speechRecognitionLanguage", {
        /**
         * Gets the speech recognition language.
         * @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage
         * @function
         * @public
         * @return {string} The speechRecognitionLanguage.
         */
        get: function () {
            return this.privSpeechProperties.getProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage]);
        },
        /**
         * Sets the speech recognition language.
         * @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage
         * @function
         * @public
         * @param {string} value - The authorization token.
         */
        set: function (value) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value");
            this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage, value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "subscriptionKey", {
        /**
         * @member SpeechTranslationConfigImpl.prototype.subscriptionKey
         * @function
         * @public
         */
        get: function () {
            return this.privSpeechProperties.getProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_Key]);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "outputFormat", {
        /**
         * Gets the output format
         * @member SpeechTranslationConfigImpl.prototype.outputFormat
         * @function
         * @public
         */
        get: function () {
            return Exports_2.OutputFormat[this.privSpeechProperties.getProperty(Exports_1.OutputFormatPropertyName, undefined)];
        },
        /**
         * Gets/Sets the output format
         * @member SpeechTranslationConfigImpl.prototype.outputFormat
         * @function
         * @public
         */
        set: function (value) {
            this.privSpeechProperties.setProperty(Exports_1.OutputFormatPropertyName, Exports_2.OutputFormat[value]);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "endpointId", {
        /**
         * Gets the endpoint id.
         * @member SpeechTranslationConfigImpl.prototype.endpointId
         * @function
         * @public
         */
        get: function () {
            return this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId);
        },
        /**
         * Gets/Sets the endpoint id.
         * @member SpeechTranslationConfigImpl.prototype.endpointId
         * @function
         * @public
         */
        set: function (value) {
            this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId, value);
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Add a (text) target language to translate into.
     * @member SpeechTranslationConfigImpl.prototype.addTargetLanguage
     * @function
     * @public
     * @param {string} value - The language such as de-DE
     */
    SpeechTranslationConfigImpl.prototype.addTargetLanguage = function (value) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value");
        var languages = this.targetLanguages;
        languages.push(value);
        this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(","));
    };
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "targetLanguages", {
        /**
         * Gets the (text) target language to translate into.
         * @member SpeechTranslationConfigImpl.prototype.targetLanguages
         * @function
         * @public
         * @param {string} value - The language such as de-DE
         */
        get: function () {
            if (this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) {
                return this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
            }
            else {
                return [];
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "voiceName", {
        /**
         * Gets the voice name.
         * @member SpeechTranslationConfigImpl.prototype.voiceName
         * @function
         * @public
         */
        get: function () {
            return this.getProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_TranslationVoice]);
        },
        /**
         * Gets/Sets the voice of the translated language, enable voice synthesis output.
         * @member SpeechTranslationConfigImpl.prototype.voiceName
         * @function
         * @public
         * @param {string} value - The name of the voice.
         */
        set: function (value) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value");
            this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationVoice, value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "region", {
        /**
         * Provides the region.
         * @member SpeechTranslationConfigImpl.prototype.region
         * @function
         * @public
         * @returns {string} The region.
         */
        get: function () {
            return this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region);
        },
        enumerable: false,
        configurable: true
    });
    SpeechTranslationConfigImpl.prototype.setProxy = function (proxyHostName, proxyPort, proxyUserName, proxyPassword) {
        this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName);
        this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyPort], proxyPort);
        this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName);
        this.setProperty(Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_ProxyPassword], proxyPassword);
    };
    /**
     * Gets an arbitrary property value.
     * @member SpeechTranslationConfigImpl.prototype.getProperty
     * @function
     * @public
     * @param {string} name - The name of the property.
     * @param {string} def - The default value of the property in case it is not set.
     * @returns {string} The value of the property.
     */
    SpeechTranslationConfigImpl.prototype.getProperty = function (name, def) {
        return this.privSpeechProperties.getProperty(name, def);
    };
    /**
     * Gets/Sets an arbitrary property value.
     * @member SpeechTranslationConfigImpl.prototype.setProperty
     * @function
     * @public
     * @param {string} name - The name of the property.
     * @param {string} value - The value of the property.
     */
    SpeechTranslationConfigImpl.prototype.setProperty = function (name, value) {
        this.privSpeechProperties.setProperty(name, value);
    };
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "properties", {
        /**
         * Provides access to custom properties.
         * @member SpeechTranslationConfigImpl.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The properties.
         */
        get: function () {
            return this.privSpeechProperties;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Dispose of associated resources.
     * @member SpeechTranslationConfigImpl.prototype.close
     * @function
     * @public
     */
    SpeechTranslationConfigImpl.prototype.close = function () {
        return;
    };
    SpeechTranslationConfigImpl.prototype.setServiceProperty = function (name, value, channel) {
        var currentProperties = JSON.parse(this.privSpeechProperties.getProperty(Exports_1.ServicePropertiesPropertyName, "{}"));
        currentProperties[name] = value;
        this.privSpeechProperties.setProperty(Exports_1.ServicePropertiesPropertyName, JSON.stringify(currentProperties));
    };
    SpeechTranslationConfigImpl.prototype.setProfanity = function (profanity) {
        this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceResponse_ProfanityOption, Exports_2.ProfanityOption[profanity]);
    };
    SpeechTranslationConfigImpl.prototype.enableAudioLogging = function () {
        this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, "true");
    };
    SpeechTranslationConfigImpl.prototype.requestWordLevelTimestamps = function () {
        this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "true");
    };
    SpeechTranslationConfigImpl.prototype.enableDictation = function () {
        this.privSpeechProperties.setProperty(Exports_1.ForceDictationPropertyName, "true");
    };
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "speechSynthesisLanguage", {
        get: function () {
            return this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthLanguage);
        },
        set: function (language) {
            this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthLanguage, language);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "speechSynthesisVoiceName", {
        get: function () {
            return this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthVoice);
        },
        set: function (voice) {
            this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthVoice, voice);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechTranslationConfigImpl.prototype, "speechSynthesisOutputFormat", {
        get: function () {
            return Exports_2.SpeechSynthesisOutputFormat[this.privSpeechProperties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)];
        },
        set: function (format) {
            this.privSpeechProperties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, Exports_2.SpeechSynthesisOutputFormat[format]);
        },
        enumerable: false,
        configurable: true
    });
    return SpeechTranslationConfigImpl;
}(SpeechTranslationConfig));
exports.SpeechTranslationConfigImpl = SpeechTranslationConfigImpl;



/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PropertyCollection = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Represents collection of properties and their values.
 * @class PropertyCollection
 */
var PropertyCollection = /** @class */ (function () {
    function PropertyCollection() {
        this.privKeys = [];
        this.privValues = [];
    }
    /**
     * Returns the property value in type String. The parameter must have the same type as String.
     * Currently only String, int and bool are allowed.
     * If the name is not available, the specified defaultValue is returned.
     * @member PropertyCollection.prototype.getProperty
     * @function
     * @public
     * @param {string} key - The parameter name.
     * @param {string} def - The default value which is returned if the parameter
     *        is not available in the collection.
     * @returns {string} value of the parameter.
     */
    PropertyCollection.prototype.getProperty = function (key, def) {
        var keyToUse;
        if (typeof key === "string") {
            keyToUse = key;
        }
        else {
            keyToUse = Exports_1.PropertyId[key];
        }
        for (var n = 0; n < this.privKeys.length; n++) {
            if (this.privKeys[n] === keyToUse) {
                return this.privValues[n];
            }
        }
        return def;
    };
    /**
     * Sets the String value of the parameter specified by name.
     * @member PropertyCollection.prototype.setProperty
     * @function
     * @public
     * @param {string} key - The parameter name.
     * @param {string} value - The value of the parameter.
     */
    PropertyCollection.prototype.setProperty = function (key, value) {
        var keyToUse;
        if (typeof key === "string") {
            keyToUse = key;
        }
        else {
            keyToUse = Exports_1.PropertyId[key];
        }
        for (var n = 0; n < this.privKeys.length; n++) {
            if (this.privKeys[n] === keyToUse) {
                this.privValues[n] = value;
                return;
            }
        }
        this.privKeys.push(keyToUse);
        this.privValues.push(value);
    };
    /**
     * Clones the collection.
     * @member PropertyCollection.prototype.clone
     * @function
     * @public
     * @returns {PropertyCollection} A copy of the collection.
     */
    PropertyCollection.prototype.clone = function () {
        var clonedMap = new PropertyCollection();
        for (var n = 0; n < this.privKeys.length; n++) {
            clonedMap.privKeys.push(this.privKeys[n]);
            clonedMap.privValues.push(this.privValues[n]);
        }
        return clonedMap;
    };
    /**
     * Merges this set of properties into another, no overwrites.
     * @member PropertyCollection.prototype.mergeTo
     * @function
     * @public
     * @param {PropertyCollection} The collection to merge into.
     */
    PropertyCollection.prototype.mergeTo = function (destinationCollection) {
        var _this = this;
        this.privKeys.forEach(function (key) {
            if (destinationCollection.getProperty(key, undefined) === undefined) {
                var value = _this.getProperty(key);
                destinationCollection.setProperty(key, value);
            }
        });
    };
    Object.defineProperty(PropertyCollection.prototype, "keys", {
        /**
         * Get the keys in Property Collection.
         * @member PropertyCollection.prototype.keys
         * @function
         * @public
         * @returns {string []} Keys in the collection.
         */
        get: function () {
            return this.privKeys;
        },
        enumerable: false,
        configurable: true
    });
    return PropertyCollection;
}());
exports.PropertyCollection = PropertyCollection;



/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PropertyId = void 0;
/**
 * Defines speech property ids.
 * @class PropertyId
 */
var PropertyId;
(function (PropertyId) {
    /**
     * The Cognitive Services Speech Service subscription Key. If you are using an intent recognizer, you need to specify
     * to specify the LUIS endpoint key for your particular LUIS app. Under normal circumstances, you shouldn't
     * have to use this property directly.
     * Instead, use [[SpeechConfig.fromSubscription]].
     * @member PropertyId.SpeechServiceConnection_Key
     */
    PropertyId[PropertyId["SpeechServiceConnection_Key"] = 0] = "SpeechServiceConnection_Key";
    /**
     * The Cognitive Services Speech Service endpoint (url). Under normal circumstances, you shouldn't
     * have to use this property directly.
     * Instead, use [[SpeechConfig.fromEndpoint]].
     * NOTE: This endpoint is not the same as the endpoint used to obtain an access token.
     * @member PropertyId.SpeechServiceConnection_Endpoint
     */
    PropertyId[PropertyId["SpeechServiceConnection_Endpoint"] = 1] = "SpeechServiceConnection_Endpoint";
    /**
     * The Cognitive Services Speech Service region. Under normal circumstances, you shouldn't have to
     * use this property directly.
     * Instead, use [[SpeechConfig.fromSubscription]], [[SpeechConfig.fromEndpoint]], [[SpeechConfig.fromAuthorizationToken]].
     * @member PropertyId.SpeechServiceConnection_Region
     */
    PropertyId[PropertyId["SpeechServiceConnection_Region"] = 2] = "SpeechServiceConnection_Region";
    /**
     * The Cognitive Services Speech Service authorization token (aka access token). Under normal circumstances,
     * you shouldn't have to use this property directly.
     * Instead, use [[SpeechConfig.fromAuthorizationToken]], [[SpeechRecognizer.authorizationToken]],
     * [[IntentRecognizer.authorizationToken]], [[TranslationRecognizer.authorizationToken]], [[SpeakerRecognizer.authorizationToken]].
     * @member PropertyId.SpeechServiceAuthorization_Token
     */
    PropertyId[PropertyId["SpeechServiceAuthorization_Token"] = 3] = "SpeechServiceAuthorization_Token";
    /**
     * The Cognitive Services Speech Service authorization type. Currently unused.
     * @member PropertyId.SpeechServiceAuthorization_Type
     */
    PropertyId[PropertyId["SpeechServiceAuthorization_Type"] = 4] = "SpeechServiceAuthorization_Type";
    /**
     * The Cognitive Services Speech Service endpoint id. Under normal circumstances, you shouldn't
     * have to use this property directly.
     * Instead, use [[SpeechConfig.endpointId]].
     * NOTE: The endpoint id is available in the Speech Portal, listed under Endpoint Details.
     * @member PropertyId.SpeechServiceConnection_EndpointId
     */
    PropertyId[PropertyId["SpeechServiceConnection_EndpointId"] = 5] = "SpeechServiceConnection_EndpointId";
    /**
     * The list of comma separated languages (BCP-47 format) used as target translation languages. Under normal circumstances,
     * you shouldn't have to use this property directly.
     * Instead use [[SpeechTranslationConfig.addTargetLanguage]],
     * [[SpeechTranslationConfig.targetLanguages]], [[TranslationRecognizer.targetLanguages]].
     * @member PropertyId.SpeechServiceConnection_TranslationToLanguages
     */
    PropertyId[PropertyId["SpeechServiceConnection_TranslationToLanguages"] = 6] = "SpeechServiceConnection_TranslationToLanguages";
    /**
     * The name of the Cognitive Service Text to Speech Service Voice. Under normal circumstances, you shouldn't have to use this
     * property directly.
     * Instead, use [[SpeechTranslationConfig.voiceName]].
     * NOTE: Valid voice names can be found <a href="https://aka.ms/csspeech/voicenames">here</a>.
     * @member PropertyId.SpeechServiceConnection_TranslationVoice
     */
    PropertyId[PropertyId["SpeechServiceConnection_TranslationVoice"] = 7] = "SpeechServiceConnection_TranslationVoice";
    /**
     * Translation features.
     * @member PropertyId.SpeechServiceConnection_TranslationFeatures
     */
    PropertyId[PropertyId["SpeechServiceConnection_TranslationFeatures"] = 8] = "SpeechServiceConnection_TranslationFeatures";
    /**
     * The Language Understanding Service Region. Under normal circumstances, you shouldn't have to use this property directly.
     * Instead, use [[LanguageUnderstandingModel]].
     * @member PropertyId.SpeechServiceConnection_IntentRegion
     */
    PropertyId[PropertyId["SpeechServiceConnection_IntentRegion"] = 9] = "SpeechServiceConnection_IntentRegion";
    /**
     * The host name of the proxy server used to connect to the Cognitive Services Speech Service. Only relevant in Node.js environments.
     * You shouldn't have to use this property directly.
     * Instead use <see cref="SpeechConfig.SetProxy(string,int,string,string)"/>.
     * Added in version 1.4.0.
     */
    PropertyId[PropertyId["SpeechServiceConnection_ProxyHostName"] = 10] = "SpeechServiceConnection_ProxyHostName";
    /**
     * The port of the proxy server used to connect to the Cognitive Services Speech Service. Only relevant in Node.js environments.
     * You shouldn't have to use this property directly.
     * Instead use <see cref="SpeechConfig.SetProxy(string,int,string,string)"/>.
     * Added in version 1.4.0.
     */
    PropertyId[PropertyId["SpeechServiceConnection_ProxyPort"] = 11] = "SpeechServiceConnection_ProxyPort";
    /**
     * The user name of the proxy server used to connect to the Cognitive Services Speech Service. Only relevant in Node.js environments.
     * You shouldn't have to use this property directly.
     * Instead use <see cref="SpeechConfig.SetProxy(string,int,string,string)"/>.
     * Added in version 1.4.0.
     */
    PropertyId[PropertyId["SpeechServiceConnection_ProxyUserName"] = 12] = "SpeechServiceConnection_ProxyUserName";
    /**
     * The password of the proxy server used to connect to the Cognitive Services Speech Service. Only relevant in Node.js environments.
     * You shouldn't have to use this property directly.
     * Instead use <see cref="SpeechConfig.SetProxy(string,int,string,string)"/>.
     * Added in version 1.4.0.
     */
    PropertyId[PropertyId["SpeechServiceConnection_ProxyPassword"] = 13] = "SpeechServiceConnection_ProxyPassword";
    /**
     * The Cognitive Services Speech Service recognition Mode. Can be "INTERACTIVE", "CONVERSATION", "DICTATION".
     * This property is intended to be read-only. The SDK is using it internally.
     * @member PropertyId.SpeechServiceConnection_RecoMode
     */
    PropertyId[PropertyId["SpeechServiceConnection_RecoMode"] = 14] = "SpeechServiceConnection_RecoMode";
    /**
     * The spoken language to be recognized (in BCP-47 format). Under normal circumstances, you shouldn't have to use this property
     * directly.
     * Instead, use [[SpeechConfig.speechRecognitionLanguage]].
     * @member PropertyId.SpeechServiceConnection_RecoLanguage
     */
    PropertyId[PropertyId["SpeechServiceConnection_RecoLanguage"] = 15] = "SpeechServiceConnection_RecoLanguage";
    /**
     * The session id. This id is a universally unique identifier (aka UUID) representing a specific binding of an audio input stream
     * and the underlying speech recognition instance to which it is bound. Under normal circumstances, you shouldn't have to use this
     * property directly.
     * Instead use [[SessionEventArgs.sessionId]].
     * @member PropertyId.Speech_SessionId
     */
    PropertyId[PropertyId["Speech_SessionId"] = 16] = "Speech_SessionId";
    /**
     * The spoken language to be synthesized (e.g. en-US)
     * @member PropertyId.SpeechServiceConnection_SynthLanguage
     */
    PropertyId[PropertyId["SpeechServiceConnection_SynthLanguage"] = 17] = "SpeechServiceConnection_SynthLanguage";
    /**
     * The name of the TTS voice to be used for speech synthesis
     * @member PropertyId.SpeechServiceConnection_SynthVoice
     */
    PropertyId[PropertyId["SpeechServiceConnection_SynthVoice"] = 18] = "SpeechServiceConnection_SynthVoice";
    /**
     * The string to specify TTS output audio format
     * @member PropertyId.SpeechServiceConnection_SynthOutputFormat
     */
    PropertyId[PropertyId["SpeechServiceConnection_SynthOutputFormat"] = 19] = "SpeechServiceConnection_SynthOutputFormat";
    /**
     * The list of comma separated languages used as possible source languages
     * Added in version 1.13.0
     * @member PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages
     */
    PropertyId[PropertyId["SpeechServiceConnection_AutoDetectSourceLanguages"] = 20] = "SpeechServiceConnection_AutoDetectSourceLanguages";
    /**
     * The requested Cognitive Services Speech Service response output format (simple or detailed). Under normal circumstances, you shouldn't have
     * to use this property directly.
     * Instead use [[SpeechConfig.outputFormat]].
     * @member PropertyId.SpeechServiceResponse_RequestDetailedResultTrueFalse
     */
    PropertyId[PropertyId["SpeechServiceResponse_RequestDetailedResultTrueFalse"] = 21] = "SpeechServiceResponse_RequestDetailedResultTrueFalse";
    /**
     * The requested Cognitive Services Speech Service response output profanity level. Currently unused.
     * @member PropertyId.SpeechServiceResponse_RequestProfanityFilterTrueFalse
     */
    PropertyId[PropertyId["SpeechServiceResponse_RequestProfanityFilterTrueFalse"] = 22] = "SpeechServiceResponse_RequestProfanityFilterTrueFalse";
    /**
     * The Cognitive Services Speech Service response output (in JSON format). This property is available on recognition result objects only.
     * @member PropertyId.SpeechServiceResponse_JsonResult
     */
    PropertyId[PropertyId["SpeechServiceResponse_JsonResult"] = 23] = "SpeechServiceResponse_JsonResult";
    /**
     * The Cognitive Services Speech Service error details (in JSON format). Under normal circumstances, you shouldn't have to
     * use this property directly. Instead use [[CancellationDetails.errorDetails]].
     * @member PropertyId.SpeechServiceResponse_JsonErrorDetails
     */
    PropertyId[PropertyId["SpeechServiceResponse_JsonErrorDetails"] = 24] = "SpeechServiceResponse_JsonErrorDetails";
    /**
     * The cancellation reason. Currently unused.
     * @member PropertyId.CancellationDetails_Reason
     */
    PropertyId[PropertyId["CancellationDetails_Reason"] = 25] = "CancellationDetails_Reason";
    /**
     * The cancellation text. Currently unused.
     * @member PropertyId.CancellationDetails_ReasonText
     */
    PropertyId[PropertyId["CancellationDetails_ReasonText"] = 26] = "CancellationDetails_ReasonText";
    /**
     * The Cancellation detailed text. Currently unused.
     * @member PropertyId.CancellationDetails_ReasonDetailedText
     */
    PropertyId[PropertyId["CancellationDetails_ReasonDetailedText"] = 27] = "CancellationDetails_ReasonDetailedText";
    /**
     * The Language Understanding Service response output (in JSON format). Available via [[IntentRecognitionResult]]
     * @member PropertyId.LanguageUnderstandingServiceResponse_JsonResult
     */
    PropertyId[PropertyId["LanguageUnderstandingServiceResponse_JsonResult"] = 28] = "LanguageUnderstandingServiceResponse_JsonResult";
    /**
     * The URL string built from speech configuration.
     * This property is intended to be read-only. The SDK is using it internally.
     * NOTE: Added in version 1.7.0.
     */
    PropertyId[PropertyId["SpeechServiceConnection_Url"] = 29] = "SpeechServiceConnection_Url";
    /**
     * The initial silence timeout value (in milliseconds) used by the service.
     * Added in version 1.7.0
     */
    PropertyId[PropertyId["SpeechServiceConnection_InitialSilenceTimeoutMs"] = 30] = "SpeechServiceConnection_InitialSilenceTimeoutMs";
    /**
     * The end silence timeout value (in milliseconds) used by the service.
     * Added in version 1.7.0
     */
    PropertyId[PropertyId["SpeechServiceConnection_EndSilenceTimeoutMs"] = 31] = "SpeechServiceConnection_EndSilenceTimeoutMs";
    /**
     * A boolean value specifying whether audio logging is enabled in the service or not.
     * Added in version 1.7.0
     */
    PropertyId[PropertyId["SpeechServiceConnection_EnableAudioLogging"] = 32] = "SpeechServiceConnection_EnableAudioLogging";
    /**
     * The requested Cognitive Services Speech Service response output profanity setting.
     * Allowed values are "masked", "removed", and "raw".
     * Added in version 1.7.0.
     */
    PropertyId[PropertyId["SpeechServiceResponse_ProfanityOption"] = 33] = "SpeechServiceResponse_ProfanityOption";
    /**
     * A string value specifying which post processing option should be used by service.
     * Allowed values are "TrueText".
     * Added in version 1.7.0
     */
    PropertyId[PropertyId["SpeechServiceResponse_PostProcessingOption"] = 34] = "SpeechServiceResponse_PostProcessingOption";
    /**
     *  A boolean value specifying whether to include word-level timestamps in the response result.
     * Added in version 1.7.0
     */
    PropertyId[PropertyId["SpeechServiceResponse_RequestWordLevelTimestamps"] = 35] = "SpeechServiceResponse_RequestWordLevelTimestamps";
    /**
     * The number of times a word has to be in partial results to be returned.
     * Added in version 1.7.0
     */
    PropertyId[PropertyId["SpeechServiceResponse_StablePartialResultThreshold"] = 36] = "SpeechServiceResponse_StablePartialResultThreshold";
    /**
     * A string value specifying the output format option in the response result. Internal use only.
     * Added in version 1.7.0.
     */
    PropertyId[PropertyId["SpeechServiceResponse_OutputFormatOption"] = 37] = "SpeechServiceResponse_OutputFormatOption";
    /**
     * A boolean value to request for stabilizing translation partial results by omitting words in the end.
     * Added in version 1.7.0.
     */
    PropertyId[PropertyId["SpeechServiceResponse_TranslationRequestStablePartialResult"] = 38] = "SpeechServiceResponse_TranslationRequestStablePartialResult";
    /**
     * Identifier used to connect to the backend service.
     * @member PropertyId.Conversation_ApplicationId
     */
    PropertyId[PropertyId["Conversation_ApplicationId"] = 39] = "Conversation_ApplicationId";
    /**
     * Type of dialog backend to connect to.
     * @member PropertyId.Conversation_DialogType
     */
    PropertyId[PropertyId["Conversation_DialogType"] = 40] = "Conversation_DialogType";
    /**
     * Silence timeout for listening
     * @member PropertyId.Conversation_Initial_Silence_Timeout
     */
    PropertyId[PropertyId["Conversation_Initial_Silence_Timeout"] = 41] = "Conversation_Initial_Silence_Timeout";
    /**
     * From Id to add to speech recognition activities.
     * @member PropertyId.Conversation_From_Id
     */
    PropertyId[PropertyId["Conversation_From_Id"] = 42] = "Conversation_From_Id";
    /**
     * ConversationId for the session.
     * @member PropertyId.Conversation_Conversation_Id
     */
    PropertyId[PropertyId["Conversation_Conversation_Id"] = 43] = "Conversation_Conversation_Id";
    /**
     * Comma separated list of custom voice deployment ids.
     * @member PropertyId.Conversation_Custom_Voice_Deployment_Ids
     */
    PropertyId[PropertyId["Conversation_Custom_Voice_Deployment_Ids"] = 44] = "Conversation_Custom_Voice_Deployment_Ids";
    /**
     * Speech activity template, stamp properties from the template on the activity generated by the service for speech.
     * @member PropertyId.Conversation_Speech_Activity_Template
     * Added in version 1.10.0.
     */
    PropertyId[PropertyId["Conversation_Speech_Activity_Template"] = 45] = "Conversation_Speech_Activity_Template";
    /**
     * Enables or disables the receipt of turn status messages as obtained on the turnStatusReceived event.
     * @member PropertyId.Conversation_Request_Bot_Status_Messages
     * Added in version 1.15.0.
     */
    PropertyId[PropertyId["Conversation_Request_Bot_Status_Messages"] = 46] = "Conversation_Request_Bot_Status_Messages";
    /**
     * Specifies the connection ID to be provided in the Agent configuration message, e.g. a Direct Line token for
     * channel authentication.
     * Added in version 1.15.1.
     */
    PropertyId[PropertyId["Conversation_Agent_Connection_Id"] = 47] = "Conversation_Agent_Connection_Id";
    /**
     * The Cognitive Services Speech Service host (url). Under normal circumstances, you shouldn't have to use this property directly.
     * Instead, use [[SpeechConfig.fromHost]].
     */
    PropertyId[PropertyId["SpeechServiceConnection_Host"] = 48] = "SpeechServiceConnection_Host";
    /**
     * Set the host for service calls to the Conversation Translator REST management and websocket calls.
     */
    PropertyId[PropertyId["ConversationTranslator_Host"] = 49] = "ConversationTranslator_Host";
    /**
     * Optionally set the the host's display name.
     * Used when joining a conversation.
     */
    PropertyId[PropertyId["ConversationTranslator_Name"] = 50] = "ConversationTranslator_Name";
    /**
     * Optionally set a value for the X-CorrelationId request header.
     * Used for troubleshooting errors in the server logs. It should be a valid guid.
     */
    PropertyId[PropertyId["ConversationTranslator_CorrelationId"] = 51] = "ConversationTranslator_CorrelationId";
    /**
     * Set the conversation token to be sent to the speech service. This enables the
     * service to service call from the speech service to the Conversation Translator service for relaying
     * recognitions. For internal use.
     */
    PropertyId[PropertyId["ConversationTranslator_Token"] = 52] = "ConversationTranslator_Token";
    /**
     * The reference text of the audio for pronunciation evaluation.
     * For this and the following pronunciation assessment parameters, see
     * https://docs.microsoft.com/azure/cognitive-services/speech-service/rest-speech-to-text#pronunciation-assessment-parameters for details.
     * Under normal circumstances, you shouldn't have to use this property directly.
     * Added in version 1.15.0
     */
    PropertyId[PropertyId["PronunciationAssessment_ReferenceText"] = 53] = "PronunciationAssessment_ReferenceText";
    /**
     * The point system for pronunciation score calibration (FivePoint or HundredMark).
     * Under normal circumstances, you shouldn't have to use this property directly.
     * Added in version 1.15.0
     */
    PropertyId[PropertyId["PronunciationAssessment_GradingSystem"] = 54] = "PronunciationAssessment_GradingSystem";
    /**
     * The pronunciation evaluation granularity (Phoneme, Word, or FullText).
     * Under normal circumstances, you shouldn't have to use this property directly.
     * Added in version 1.15.0
     */
    PropertyId[PropertyId["PronunciationAssessment_Granularity"] = 55] = "PronunciationAssessment_Granularity";
    /**
     * Defines if enable miscue calculation.
     * With this enabled, the pronounced words will be compared to the reference text,
     * and will be marked with omission/insertion based on the comparison. The default setting is False.
     * Under normal circumstances, you shouldn't have to use this property directly.
     * Added in version 1.15.0
     */
    PropertyId[PropertyId["PronunciationAssessment_EnableMiscue"] = 56] = "PronunciationAssessment_EnableMiscue";
    /**
     * The json string of pronunciation assessment parameters
     * Under normal circumstances, you shouldn't have to use this property directly.
     * Added in version 1.15.0
     */
    PropertyId[PropertyId["PronunciationAssessment_Json"] = 57] = "PronunciationAssessment_Json";
    /**
     * Pronunciation assessment parameters.
     * This property is intended to be read-only. The SDK is using it internally.
     * Added in version 1.15.0
     */
    PropertyId[PropertyId["PronunciationAssessment_Params"] = 58] = "PronunciationAssessment_Params";
    /**
     * Version of Speaker Recognition API to use.
     * Added in version 1.18.0
     */
    PropertyId[PropertyId["SpeakerRecognition_Api_Version"] = 59] = "SpeakerRecognition_Api_Version";
})(PropertyId = exports.PropertyId || (exports.PropertyId = {}));



/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Recognizer = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
/**
 * Defines the base class Recognizer which mainly contains common event handlers.
 * @class Recognizer
 */
var Recognizer = /** @class */ (function () {
    /**
     * Creates and initializes an instance of a Recognizer
     * @constructor
     * @param {AudioConfig} audioInput - An optional audio input stream associated with the recognizer
     */
    function Recognizer(audioConfig, properties, connectionFactory) {
        this.audioConfig = (audioConfig !== undefined) ? audioConfig : Exports_3.AudioConfig.fromDefaultMicrophoneInput();
        this.privDisposed = false;
        this.privProperties = properties.clone();
        this.privConnectionFactory = connectionFactory;
        this.implCommonRecognizerSetup();
    }
    /**
     * Dispose of associated resources.
     * @member Recognizer.prototype.close
     * @function
     * @public
     */
    Recognizer.prototype.close = function (cb, errorCb) {
        Contracts_1.Contracts.throwIfDisposed(this.privDisposed);
        Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);
    };
    Object.defineProperty(Recognizer.prototype, "internalData", {
        /**
         * @Internal
         * Internal data member to support fromRecognizer* pattern methods on other classes.
         * Do not use externally, object returned will change without warning or notice.
         */
        get: function () {
            return this.privReco;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * This method performs cleanup of resources.
     * The Boolean parameter disposing indicates whether the method is called
     * from Dispose (if disposing is true) or from the finalizer (if disposing is false).
     * Derived classes should override this method to dispose resource if needed.
     * @member Recognizer.prototype.dispose
     * @function
     * @public
     * @param {boolean} disposing - Flag to request disposal.
     */
    Recognizer.prototype.dispose = function (disposing) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privDisposed) {
                            return [2 /*return*/];
                        }
                        this.privDisposed = true;
                        if (!disposing) return [3 /*break*/, 3];
                        if (!this.privReco) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.privReco.audioSource.turnOff()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.privReco.dispose()];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    Object.defineProperty(Recognizer, "telemetryEnabled", {
        /**
         * This method returns the current state of the telemetry setting.
         * @member Recognizer.prototype.telemetryEnabled
         * @function
         * @public
         * @returns true if the telemetry is enabled, false otherwise.
         */
        get: function () {
            return Exports_1.ServiceRecognizerBase.telemetryDataEnabled;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * This method globally enables or disables telemetry.
     * @member Recognizer.prototype.enableTelemetry
     * @function
     * @public
     * @param enabled - Global setting for telemetry collection.
     * If set to true, telemetry information like microphone errors,
     * recognition errors are collected and sent to Microsoft.
     * If set to false, no telemetry is sent to Microsoft.
     */
    /* tslint:disable:member-ordering */
    Recognizer.enableTelemetry = function (enabled) {
        Exports_1.ServiceRecognizerBase.telemetryDataEnabled = enabled;
    };
    // Does the generic recognizer setup that is common across all recognizer types.
    Recognizer.prototype.implCommonRecognizerSetup = function () {
        var osPlatform = (typeof window !== "undefined") ? "Browser" : "Node";
        var osName = "unknown";
        var osVersion = "unknown";
        if (typeof navigator !== "undefined") {
            osPlatform = osPlatform + "/" + navigator.platform;
            osName = navigator.userAgent;
            osVersion = navigator.appVersion;
        }
        var recognizerConfig = this.createRecognizerConfig(new Exports_1.SpeechServiceConfig(new Exports_1.Context(new Exports_1.OS(osPlatform, osName, osVersion))));
        this.privReco = this.createServiceRecognizer(Recognizer.getAuthFromProperties(this.privProperties), this.privConnectionFactory, this.audioConfig, recognizerConfig);
    };
    Recognizer.prototype.recognizeOnceAsyncImpl = function (recognitionMode) {
        return __awaiter(this, void 0, void 0, function () {
            var ret, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        Contracts_1.Contracts.throwIfDisposed(this.privDisposed);
                        ret = new Exports_2.Deferred();
                        return [4 /*yield*/, this.implRecognizerStop()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.privReco.recognize(recognitionMode, ret.resolve, ret.reject)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, ret.promise];
                    case 3:
                        result = _a.sent();
                        return [4 /*yield*/, this.implRecognizerStop()];
                    case 4:
                        _a.sent();
                        return [2 /*return*/, result];
                }
            });
        });
    };
    Recognizer.prototype.startContinuousRecognitionAsyncImpl = function (recognitionMode) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        Contracts_1.Contracts.throwIfDisposed(this.privDisposed);
                        return [4 /*yield*/, this.implRecognizerStop()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.privReco.recognize(recognitionMode, undefined, undefined)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    Recognizer.prototype.stopContinuousRecognitionAsyncImpl = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        Contracts_1.Contracts.throwIfDisposed(this.privDisposed);
                        return [4 /*yield*/, this.implRecognizerStop()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    Recognizer.prototype.implRecognizerStop = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.privReco) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.privReco.stopRecognizing()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    Recognizer.getAuthFromProperties = function (properties) {
        var subscriptionKey = properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Key, undefined);
        var authentication = (subscriptionKey && subscriptionKey !== "") ?
            new Exports_1.CognitiveSubscriptionKeyAuthentication(subscriptionKey) :
            new Exports_1.CognitiveTokenAuthentication(function (authFetchEventId) {
                var authorizationToken = properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, undefined);
                return Promise.resolve(authorizationToken);
            }, function (authFetchEventId) {
                var authorizationToken = properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, undefined);
                return Promise.resolve(authorizationToken);
            });
        return authentication;
    };
    return Recognizer;
}());
exports.Recognizer = Recognizer;



/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechRecognizer = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
/**
 * Performs speech recognition from microphone, file, or other audio input streams, and gets transcribed text as result.
 * @class SpeechRecognizer
 */
var SpeechRecognizer = /** @class */ (function (_super) {
    __extends(SpeechRecognizer, _super);
    /**
     * SpeechRecognizer constructor.
     * @constructor
     * @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer
     * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer
     */
    function SpeechRecognizer(speechConfig, audioConfig) {
        var _this = this;
        var speechConfigImpl = speechConfig;
        Contracts_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig");
        Contracts_1.Contracts.throwIfNullOrWhitespace(speechConfigImpl.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
        _this = _super.call(this, audioConfig, speechConfigImpl.properties, new Exports_1.SpeechConnectionFactory()) || this;
        _this.privDisposedRecognizer = false;
        return _this;
    }
    /**
     * SpeechRecognizer constructor.
     * @constructor
     * @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer
     * @param {AutoDetectSourceLanguageConfig} autoDetectSourceLanguageConfig - An source language detection configuration associated with the recognizer
     * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer
     */
    SpeechRecognizer.FromConfig = function (speechConfig, autoDetectSourceLanguageConfig, audioConfig) {
        var speechConfigImpl = speechConfig;
        autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties);
        var recognizer = new SpeechRecognizer(speechConfig, audioConfig);
        return recognizer;
    };
    Object.defineProperty(SpeechRecognizer.prototype, "endpointId", {
        /**
         * Gets the endpoint id of a customized speech model that is used for speech recognition.
         * @member SpeechRecognizer.prototype.endpointId
         * @function
         * @public
         * @returns {string} the endpoint id of a customized speech model that is used for speech recognition.
         */
        get: function () {
            Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_EndpointId, "00000000-0000-0000-0000-000000000000");
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechRecognizer.prototype, "authorizationToken", {
        /**
         * Gets the authorization token used to communicate with the service.
         * @member SpeechRecognizer.prototype.authorizationToken
         * @function
         * @public
         * @returns {string} Authorization token.
         */
        get: function () {
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token);
        },
        /**
         * Gets/Sets the authorization token used to communicate with the service.
         * @member SpeechRecognizer.prototype.authorizationToken
         * @function
         * @public
         * @param {string} token - Authorization token.
         */
        set: function (token) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token");
            this.properties.setProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, token);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechRecognizer.prototype, "speechRecognitionLanguage", {
        /**
         * Gets the spoken language of recognition.
         * @member SpeechRecognizer.prototype.speechRecognitionLanguage
         * @function
         * @public
         * @returns {string} The spoken language of recognition.
         */
        get: function () {
            Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechRecognizer.prototype, "outputFormat", {
        /**
         * Gets the output format of recognition.
         * @member SpeechRecognizer.prototype.outputFormat
         * @function
         * @public
         * @returns {OutputFormat} The output format of recognition.
         */
        get: function () {
            Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
            if (this.properties.getProperty(Exports_1.OutputFormatPropertyName, Exports_3.OutputFormat[Exports_3.OutputFormat.Simple]) === Exports_3.OutputFormat[Exports_3.OutputFormat.Simple]) {
                return Exports_3.OutputFormat.Simple;
            }
            else {
                return Exports_3.OutputFormat.Detailed;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechRecognizer.prototype, "properties", {
        /**
         * The collection of properties and their values defined for this SpeechRecognizer.
         * @member SpeechRecognizer.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The collection of properties and their values defined for this SpeechRecognizer.
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Starts speech recognition, and stops after the first utterance is recognized.
     * The task returns the recognition text as result.
     * Note: RecognizeOnceAsync() returns when the first utterance has been recognized,
     *       so it is suitable only for single shot recognition
     *       like command or query. For long-running recognition, use StartContinuousRecognitionAsync() instead.
     * @member SpeechRecognizer.prototype.recognizeOnceAsync
     * @function
     * @public
     * @param cb - Callback that received the SpeechRecognitionResult.
     * @param err - Callback invoked in case of an error.
     */
    SpeechRecognizer.prototype.recognizeOnceAsync = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(Exports_1.RecognitionMode.Interactive), cb, err);
    };
    /**
     * Starts speech recognition, until stopContinuousRecognitionAsync() is called.
     * User must subscribe to events to receive recognition results.
     * @member SpeechRecognizer.prototype.startContinuousRecognitionAsync
     * @function
     * @public
     * @param cb - Callback invoked once the recognition has started.
     * @param err - Callback invoked in case of an error.
     */
    SpeechRecognizer.prototype.startContinuousRecognitionAsync = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(Exports_1.RecognitionMode.Conversation), cb, err);
    };
    /**
     * Stops continuous speech recognition.
     * @member SpeechRecognizer.prototype.stopContinuousRecognitionAsync
     * @function
     * @public
     * @param cb - Callback invoked once the recognition has stopped.
     * @param err - Callback invoked in case of an error.
     */
    SpeechRecognizer.prototype.stopContinuousRecognitionAsync = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);
    };
    /**
     * Starts speech recognition with keyword spotting, until
     * stopKeywordRecognitionAsync() is called.
     * User must subscribe to events to receive recognition results.
     * Note: Key word spotting functionality is only available on the
     *      Speech Devices SDK. This functionality is currently not included in the SDK itself.
     * @member SpeechRecognizer.prototype.startKeywordRecognitionAsync
     * @function
     * @public
     * @param {KeywordRecognitionModel} model The keyword recognition model that
     *        specifies the keyword to be recognized.
     * @param cb - Callback invoked once the recognition has started.
     * @param err - Callback invoked in case of an error.
     */
    SpeechRecognizer.prototype.startKeywordRecognitionAsync = function (model, cb, err) {
        Contracts_1.Contracts.throwIfNull(model, "model");
        if (!!err) {
            err("Not yet implemented.");
        }
    };
    /**
     * Stops continuous speech recognition.
     * Note: Key word spotting functionality is only available on the
     *       Speech Devices SDK. This functionality is currently not included in the SDK itself.
     * @member SpeechRecognizer.prototype.stopKeywordRecognitionAsync
     * @function
     * @public
     * @param cb - Callback invoked once the recognition has stopped.
     * @param err - Callback invoked in case of an error.
     */
    SpeechRecognizer.prototype.stopKeywordRecognitionAsync = function (cb, err) {
        if (!!cb) {
            cb();
        }
    };
    /**
     * closes all external resources held by an instance of this class.
     * @member SpeechRecognizer.prototype.close
     * @function
     * @public
     */
    SpeechRecognizer.prototype.close = function (cb, errorCb) {
        Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
        Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);
    };
    /**
     * Disposes any resources held by the object.
     * @member SpeechRecognizer.prototype.dispose
     * @function
     * @public
     * @param {boolean} disposing - true if disposing the object.
     */
    SpeechRecognizer.prototype.dispose = function (disposing) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privDisposedRecognizer) {
                            return [2 /*return*/];
                        }
                        if (!disposing) return [3 /*break*/, 2];
                        this.privDisposedRecognizer = true;
                        return [4 /*yield*/, this.implRecognizerStop()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    SpeechRecognizer.prototype.createRecognizerConfig = function (speechConfig) {
        return new Exports_1.RecognizerConfig(speechConfig, this.properties);
    };
    SpeechRecognizer.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) {
        var configImpl = audioConfig;
        return new Exports_1.SpeechServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);
    };
    return SpeechRecognizer;
}(Exports_3.Recognizer));
exports.SpeechRecognizer = SpeechRecognizer;



/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentRecognizer = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
/**
 * Intent recognizer.
 * @class
 */
var IntentRecognizer = /** @class */ (function (_super) {
    __extends(IntentRecognizer, _super);
    /**
     * Initializes an instance of the IntentRecognizer.
     * @constructor
     * @param {SpeechConfig} speechConfig - The set of configuration properties.
     * @param {AudioConfig} audioConfig - An optional audio input config associated with the recognizer
     */
    function IntentRecognizer(speechConfig, audioConfig) {
        var _this = this;
        Contracts_1.Contracts.throwIfNullOrUndefined(speechConfig, "speechConfig");
        var configImpl = speechConfig;
        Contracts_1.Contracts.throwIfNullOrUndefined(configImpl, "speechConfig");
        _this = _super.call(this, audioConfig, configImpl.properties, new Exports_1.IntentConnectionFactory()) || this;
        _this.privAddedIntents = [];
        _this.privAddedLmIntents = {};
        _this.privDisposedIntentRecognizer = false;
        _this.privProperties = configImpl.properties;
        Contracts_1.Contracts.throwIfNullOrWhitespace(_this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
        return _this;
    }
    Object.defineProperty(IntentRecognizer.prototype, "speechRecognitionLanguage", {
        /**
         * Gets the spoken language of recognition.
         * @member IntentRecognizer.prototype.speechRecognitionLanguage
         * @function
         * @public
         * @returns {string} the spoken language of recognition.
         */
        get: function () {
            Contracts_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(IntentRecognizer.prototype, "authorizationToken", {
        /**
         * Gets the authorization token used to communicate with the service.
         * @member IntentRecognizer.prototype.authorizationToken
         * @function
         * @public
         * @returns {string} Authorization token.
         */
        get: function () {
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token);
        },
        /**
         * Gets/Sets the authorization token used to communicate with the service.
         * Note: Please use a token derived from your LanguageUnderstanding subscription key for the Intent recognizer.
         * @member IntentRecognizer.prototype.authorizationToken
         * @function
         * @public
         * @param {string} value - Authorization token.
         */
        set: function (value) {
            this.properties.setProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(IntentRecognizer.prototype, "properties", {
        /**
         * The collection of properties and their values defined for this IntentRecognizer.
         * @member IntentRecognizer.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The collection of properties and their
         *          values defined for this IntentRecognizer.
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Starts intent recognition, and stops after the first utterance is recognized.
     * The task returns the recognition text and intent as result.
     * Note: RecognizeOnceAsync() returns when the first utterance has been recognized,
     *       so it is suitable only for single shot recognition like command or query.
     *       For long-running recognition, use StartContinuousRecognitionAsync() instead.
     * @member IntentRecognizer.prototype.recognizeOnceAsync
     * @function
     * @public
     * @param cb - Callback that received the recognition has finished with an IntentRecognitionResult.
     * @param err - Callback invoked in case of an error.
     */
    IntentRecognizer.prototype.recognizeOnceAsync = function (cb, err) {
        Contracts_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);
        if (Object.keys(this.privAddedLmIntents).length !== 0 || undefined !== this.privUmbrellaIntent) {
            var context = this.buildSpeechContext();
            this.privReco.speechContext.setSection("intent", context.Intent);
            this.privReco.dynamicGrammar.addReferenceGrammar(context.ReferenceGrammars);
            var intentReco = this.privReco;
            intentReco.setIntents(this.privAddedLmIntents, this.privUmbrellaIntent);
        }
        Exports_2.marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(Exports_1.RecognitionMode.Interactive), cb, err);
    };
    /**
     * Starts speech recognition, until stopContinuousRecognitionAsync() is called.
     * User must subscribe to events to receive recognition results.
     * @member IntentRecognizer.prototype.startContinuousRecognitionAsync
     * @function
     * @public
     * @param cb - Callback invoked once the recognition has started.
     * @param err - Callback invoked in case of an error.
     */
    IntentRecognizer.prototype.startContinuousRecognitionAsync = function (cb, err) {
        if (Object.keys(this.privAddedLmIntents).length !== 0 || undefined !== this.privUmbrellaIntent) {
            var context = this.buildSpeechContext();
            this.privReco.speechContext.setSection("intent", context.Intent);
            this.privReco.dynamicGrammar.addReferenceGrammar(context.ReferenceGrammars);
            var intentReco = this.privReco;
            intentReco.setIntents(this.privAddedLmIntents, this.privUmbrellaIntent);
        }
        Exports_2.marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(Exports_1.RecognitionMode.Conversation), cb, err);
    };
    /**
     * Stops continuous intent recognition.
     * @member IntentRecognizer.prototype.stopContinuousRecognitionAsync
     * @function
     * @public
     * @param cb - Callback invoked once the recognition has stopped.
     * @param err - Callback invoked in case of an error.
     */
    IntentRecognizer.prototype.stopContinuousRecognitionAsync = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);
    };
    /**
     * Starts speech recognition with keyword spotting, until stopKeywordRecognitionAsync() is called.
     * User must subscribe to events to receive recognition results.
     * Note: Key word spotting functionality is only available on the Speech Devices SDK.
     *       This functionality is currently not included in the SDK itself.
     * @member IntentRecognizer.prototype.startKeywordRecognitionAsync
     * @function
     * @public
     * @param {KeywordRecognitionModel} model - The keyword recognition model that specifies the keyword to be recognized.
     * @param cb - Callback invoked once the recognition has started.
     * @param err - Callback invoked in case of an error.
     */
    IntentRecognizer.prototype.startKeywordRecognitionAsync = function (model, cb, err) {
        Contracts_1.Contracts.throwIfNull(model, "model");
        if (!!err) {
            err("Not yet implemented.");
        }
    };
    /**
     * Stops continuous speech recognition.
     * Note: Key word spotting functionality is only available on the Speech Devices SDK.
     *       This functionality is currently not included in the SDK itself.
     * @member IntentRecognizer.prototype.stopKeywordRecognitionAsync
     * @function
     * @public
     * @param cb - Callback invoked once the recognition has stopped.
     * @param err - Callback invoked in case of an error.
     */
    IntentRecognizer.prototype.stopKeywordRecognitionAsync = function (cb, err) {
        if (!!cb) {
            cb();
        }
    };
    /**
     * Adds a phrase that should be recognized as intent.
     * @member IntentRecognizer.prototype.addIntent
     * @function
     * @public
     * @param {string} intentId - A String that represents the identifier of the intent to be recognized.
     * @param {string} phrase - A String that specifies the phrase representing the intent.
     */
    IntentRecognizer.prototype.addIntent = function (simplePhrase, intentId) {
        Contracts_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);
        Contracts_1.Contracts.throwIfNullOrWhitespace(intentId, "intentId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(simplePhrase, "simplePhrase");
        this.privAddedIntents.push([intentId, simplePhrase]);
    };
    /**
     * Adds an intent from Language Understanding service for recognition.
     * @member IntentRecognizer.prototype.addIntentWithLanguageModel
     * @function
     * @public
     * @param {string} intentId - A String that represents the identifier of the intent
     *        to be recognized. Ignored if intentName is empty.
     * @param {string} model - The intent model from Language Understanding service.
     * @param {string} intentName - The intent name defined in the intent model. If it
     *        is empty, all intent names defined in the model will be added.
     */
    IntentRecognizer.prototype.addIntentWithLanguageModel = function (intentId, model, intentName) {
        Contracts_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);
        Contracts_1.Contracts.throwIfNullOrWhitespace(intentId, "intentId");
        Contracts_1.Contracts.throwIfNull(model, "model");
        var modelImpl = model;
        Contracts_1.Contracts.throwIfNullOrWhitespace(modelImpl.appId, "model.appId");
        this.privAddedLmIntents[intentId] = new Exports_1.AddedLmIntent(modelImpl, intentName);
    };
    /**
     * @summary Adds all intents from the specified Language Understanding Model.
     * @member IntentRecognizer.prototype.addAllIntents
     * @function
     * @public
     * @function
     * @public
     * @param {LanguageUnderstandingModel} model - The language understanding model containing the intents.
     * @param {string} intentId - A custom id String to be returned in the IntentRecognitionResult's getIntentId() method.
     */
    IntentRecognizer.prototype.addAllIntents = function (model, intentId) {
        Contracts_1.Contracts.throwIfNull(model, "model");
        var modelImpl = model;
        Contracts_1.Contracts.throwIfNullOrWhitespace(modelImpl.appId, "model.appId");
        this.privUmbrellaIntent = new Exports_1.AddedLmIntent(modelImpl, intentId);
    };
    /**
     * closes all external resources held by an instance of this class.
     * @member IntentRecognizer.prototype.close
     * @function
     * @public
     */
    IntentRecognizer.prototype.close = function (cb, errorCb) {
        Contracts_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);
        Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);
    };
    IntentRecognizer.prototype.createRecognizerConfig = function (speechConfig) {
        return new Exports_1.RecognizerConfig(speechConfig, this.properties);
    };
    IntentRecognizer.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) {
        var audioImpl = audioConfig;
        return new Exports_1.IntentServiceRecognizer(authentication, connectionFactory, audioImpl, recognizerConfig, this);
    };
    IntentRecognizer.prototype.dispose = function (disposing) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privDisposedIntentRecognizer) {
                            return [2 /*return*/];
                        }
                        if (!disposing) return [3 /*break*/, 2];
                        this.privDisposedIntentRecognizer = true;
                        return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    IntentRecognizer.prototype.buildSpeechContext = function () {
        var appId;
        var region;
        var subscriptionKey;
        var refGrammers = [];
        if (undefined !== this.privUmbrellaIntent) {
            appId = this.privUmbrellaIntent.modelImpl.appId;
            region = this.privUmbrellaIntent.modelImpl.region;
            subscriptionKey = this.privUmbrellaIntent.modelImpl.subscriptionKey;
        }
        // Build the reference grammer array.
        for (var _i = 0, _a = Object.keys(this.privAddedLmIntents); _i < _a.length; _i++) {
            var intentId = _a[_i];
            var addedLmIntent = this.privAddedLmIntents[intentId];
            // validate all the same model, region, and key...
            if (appId === undefined) {
                appId = addedLmIntent.modelImpl.appId;
            }
            else {
                if (appId !== addedLmIntent.modelImpl.appId) {
                    throw new Error("Intents must all be from the same LUIS model");
                }
            }
            if (region === undefined) {
                region = addedLmIntent.modelImpl.region;
            }
            else {
                if (region !== addedLmIntent.modelImpl.region) {
                    throw new Error("Intents must all be from the same LUIS model in a single region");
                }
            }
            if (subscriptionKey === undefined) {
                subscriptionKey = addedLmIntent.modelImpl.subscriptionKey;
            }
            else {
                if (subscriptionKey !== addedLmIntent.modelImpl.subscriptionKey) {
                    throw new Error("Intents must all use the same subscription key");
                }
            }
            var grammer = "luis/" + appId + "-PRODUCTION#" + intentId;
            refGrammers.push(grammer);
        }
        return {
            Intent: {
                id: appId,
                key: (subscriptionKey === undefined) ? this.privProperties.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Key]) : subscriptionKey,
                provider: "LUIS",
            },
            ReferenceGrammars: (undefined === this.privUmbrellaIntent) ? refGrammers : ["luis/" + appId + "-PRODUCTION"],
        };
    };
    return IntentRecognizer;
}(Exports_3.Recognizer));
exports.IntentRecognizer = IntentRecognizer;



/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfileType = void 0;
/**
 * Output format
 * @class VoiceProfileType
 */
var VoiceProfileType;
(function (VoiceProfileType) {
    /**
     * Text independent speaker identification
     * @member VoiceProfileType.TextIndependentIdentification
     */
    VoiceProfileType[VoiceProfileType["TextIndependentIdentification"] = 0] = "TextIndependentIdentification";
    /**
     * Text dependent speaker verification
     * @member VoiceProfileType.TextDependentVerification
     */
    VoiceProfileType[VoiceProfileType["TextDependentVerification"] = 1] = "TextDependentVerification";
    /**
     * Text independent speaker verification
     * @member VoiceProfileType.TextIndependentVerification
     */
    VoiceProfileType[VoiceProfileType["TextIndependentVerification"] = 2] = "TextIndependentVerification";
})(VoiceProfileType = exports.VoiceProfileType || (exports.VoiceProfileType = {}));



/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationRecognizer = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var Connection_1 = __webpack_require__(105);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
/**
 * Translation recognizer
 * @class TranslationRecognizer
 */
var TranslationRecognizer = /** @class */ (function (_super) {
    __extends(TranslationRecognizer, _super);
    /**
     * Initializes an instance of the TranslationRecognizer.
     * @constructor
     * @param {SpeechTranslationConfig} speechConfig - Set of properties to configure this recognizer.
     * @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer
     */
    function TranslationRecognizer(speechConfig, audioConfig) {
        var _this = this;
        var configImpl = speechConfig;
        Contracts_1.Contracts.throwIfNull(configImpl, "speechConfig");
        _this = _super.call(this, audioConfig, configImpl.properties, new Exports_1.TranslationConnectionFactory()) || this;
        _this.privDisposedTranslationRecognizer = false;
        if (_this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationVoice, undefined) !== undefined) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(_this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationVoice), Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_TranslationVoice]);
        }
        Contracts_1.Contracts.throwIfNullOrWhitespace(_this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages), Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages]);
        Contracts_1.Contracts.throwIfNullOrWhitespace(_this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
        return _this;
    }
    Object.defineProperty(TranslationRecognizer.prototype, "speechRecognitionLanguage", {
        /**
         * Gets the language name that was set when the recognizer was created.
         * @member TranslationRecognizer.prototype.speechRecognitionLanguage
         * @function
         * @public
         * @returns {string} Gets the language name that was set when the recognizer was created.
         */
        get: function () {
            Contracts_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationRecognizer.prototype, "targetLanguages", {
        /**
         * Gets target languages for translation that were set when the recognizer was created.
         * The language is specified in BCP-47 format. The translation will provide translated text for each of language.
         * @member TranslationRecognizer.prototype.targetLanguages
         * @function
         * @public
         * @returns {string[]} Gets target languages for translation that were set when the recognizer was created.
         */
        get: function () {
            Contracts_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationRecognizer.prototype, "voiceName", {
        /**
         * Gets the name of output voice.
         * @member TranslationRecognizer.prototype.voiceName
         * @function
         * @public
         * @returns {string} the name of output voice.
         */
        get: function () {
            Contracts_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationVoice, undefined);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationRecognizer.prototype, "authorizationToken", {
        /**
         * Gets the authorization token used to communicate with the service.
         * @member TranslationRecognizer.prototype.authorizationToken
         * @function
         * @public
         * @returns {string} Authorization token.
         */
        get: function () {
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token);
        },
        /**
         * Gets/Sets the authorization token used to communicate with the service.
         * @member TranslationRecognizer.prototype.authorizationToken
         * @function
         * @public
         * @param {string} value - Authorization token.
         */
        set: function (value) {
            this.properties.setProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, value);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationRecognizer.prototype, "properties", {
        /**
         * The collection of properties and their values defined for this TranslationRecognizer.
         * @member TranslationRecognizer.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The collection of properties and their values defined for this TranslationRecognizer.
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Starts recognition and translation, and stops after the first utterance is recognized.
     * The task returns the translation text as result.
     * Note: recognizeOnceAsync returns when the first utterance has been recognized, so it is suitableonly
     *       for single shot recognition like command or query. For long-running recognition,
     *       use startContinuousRecognitionAsync() instead.
     * @member TranslationRecognizer.prototype.recognizeOnceAsync
     * @function
     * @public
     * @param cb - Callback that received the result when the translation has completed.
     * @param err - Callback invoked in case of an error.
     */
    TranslationRecognizer.prototype.recognizeOnceAsync = function (cb, err) {
        Contracts_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
        Exports_2.marshalPromiseToCallbacks(this.recognizeOnceAsyncImpl(Exports_1.RecognitionMode.Conversation), cb, err);
    };
    /**
     * Starts recognition and translation, until stopContinuousRecognitionAsync() is called.
     * User must subscribe to events to receive translation results.
     * @member TranslationRecognizer.prototype.startContinuousRecognitionAsync
     * @function
     * @public
     * @param cb - Callback that received the translation has started.
     * @param err - Callback invoked in case of an error.
     */
    TranslationRecognizer.prototype.startContinuousRecognitionAsync = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(Exports_1.RecognitionMode.Conversation), cb, err);
    };
    /**
     * Stops continuous recognition and translation.
     * @member TranslationRecognizer.prototype.stopContinuousRecognitionAsync
     * @function
     * @public
     * @param cb - Callback that received the translation has stopped.
     * @param err - Callback invoked in case of an error.
     */
    TranslationRecognizer.prototype.stopContinuousRecognitionAsync = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);
    };
    /**
     * dynamically remove a language from list of target language
     * (can be used while recognition is ongoing)
     * @member TranslationRecognizer.prototype.removeTargetLanguage
     * @function
     * @param lang - language to be removed
     * @public
     */
    TranslationRecognizer.prototype.removeTargetLanguage = function (lang) {
        Contracts_1.Contracts.throwIfNullOrUndefined(lang, "language to be removed");
        if (this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) {
            var languages = this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
            var index = languages.indexOf(lang);
            if (index > -1) {
                languages.splice(index, 1);
                this.properties.setProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(","));
                this.updateLanguages(languages);
            }
        }
    };
    /**
     * dynamically add a language to list of target language
     * (can be used while recognition is ongoing)
     * @member TranslationRecognizer.prototype.addTargetLanguage
     * @function
     * @param lang - language to be added
     * @public
     */
    TranslationRecognizer.prototype.addTargetLanguage = function (lang) {
        Contracts_1.Contracts.throwIfNullOrUndefined(lang, "language to be added");
        var languages = [];
        if (this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, undefined) !== undefined) {
            languages = this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
            if (!languages.includes(lang)) {
                languages.push(lang);
                this.properties.setProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(","));
            }
        }
        else {
            this.properties.setProperty(Exports_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, lang);
            languages = [lang];
        }
        this.updateLanguages(languages);
    };
    /**
     * closes all external resources held by an instance of this class.
     * @member TranslationRecognizer.prototype.close
     * @function
     * @public
     */
    TranslationRecognizer.prototype.close = function (cb, errorCb) {
        Contracts_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
        Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);
    };
    /**
     * handles ConnectionEstablishedEvent for conversation translation scenarios.
     * @member TranslationRecognizer.prototype.onConnection
     * @function
     * @public
     */
    /* tslint:disable:no-empty */
    TranslationRecognizer.prototype.onConnection = function () { };
    /**
     * handles disconnection events for conversation translation scenarios.
     * @member TranslationRecognizer.prototype.onDisconnection
     * @function
     * @public
     */
    /* tslint:disable:no-empty */
    TranslationRecognizer.prototype.onDisconnection = function () {
        return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
            return [2 /*return*/];
        }); });
    };
    TranslationRecognizer.prototype.dispose = function (disposing) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privDisposedTranslationRecognizer) {
                            return [2 /*return*/];
                        }
                        this.privDisposedTranslationRecognizer = true;
                        if (!disposing) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.implRecognizerStop()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    TranslationRecognizer.prototype.createRecognizerConfig = function (speechConfig) {
        return new Exports_1.RecognizerConfig(speechConfig, this.properties);
    };
    TranslationRecognizer.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) {
        var configImpl = audioConfig;
        return new Exports_1.TranslationServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);
    };
    TranslationRecognizer.prototype.updateLanguages = function (languages) {
        var conn = Connection_1.Connection.fromRecognizer(this);
        if (!!conn) {
            conn.setMessageProperty("speech.context", "translationcontext", { to: languages });
            conn.sendMessageAsync("event", JSON.stringify({
                id: "translation",
                name: "updateLanguage",
                to: languages
            }));
        }
    };
    return TranslationRecognizer;
}(Exports_3.Recognizer));
exports.TranslationRecognizer = TranslationRecognizer;



/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
Object.defineProperty(exports, "__esModule", { value: true });
exports.Connection = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var ConnectionMessage_1 = __webpack_require__(106);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
/**
 * Connection is a proxy class for managing connection to the speech service of the specified Recognizer.
 * By default, a Recognizer autonomously manages connection to service when needed.
 * The Connection class provides additional methods for users to explicitly open or close a connection and
 * to subscribe to connection status changes.
 * The use of Connection is optional, and mainly for scenarios where fine tuning of application
 * behavior based on connection status is needed. Users can optionally call Open() to manually set up a connection
 * in advance before starting recognition on the Recognizer associated with this Connection.
 * If the Recognizer needs to connect or disconnect to service, it will
 * setup or shutdown the connection independently. In this case the Connection will be notified by change of connection
 * status via Connected/Disconnected events.
 * Added in version 1.2.1.
 */
var Connection = /** @class */ (function () {
    function Connection() {
    }
    /**
     * Gets the Connection instance from the specified recognizer.
     * @param recognizer The recognizer associated with the connection.
     * @return The Connection instance of the recognizer.
     */
    Connection.fromRecognizer = function (recognizer) {
        var recoBase = recognizer.internalData;
        var ret = new Connection();
        ret.privInternalData = recoBase;
        ret.setupEvents();
        return ret;
    };
    /**
     * Gets the Connection instance from the specified synthesizer.
     * @param synthesizer The synthesizer associated with the connection.
     * @return The Connection instance of the synthesizer.
     */
    Connection.fromSynthesizer = function (synthesizer) {
        var synthBase = synthesizer.internalData;
        var ret = new Connection();
        ret.privInternalData = synthBase;
        ret.setupEvents();
        return ret;
    };
    /**
     * Starts to set up connection to the service.
     * Users can optionally call openConnection() to manually set up a connection in advance before starting recognition on the
     * Recognizer associated with this Connection. After starting recognition, calling Open() will have no effect
     *
     * Note: On return, the connection might not be ready yet. Please subscribe to the Connected event to
     * be notified when the connection is established.
     */
    Connection.prototype.openConnection = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.privInternalData.connect(), cb, err);
    };
    /**
     * Closes the connection the service.
     * Users can optionally call closeConnection() to manually shutdown the connection of the associated Recognizer.
     *
     * If closeConnection() is called during recognition, recognition will fail and cancel with an error.
     */
    Connection.prototype.closeConnection = function (cb, err) {
        if (this.privInternalData instanceof Exports_1.SynthesisAdapterBase) {
            throw new Error("Disconnecting a synthesizer's connection is currently not supported");
        }
        else {
            Exports_2.marshalPromiseToCallbacks(this.privInternalData.disconnect(), cb, err);
        }
    };
    /**
     * Appends a parameter in a message to service.
     * Added in version 1.12.1.
     * @param path The path of the network message.
     * @param propertyName Name of the property
     * @param propertyValue Value of the property. This is a json string.
     */
    Connection.prototype.setMessageProperty = function (path, propertyName, propertyValue) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(propertyName, "propertyName");
        if (this.privInternalData instanceof Exports_1.ServiceRecognizerBase) {
            if (path.toLowerCase() !== "speech.context") {
                throw new Error("Only speech.context message property sets are currently supported for recognizer");
            }
            else {
                this.privInternalData.speechContext.setSection(propertyName, propertyValue);
            }
        }
        else if (this.privInternalData instanceof Exports_1.SynthesisAdapterBase) {
            if (path.toLowerCase() !== "synthesis.context") {
                throw new Error("Only synthesis.context message property sets are currently supported for synthesizer");
            }
            else {
                this.privInternalData.synthesisContext.setSection(propertyName, propertyValue);
            }
        }
    };
    /**
     * Sends a message to the speech service.
     * Added in version 1.13.0.
     * @param path The WebSocket path of the message
     * @param payload The payload of the message. This is a json string or a ArrayBuffer.
     * @param success A callback to indicate success.
     * @param error A callback to indicate an error.
     */
    Connection.prototype.sendMessageAsync = function (path, payload, success, error) {
        Exports_2.marshalPromiseToCallbacks(this.privInternalData.sendNetworkMessage(path, payload), success, error);
    };
    /**
     * Dispose of associated resources.
     */
    Connection.prototype.close = function () {
        /* tslint:disable:no-empty */
    };
    Connection.prototype.setupEvents = function () {
        var _this = this;
        this.privEventListener = this.privInternalData.connectionEvents.attach(function (connectionEvent) {
            if (connectionEvent.name === "ConnectionEstablishedEvent") {
                if (!!_this.connected) {
                    _this.connected(new Exports_3.ConnectionEventArgs(connectionEvent.connectionId));
                }
            }
            else if (connectionEvent.name === "ConnectionClosedEvent") {
                if (!!_this.disconnected) {
                    _this.disconnected(new Exports_3.ConnectionEventArgs(connectionEvent.connectionId));
                }
            }
            else if (connectionEvent.name === "ConnectionMessageSentEvent") {
                if (!!_this.messageSent) {
                    _this.messageSent(new Exports_3.ConnectionMessageEventArgs(new ConnectionMessage_1.ConnectionMessageImpl(connectionEvent.message)));
                }
            }
            else if (connectionEvent.name === "ConnectionMessageReceivedEvent") {
                if (!!_this.messageReceived) {
                    _this.messageReceived(new Exports_3.ConnectionMessageEventArgs(new ConnectionMessage_1.ConnectionMessageImpl(connectionEvent.message)));
                }
            }
        });
        this.privServiceEventListener = this.privInternalData.serviceEvents.attach(function (e) {
            if (!!_this.receivedServiceMessage) {
                _this.receivedServiceMessage(new Exports_3.ServiceEventArgs(e.jsonString, e.name));
            }
        });
    };
    return Connection;
}());
exports.Connection = Connection;



/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionMessageImpl = exports.ConnectionMessage = void 0;
var HeaderNames_1 = __webpack_require__(55);
var Exports_1 = __webpack_require__(4);
var PropertyCollection_1 = __webpack_require__(98);
var PropertyId_1 = __webpack_require__(99);
/**
 * ConnectionMessage represents implementation specific messages sent to and received from
 * the speech service. These messages are provided for debugging purposes and should not
 * be used for production use cases with the Azure Cognitive Services Speech Service.
 * Messages sent to and received from the Speech Service are subject to change without
 * notice. This includes message contents, headers, payloads, ordering, etc.
 * Added in version 1.11.0.
 */
var ConnectionMessage = /** @class */ (function () {
    function ConnectionMessage() {
    }
    return ConnectionMessage;
}());
exports.ConnectionMessage = ConnectionMessage;
// tslint:disable-next-line:max-classes-per-file
var ConnectionMessageImpl = /** @class */ (function () {
    function ConnectionMessageImpl(message) {
        var _this = this;
        this.privConnectionMessage = message;
        this.privProperties = new PropertyCollection_1.PropertyCollection();
        if (!!this.privConnectionMessage.headers[HeaderNames_1.HeaderNames.ConnectionId]) {
            this.privProperties.setProperty(PropertyId_1.PropertyId.Speech_SessionId, this.privConnectionMessage.headers[HeaderNames_1.HeaderNames.ConnectionId]);
        }
        Object.keys(this.privConnectionMessage.headers).forEach(function (header, index, array) {
            _this.privProperties.setProperty(header, _this.privConnectionMessage.headers[header]);
        });
    }
    Object.defineProperty(ConnectionMessageImpl.prototype, "path", {
        /**
         * The message path.
         */
        get: function () {
            return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find(function (key) { return key.toLowerCase() === "path".toLowerCase(); })];
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessageImpl.prototype, "isTextMessage", {
        /**
         * Checks to see if the ConnectionMessage is a text message.
         * See also IsBinaryMessage().
         */
        get: function () {
            return this.privConnectionMessage.messageType === Exports_1.MessageType.Text;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessageImpl.prototype, "isBinaryMessage", {
        /**
         * Checks to see if the ConnectionMessage is a binary message.
         * See also GetBinaryMessage().
         */
        get: function () {
            return this.privConnectionMessage.messageType === Exports_1.MessageType.Binary;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessageImpl.prototype, "TextMessage", {
        /**
         * Gets the text message payload. Typically the text message content-type is
         * application/json. To determine other content-types use
         * Properties.GetProperty("Content-Type").
         */
        get: function () {
            return this.privConnectionMessage.textBody;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessageImpl.prototype, "binaryMessage", {
        /**
         * Gets the binary message payload.
         */
        get: function () {
            return this.privConnectionMessage.binaryBody;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConnectionMessageImpl.prototype, "properties", {
        /**
         * A collection of properties and their values defined for this <see cref="ConnectionMessage"/>.
         * Message headers can be accessed via this collection (e.g. "Content-Type").
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Returns a string that represents the connection message.
     */
    ConnectionMessageImpl.prototype.toString = function () {
        return "";
    };
    return ConnectionMessageImpl;
}());
exports.ConnectionMessageImpl = ConnectionMessageImpl;



/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Translations = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Represents collection of parameters and their values.
 * @class Translations
 */
var Translations = /** @class */ (function () {
    function Translations() {
        // Use an PropertyCollection internally, just wrapping it to hide the | enum syntax it has.
        this.privMap = new Exports_1.PropertyCollection();
    }
    /**
     * Returns the parameter value in type String. The parameter must have the same type as String.
     * Currently only String, int and bool are allowed.
     * If the name is not available, the specified defaultValue is returned.
     * @member Translations.prototype.get
     * @function
     * @public
     * @param {string} key - The parameter name.
     * @param {string} def - The default value which is returned if the parameter is not available in the collection.
     * @returns {string} value of the parameter.
     */
    Translations.prototype.get = function (key, def) {
        return this.privMap.getProperty(key, def);
    };
    /**
     * Sets the String value of the parameter specified by name.
     * @member Translations.prototype.set
     * @function
     * @public
     * @param {string} key - The parameter name.
     * @param {string} value - The value of the parameter.
     */
    Translations.prototype.set = function (key, value) {
        this.privMap.setProperty(key, value);
    };
    Object.defineProperty(Translations.prototype, "languages", {
        /**
         * Get the languages in the object in a String array.
         * @member Translations.prototype.languages
         * @function
         * @public
         * @returns {string[]} languages in translations object.
         */
        get: function () {
            return this.privMap.keys;
        },
        enumerable: false,
        configurable: true
    });
    return Translations;
}());
exports.Translations = Translations;



/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoMatchReason = void 0;
/**
 * Defines the possible reasons a recognition result might not be recognized.
 * @class NoMatchReason
 */
var NoMatchReason;
(function (NoMatchReason) {
    /**
     * Indicates that speech was detected, but not recognized.
     * @member NoMatchReason.NotRecognized
     */
    NoMatchReason[NoMatchReason["NotRecognized"] = 0] = "NotRecognized";
    /**
     * Indicates that the start of the audio stream contained only silence,
     * and the service timed out waiting for speech.
     * @member NoMatchReason.InitialSilenceTimeout
     */
    NoMatchReason[NoMatchReason["InitialSilenceTimeout"] = 1] = "InitialSilenceTimeout";
    /**
     * Indicates that the start of the audio stream contained only noise,
     * and the service timed out waiting for speech.
     * @member NoMatchReason.InitialBabbleTimeout
     */
    NoMatchReason[NoMatchReason["InitialBabbleTimeout"] = 2] = "InitialBabbleTimeout";
})(NoMatchReason = exports.NoMatchReason || (exports.NoMatchReason = {}));



/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoMatchDetails = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(61);
/**
 * Contains detailed information for NoMatch recognition results.
 * @class NoMatchDetails
 */
var NoMatchDetails = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {NoMatchReason} reason - The no-match reason.
     */
    function NoMatchDetails(reason) {
        this.privReason = reason;
    }
    /**
     * Creates an instance of NoMatchDetails object for the NoMatch SpeechRecognitionResults.
     * @member NoMatchDetails.fromResult
     * @function
     * @public
     * @param {SpeechRecognitionResult | IntentRecognitionResult | TranslationRecognitionResult}
     *        result - The recognition result that was not recognized.
     * @returns {NoMatchDetails} The no match details object being created.
     */
    NoMatchDetails.fromResult = function (result) {
        var simpleSpeech = Exports_1.SimpleSpeechPhrase.fromJSON(result.json);
        var reason = Exports_2.NoMatchReason.NotRecognized;
        switch (simpleSpeech.RecognitionStatus) {
            case Exports_1.RecognitionStatus.BabbleTimeout:
                reason = Exports_2.NoMatchReason.InitialBabbleTimeout;
                break;
            case Exports_1.RecognitionStatus.InitialSilenceTimeout:
                reason = Exports_2.NoMatchReason.InitialSilenceTimeout;
                break;
            default:
                reason = Exports_2.NoMatchReason.NotRecognized;
                break;
        }
        return new NoMatchDetails(reason);
    };
    Object.defineProperty(NoMatchDetails.prototype, "reason", {
        /**
         * The reason the recognition was canceled.
         * @member NoMatchDetails.prototype.reason
         * @function
         * @public
         * @returns {NoMatchReason} Specifies the reason canceled.
         */
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    return NoMatchDetails;
}());
exports.NoMatchDetails = NoMatchDetails;



/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationRecognitionCanceledEventArgs = void 0;
/**
 * Define payload of speech recognition canceled result events.
 * @class TranslationRecognitionCanceledEventArgs
 */
var TranslationRecognitionCanceledEventArgs = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {string} sessionid - The session id.
     * @param {CancellationReason} cancellationReason - The cancellation reason.
     * @param {string} errorDetails - Error details, if provided.
     * @param {TranslationRecognitionResult} result - The result.
     */
    function TranslationRecognitionCanceledEventArgs(sessionid, cancellationReason, errorDetails, errorCode, result) {
        this.privCancelReason = cancellationReason;
        this.privErrorDetails = errorDetails;
        this.privResult = result;
        this.privSessionId = sessionid;
        this.privErrorCode = errorCode;
    }
    Object.defineProperty(TranslationRecognitionCanceledEventArgs.prototype, "result", {
        /**
         * Specifies the recognition result.
         * @member TranslationRecognitionCanceledEventArgs.prototype.result
         * @function
         * @public
         * @returns {TranslationRecognitionResult} the recognition result.
         */
        get: function () {
            return this.privResult;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationRecognitionCanceledEventArgs.prototype, "sessionId", {
        /**
         * Specifies the session identifier.
         * @member TranslationRecognitionCanceledEventArgs.prototype.sessionId
         * @function
         * @public
         * @returns {string} the session identifier.
         */
        get: function () {
            return this.privSessionId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationRecognitionCanceledEventArgs.prototype, "reason", {
        /**
         * The reason the recognition was canceled.
         * @member TranslationRecognitionCanceledEventArgs.prototype.reason
         * @function
         * @public
         * @returns {CancellationReason} Specifies the reason canceled.
         */
        get: function () {
            return this.privCancelReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationRecognitionCanceledEventArgs.prototype, "errorCode", {
        /**
         * The error code in case of an unsuccessful recognition.
         * Added in version 1.1.0.
         * @return An error code that represents the error reason.
         */
        get: function () {
            return this.privErrorCode;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationRecognitionCanceledEventArgs.prototype, "errorDetails", {
        /**
         * In case of an unsuccessful recognition, provides details of the occurred error.
         * @member TranslationRecognitionCanceledEventArgs.prototype.errorDetails
         * @function
         * @public
         * @returns {string} A String that represents the error details.
         */
        get: function () {
            return this.privErrorDetails;
        },
        enumerable: false,
        configurable: true
    });
    return TranslationRecognitionCanceledEventArgs;
}());
exports.TranslationRecognitionCanceledEventArgs = TranslationRecognitionCanceledEventArgs;



/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentRecognitionCanceledEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Define payload of intent recognition canceled result events.
 * @class IntentRecognitionCanceledEventArgs
 */
var IntentRecognitionCanceledEventArgs = /** @class */ (function (_super) {
    __extends(IntentRecognitionCanceledEventArgs, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {CancellationReason} result - The result of the intent recognition.
     * @param {string} offset - The offset.
     * @param {IntentRecognitionResult} sessionId - The session id.
     */
    function IntentRecognitionCanceledEventArgs(reason, errorDetails, errorCode, result, offset, sessionId) {
        var _this = _super.call(this, result, offset, sessionId) || this;
        _this.privReason = reason;
        _this.privErrorDetails = errorDetails;
        _this.privErrorCode = errorCode;
        return _this;
    }
    Object.defineProperty(IntentRecognitionCanceledEventArgs.prototype, "reason", {
        /**
         * The reason the recognition was canceled.
         * @member IntentRecognitionCanceledEventArgs.prototype.reason
         * @function
         * @public
         * @returns {CancellationReason} Specifies the reason canceled.
         */
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(IntentRecognitionCanceledEventArgs.prototype, "errorCode", {
        /**
         * The error code in case of an unsuccessful recognition.
         * Added in version 1.1.0.
         * @return An error code that represents the error reason.
         */
        get: function () {
            return this.privErrorCode;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(IntentRecognitionCanceledEventArgs.prototype, "errorDetails", {
        /**
         * In case of an unsuccessful recognition, provides details of the occurred error.
         * @member IntentRecognitionCanceledEventArgs.prototype.errorDetails
         * @function
         * @public
         * @returns {string} A String that represents the error details.
         */
        get: function () {
            return this.privErrorDetails;
        },
        enumerable: false,
        configurable: true
    });
    return IntentRecognitionCanceledEventArgs;
}(Exports_1.IntentRecognitionEventArgs));
exports.IntentRecognitionCanceledEventArgs = IntentRecognitionCanceledEventArgs;



/***/ }),
/* 112 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancellationDetailsBase = void 0;
/**
 * Contains detailed information about why a result was canceled.
 * @class CancellationDetailsBase
 */
var CancellationDetailsBase = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {CancellationReason} reason - The cancellation reason.
     * @param {string} errorDetails - The error details, if provided.
     */
    function CancellationDetailsBase(reason, errorDetails, errorCode) {
        this.privReason = reason;
        this.privErrorDetails = errorDetails;
        this.privErrorCode = errorCode;
    }
    Object.defineProperty(CancellationDetailsBase.prototype, "reason", {
        /**
         * The reason the recognition was canceled.
         * @member CancellationDetailsBase.prototype.reason
         * @function
         * @public
         * @returns {CancellationReason} Specifies the reason canceled.
         */
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CancellationDetailsBase.prototype, "errorDetails", {
        /**
         * In case of an unsuccessful recognition, provides details of the occurred error.
         * @member CancellationDetailsBase.prototype.errorDetails
         * @function
         * @public
         * @returns {string} A String that represents the error details.
         */
        get: function () {
            return this.privErrorDetails;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CancellationDetailsBase.prototype, "ErrorCode", {
        /**
         * The error code in case of an unsuccessful recognition.
         * Added in version 1.1.0.
         * @return An error code that represents the error reason.
         */
        get: function () {
            return this.privErrorCode;
        },
        enumerable: false,
        configurable: true
    });
    return CancellationDetailsBase;
}());
exports.CancellationDetailsBase = CancellationDetailsBase;



/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancellationDetails = void 0;
var Exports_1 = __webpack_require__(53);
var CancellationDetailsBase_1 = __webpack_require__(112);
var Exports_2 = __webpack_require__(61);
/**
 * Contains detailed information about why a result was canceled.
 * @class CancellationDetails
 */
var CancellationDetails = /** @class */ (function (_super) {
    __extends(CancellationDetails, _super);
    function CancellationDetails(reason, errorDetails, errorCode) {
        return _super.call(this, reason, errorDetails, errorCode) || this;
    }
    /**
     * Creates an instance of CancellationDetails object for the canceled RecognitionResult.
     * @member CancellationDetails.fromResult
     * @function
     * @public
     * @param {RecognitionResult | SpeechSynthesisResult} result - The result that was canceled.
     * @returns {CancellationDetails} The cancellation details object being created.
     */
    CancellationDetails.fromResult = function (result) {
        var reason = Exports_2.CancellationReason.Error;
        var errorCode = Exports_2.CancellationErrorCode.NoError;
        if (result instanceof Exports_2.RecognitionResult && !!result.json) {
            var simpleSpeech = Exports_1.SimpleSpeechPhrase.fromJSON(result.json);
            reason = Exports_1.EnumTranslation.implTranslateCancelResult(simpleSpeech.RecognitionStatus);
        }
        if (!!result.properties) {
            errorCode = Exports_2.CancellationErrorCode[result.properties.getProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.NoError])];
        }
        return new CancellationDetails(reason, result.errorDetails || Exports_1.EnumTranslation.implTranslateErrorDetails(errorCode), errorCode);
    };
    return CancellationDetails;
}(CancellationDetailsBase_1.CancellationDetailsBase));
exports.CancellationDetails = CancellationDetails;



/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancellationErrorCode = void 0;
/**
 *  Defines error code in case that CancellationReason is Error.
 *  Added in version 1.1.0.
 */
var CancellationErrorCode;
(function (CancellationErrorCode) {
    /**
     * Indicates that no error occurred during speech recognition.
     */
    CancellationErrorCode[CancellationErrorCode["NoError"] = 0] = "NoError";
    /**
     * Indicates an authentication error.
     */
    CancellationErrorCode[CancellationErrorCode["AuthenticationFailure"] = 1] = "AuthenticationFailure";
    /**
     * Indicates that one or more recognition parameters are invalid.
     */
    CancellationErrorCode[CancellationErrorCode["BadRequestParameters"] = 2] = "BadRequestParameters";
    /**
     * Indicates that the number of parallel requests exceeded the number of allowed
     * concurrent transcriptions for the subscription.
     */
    CancellationErrorCode[CancellationErrorCode["TooManyRequests"] = 3] = "TooManyRequests";
    /**
     * Indicates a connection error.
     */
    CancellationErrorCode[CancellationErrorCode["ConnectionFailure"] = 4] = "ConnectionFailure";
    /**
     * Indicates a time-out error when waiting for response from service.
     */
    CancellationErrorCode[CancellationErrorCode["ServiceTimeout"] = 5] = "ServiceTimeout";
    /**
     * Indicates that an error is returned by the service.
     */
    CancellationErrorCode[CancellationErrorCode["ServiceError"] = 6] = "ServiceError";
    /**
     * Indicates an unexpected runtime error.
     */
    CancellationErrorCode[CancellationErrorCode["RuntimeError"] = 7] = "RuntimeError";
    /**
     * Indicates an quota overrun on existing key.
     */
    CancellationErrorCode[CancellationErrorCode["Forbidden"] = 8] = "Forbidden";
})(CancellationErrorCode = exports.CancellationErrorCode || (exports.CancellationErrorCode = {}));



/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Defines payload for connection events like Connected/Disconnected.
 * Added in version 1.2.0
 */
var ConnectionEventArgs = /** @class */ (function (_super) {
    __extends(ConnectionEventArgs, _super);
    function ConnectionEventArgs() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ConnectionEventArgs;
}(Exports_1.SessionEventArgs));
exports.ConnectionEventArgs = ConnectionEventArgs;



/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Defines payload for any Service message event
 * Added in version 1.9.0
 */
var ServiceEventArgs = /** @class */ (function (_super) {
    __extends(ServiceEventArgs, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {string} json - json payload of the USP message.
     */
    function ServiceEventArgs(json, name, sessionId) {
        var _this = _super.call(this, sessionId) || this;
        _this.privJsonResult = json;
        _this.privEventName = name;
        return _this;
    }
    Object.defineProperty(ServiceEventArgs.prototype, "jsonString", {
        get: function () {
            return this.privJsonResult;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ServiceEventArgs.prototype, "eventName", {
        get: function () {
            return this.privEventName;
        },
        enumerable: false,
        configurable: true
    });
    return ServiceEventArgs;
}(Exports_1.SessionEventArgs));
exports.ServiceEventArgs = ServiceEventArgs;



/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PhraseListGrammar = void 0;
/**
 * Allows additions of new phrases to improve speech recognition.
 *
 * Phrases added to the recognizer are effective at the start of the next recognition, or the next time the SpeechSDK must reconnect
 * to the speech service.
 */
var PhraseListGrammar = /** @class */ (function () {
    function PhraseListGrammar(recogBase) {
        this.privGrammerBuilder = recogBase.dynamicGrammar;
    }
    /**
     * Creates a PhraseListGrammar from a given speech recognizer. Will accept any recognizer that derives from @class Recognizer.
     * @param recognizer The recognizer to add phrase lists to.
     */
    PhraseListGrammar.fromRecognizer = function (recognizer) {
        var recoBase = recognizer.internalData;
        return new PhraseListGrammar(recoBase);
    };
    /**
     * Adds a single phrase to the current recognizer.
     * @param phrase Phrase to add.
     */
    PhraseListGrammar.prototype.addPhrase = function (phrase) {
        this.privGrammerBuilder.addPhrase(phrase);
    };
    /**
     * Adds multiple phrases to the current recognizer.
     * @param phrases Array of phrases to add.
     */
    PhraseListGrammar.prototype.addPhrases = function (phrases) {
        this.privGrammerBuilder.addPhrase(phrases);
    };
    /**
     * Clears all phrases added to the current recognizer.
     */
    PhraseListGrammar.prototype.clear = function () {
        this.privGrammerBuilder.clearPhrases();
    };
    return PhraseListGrammar;
}());
exports.PhraseListGrammar = PhraseListGrammar;



/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogServiceConfigImpl = exports.DialogServiceConfig = void 0;
var Contracts_1 = __webpack_require__(63);
var Exports_1 = __webpack_require__(61);
/**
 * Class that defines base configurations for dialog service connector
 * @class DialogServiceConfig
 */
var DialogServiceConfig = /** @class */ (function () {
    /**
     * Creates an instance of DialogService config.
     * @constructor
     */
    function DialogServiceConfig() {
    }
    Object.defineProperty(DialogServiceConfig.prototype, "applicationId", {
        /**
         * Sets the corresponding backend application identifier.
         * @member DialogServiceConfig.prototype.Conversation_ApplicationId
         * @function
         * @public
         * @param {string} value - The application identifier to set.
         */
        // tslint:disable-next-line: no-empty
        set: function (value) { },
        enumerable: false,
        configurable: true
    });
    var _a;
    DialogServiceConfig.DialogTypes = (_a = /** @class */ (function () {
            function class_1() {
            }
            return class_1;
        }()),
        _a.BotFramework = "bot_framework",
        _a.CustomCommands = "custom_commands",
        _a);
    return DialogServiceConfig;
}());
exports.DialogServiceConfig = DialogServiceConfig;
/**
 * Dialog Service configuration.
 * @class DialogServiceConfigImpl
 */
// tslint:disable-next-line:max-classes-per-file
var DialogServiceConfigImpl = /** @class */ (function (_super) {
    __extends(DialogServiceConfigImpl, _super);
    /**
     * Creates an instance of dialogService config.
     */
    function DialogServiceConfigImpl() {
        var _this = _super.call(this) || this;
        _this.privSpeechConfig = new Exports_1.SpeechConfigImpl();
        return _this;
    }
    Object.defineProperty(DialogServiceConfigImpl.prototype, "properties", {
        /**
         * Provides access to custom properties.
         * @member DialogServiceConfigImpl.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The properties.
         */
        get: function () {
            return this.privSpeechConfig.properties;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DialogServiceConfigImpl.prototype, "speechRecognitionLanguage", {
        /**
         * Gets the speech recognition language.
         * @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage
         * @function
         * @public
         */
        get: function () {
            return this.privSpeechConfig.speechRecognitionLanguage;
        },
        /**
         * Sets the speech recognition language.
         * @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage
         * @function
         * @public
         * @param {string} value - The language to set.
         */
        set: function (value) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value");
            this.privSpeechConfig.speechRecognitionLanguage = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DialogServiceConfigImpl.prototype, "outputFormat", {
        get: function () {
            return this.privSpeechConfig.outputFormat;
        },
        set: function (value) {
            this.privSpeechConfig.outputFormat = value;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Sets a named property as value
     * @member DialogServiceConfigImpl.prototype.setProperty
     * @function
     * @public
     * @param {PropertyId | string} name - The property to set.
     * @param {string} value - The value.
     */
    DialogServiceConfigImpl.prototype.setProperty = function (name, value) {
        this.privSpeechConfig.setProperty(name, value);
    };
    /**
     * Sets a named property as value
     * @member DialogServiceConfigImpl.prototype.getProperty
     * @function
     * @public
     * @param {PropertyId | string} name - The property to get.
     * @param {string} def - The default value to return in case the property is not known.
     * @returns {string} The current value, or provided default, of the given property.
     */
    DialogServiceConfigImpl.prototype.getProperty = function (name, def) {
        return this.privSpeechConfig.getProperty(name);
    };
    /**
     * Sets the proxy configuration.
     * Only relevant in Node.js environments.
     * Added in version 1.4.0.
     * @param proxyHostName The host name of the proxy server, without the protocol scheme (http://)
     * @param proxyPort The port number of the proxy server.
     * @param proxyUserName The user name of the proxy server.
     * @param proxyPassword The password of the proxy server.
     */
    DialogServiceConfigImpl.prototype.setProxy = function (proxyHostName, proxyPort, proxyUserName, proxyPassword) {
        this.setProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyHostName, proxyHostName);
        this.setProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyPort, "" + proxyPort);
        if (proxyUserName) {
            this.setProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyUserName, proxyUserName);
        }
        if (proxyPassword) {
            this.setProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyPassword, proxyPassword);
        }
    };
    DialogServiceConfigImpl.prototype.setServiceProperty = function (name, value, channel) {
        this.privSpeechConfig.setServiceProperty(name, value, channel);
    };
    /**
     * Dispose of associated resources.
     * @member DialogServiceConfigImpl.prototype.close
     * @function
     * @public
     */
    DialogServiceConfigImpl.prototype.close = function () {
        return;
    };
    return DialogServiceConfigImpl;
}(DialogServiceConfig));
exports.DialogServiceConfigImpl = DialogServiceConfigImpl;



/***/ }),
/* 119 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.BotFrameworkConfig = void 0;
var Contracts_1 = __webpack_require__(63);
var DialogServiceConfig_1 = __webpack_require__(118);
var Exports_1 = __webpack_require__(61);
/**
 * Class that defines configurations for the dialog service connector object for using a Bot Framework backend.
 * @class BotFrameworkConfig
 */
var BotFrameworkConfig = /** @class */ (function (_super) {
    __extends(BotFrameworkConfig, _super);
    /**
     * Creates an instance of BotFrameworkConfig.
     */
    function BotFrameworkConfig() {
        return _super.call(this) || this;
    }
    /**
     * Creates a bot framework configuration instance with the provided subscription information.
     * @member BotFrameworkConfig.fromSubscription
     * @function
     * @public
     * @param subscription Subscription key associated with the bot
     * @param region The region name (see the <a href="https://aka.ms/csspeech/region">region page</a>).
     * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the
     *        resource name.
     * @returns {BotFrameworkConfig} A new bot framework configuration instance.
     */
    BotFrameworkConfig.fromSubscription = function (subscription, region, botId) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(subscription, "subscription");
        Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region");
        var botFrameworkConfig = new DialogServiceConfig_1.DialogServiceConfigImpl();
        botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.BotFramework);
        botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Key, subscription);
        botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Region, region);
        if (botId) {
            botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_ApplicationId, botId);
        }
        return botFrameworkConfig;
    };
    /**
     * Creates a bot framework configuration instance for the specified authorization token and region.
     * Note: The caller must ensure that an authorization token is valid. Before an authorization token expires, the
     *       caller must refresh it by setting the authorizationToken property on the corresponding
     *       DialogServiceConnector instance created with this config. The contents of configuration objects are copied
     *       when connectors are created, so setting authorizationToken on a DialogServiceConnector will not update the
     *       original configuration's authorization token. Create a new configuration instance or set the
     *       SpeechServiceAuthorization_Token property to update an existing instance if it will be used to create
     *       further DialogServiceConnectors.
     * @member BotFrameworkConfig.fromAuthorizationToken
     * @function
     * @public
     * @param authorizationToken The authorization token associated with the bot
     * @param region The region name (see the <a href="https://aka.ms/csspeech/region">region page</a>).
     * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the
     *        resource name.
     * @returns {BotFrameworkConfig} A new bot framework configuration instance.
     */
    BotFrameworkConfig.fromAuthorizationToken = function (authorizationToken, region, botId) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken");
        Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region");
        var botFrameworkConfig = new DialogServiceConfig_1.DialogServiceConfigImpl();
        botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.BotFramework);
        botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceAuthorization_Token, authorizationToken);
        botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Region, region);
        if (botId) {
            botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_ApplicationId, botId);
        }
        return botFrameworkConfig;
    };
    /**
     * Creates an instance of a BotFrameworkConfig.
     * This method is intended only for users who use a non-default service host. The standard resource path will be
     * assumed. For services with a non-standard resource path or no path at all, use fromEndpoint instead.
     * Note: Query parameters are not allowed in the host URI and must be set by other APIs.
     * Note: To use an authorization token with fromHost, use fromHost(URL) and then set the AuthorizationToken
     *       property on the created BotFrameworkConfig instance.
     * Note: Added in version 1.15.0.
     * @member BotFrameworkConfig.fromHost
     * @function
     * @public
     * @param {URL | string} host - If a URL is provided, the fully-qualified host with protocol (e.g.
     *        wss://your.host.com:1234) will be used. If a string is provided, it will be embedded in
     *        wss://{host}.convai.speech.azure.us.
     * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization
     *        token must be set.
     * @param botId Optional. Identifier for using a specific bot within an Azure resource group. Equivalent to the
     *        resource name.
     * @returns {BotFrameworkConfig} A new bot framework configuration instance.
     */
    BotFrameworkConfig.fromHost = function (host, subscriptionKey, botId) {
        Contracts_1.Contracts.throwIfNullOrUndefined(host, "host");
        var resolvedHost = host instanceof URL ? host : new URL("wss://" + host + ".convai.speech.azure.us");
        Contracts_1.Contracts.throwIfNullOrUndefined(resolvedHost, "resolvedHost");
        var botFrameworkConfig = new DialogServiceConfig_1.DialogServiceConfigImpl();
        botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.BotFramework);
        botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Host, resolvedHost.toString());
        if (undefined !== subscriptionKey) {
            botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
        }
        return botFrameworkConfig;
    };
    /**
     * Creates an instance of a BotFrameworkConfig.
     * This method is intended only for users who use a non-standard service endpoint or parameters.
     * Note: The query parameters specified in the endpoint URL are not changed, even if they are set by any other APIs.
     * Note: To use authorization token with fromEndpoint, pass an empty string to the subscriptionKey in the
     *       fromEndpoint method, and then set authorizationToken="token" on the created BotFrameworkConfig instance to
     *       use the authorization token.
     * Note: Added in version 1.15.0.
     * @member BotFrameworkConfig.fromEndpoint
     * @function
     * @public
     * @param {URL} endpoint - The service endpoint to connect to.
     * @param {string} subscriptionKey - The subscription key. If a subscription key is not specified, an authorization
     *        token must be set.
     * @returns {BotFrameworkConfig} - A new bot framework configuration instance using the provided endpoint.
     */
    BotFrameworkConfig.fromEndpoint = function (endpoint, subscriptionKey) {
        Contracts_1.Contracts.throwIfNull(endpoint, "endpoint");
        var botFrameworkConfig = new DialogServiceConfig_1.DialogServiceConfigImpl();
        botFrameworkConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.BotFramework);
        botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Endpoint, endpoint.toString());
        if (undefined !== subscriptionKey) {
            botFrameworkConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
        }
        return botFrameworkConfig;
    };
    return BotFrameworkConfig;
}(DialogServiceConfig_1.DialogServiceConfigImpl));
exports.BotFrameworkConfig = BotFrameworkConfig;



/***/ }),
/* 120 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomCommandsConfig = void 0;
var Contracts_1 = __webpack_require__(63);
var DialogServiceConfig_1 = __webpack_require__(118);
var Exports_1 = __webpack_require__(61);
/**
 * Class that defines configurations for the dialog service connector object for using a CustomCommands backend.
 * @class CustomCommandsConfig
 */
var CustomCommandsConfig = /** @class */ (function (_super) {
    __extends(CustomCommandsConfig, _super);
    /**
     * Creates an instance of CustomCommandsConfig.
     */
    function CustomCommandsConfig() {
        return _super.call(this) || this;
    }
    /**
     * Creates an instance of the bot framework config with the specified subscription and region.
     * @member CustomCommandsConfig.fromSubscription
     * @function
     * @public
     * @param applicationId Speech Commands application id.
     * @param subscription Subscription key associated with the bot
     * @param region The region name (see the <a href="https://aka.ms/csspeech/region">region page</a>).
     * @returns {CustomCommandsConfig} A new bot framework config.
     */
    CustomCommandsConfig.fromSubscription = function (applicationId, subscription, region) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(applicationId, "applicationId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(subscription, "subscription");
        Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region");
        var customCommandsConfig = new DialogServiceConfig_1.DialogServiceConfigImpl();
        customCommandsConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.CustomCommands);
        customCommandsConfig.setProperty(Exports_1.PropertyId.Conversation_ApplicationId, applicationId);
        customCommandsConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Key, subscription);
        customCommandsConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Region, region);
        return customCommandsConfig;
    };
    /**
     * Creates an instance of the bot framework config with the specified Speech Commands application id, authorization token and region.
     * Note: The caller needs to ensure that the authorization token is valid. Before the authorization token
     * expires, the caller needs to refresh it by calling this setter with a new valid token.
     * As configuration values are copied when creating a new recognizer, the new token value will not apply to recognizers that have already been created.
     * For recognizers that have been created before, you need to set authorization token of the corresponding recognizer
     * to refresh the token. Otherwise, the recognizers will encounter errors during recognition.
     * @member CustomCommandsConfig.fromAuthorizationToken
     * @function
     * @public
     * @param applicationId Speech Commands application id.
     * @param authorizationToken The authorization token associated with the application.
     * @param region The region name (see the <a href="https://aka.ms/csspeech/region">region page</a>).
     * @returns {CustomCommandsConfig} A new speech commands config.
     */
    CustomCommandsConfig.fromAuthorizationToken = function (applicationId, authorizationToken, region) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(applicationId, "applicationId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken");
        Contracts_1.Contracts.throwIfNullOrWhitespace(region, "region");
        var customCommandsConfig = new DialogServiceConfig_1.DialogServiceConfigImpl();
        customCommandsConfig.setProperty(Exports_1.PropertyId.Conversation_DialogType, DialogServiceConfig_1.DialogServiceConfig.DialogTypes.CustomCommands);
        customCommandsConfig.setProperty(Exports_1.PropertyId.Conversation_ApplicationId, applicationId);
        customCommandsConfig.setProperty(Exports_1.PropertyId.SpeechServiceAuthorization_Token, authorizationToken);
        customCommandsConfig.setProperty(Exports_1.PropertyId.SpeechServiceConnection_Region, region);
        return customCommandsConfig;
    };
    Object.defineProperty(CustomCommandsConfig.prototype, "applicationId", {
        /**
         * Gets the corresponding backend application identifier.
         * @member CustomCommandsConfig.prototype.Conversation_ApplicationId
         * @function
         * @public
         * @param {string} value - The application identifier to get.
         */
        get: function () {
            return this.getProperty(Exports_1.PropertyId.Conversation_ApplicationId);
        },
        /**
         * Sets the corresponding backend application identifier.
         * @member CustomCommandsConfig.prototype.Conversation_ApplicationId
         * @function
         * @public
         * @param {string} value - The application identifier to set.
         */
        set: function (value) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(value, "value");
            this.setProperty(Exports_1.PropertyId.Conversation_ApplicationId, value);
        },
        enumerable: false,
        configurable: true
    });
    return CustomCommandsConfig;
}(DialogServiceConfig_1.DialogServiceConfigImpl));
exports.CustomCommandsConfig = CustomCommandsConfig;



/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogServiceConnector = void 0;
var DialogConnectorFactory_1 = __webpack_require__(122);
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
var PropertyId_1 = __webpack_require__(99);
/**
 * Dialog Service Connector
 * @class DialogServiceConnector
 */
var DialogServiceConnector = /** @class */ (function (_super) {
    __extends(DialogServiceConnector, _super);
    /**
     * Initializes an instance of the DialogServiceConnector.
     * @constructor
     * @param {DialogServiceConfig} dialogConfig - Set of properties to configure this recognizer.
     * @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer
     */
    function DialogServiceConnector(dialogConfig, audioConfig) {
        var _this = this;
        var dialogServiceConfigImpl = dialogConfig;
        Contracts_1.Contracts.throwIfNull(dialogConfig, "dialogConfig");
        _this = _super.call(this, audioConfig, dialogServiceConfigImpl.properties, new DialogConnectorFactory_1.DialogConnectionFactory()) || this;
        _this.isTurnComplete = true;
        _this.privIsDisposed = false;
        _this.privProperties = dialogServiceConfigImpl.properties.clone();
        var agentConfig = _this.buildAgentConfig();
        _this.privReco.agentConfig.set(agentConfig);
        return _this;
    }
    /**
     * Starts a connection to the service.
     * Users can optionally call connect() to manually set up a connection in advance, before starting interactions.
     *
     * Note: On return, the connection might not be ready yet. Please subscribe to the Connected event to
     * be notified when the connection is established.
     * @member DialogServiceConnector.prototype.connect
     * @function
     * @public
     */
    DialogServiceConnector.prototype.connect = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.privReco.connect(), cb, err);
    };
    /**
     * Closes the connection the service.
     * Users can optionally call disconnect() to manually shutdown the connection of the associated DialogServiceConnector.
     *
     * If disconnect() is called during a recognition, recognition will fail and cancel with an error.
     */
    DialogServiceConnector.prototype.disconnect = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.privReco.disconnect(), cb, err);
    };
    Object.defineProperty(DialogServiceConnector.prototype, "authorizationToken", {
        /**
         * Gets the authorization token used to communicate with the service.
         * @member DialogServiceConnector.prototype.authorizationToken
         * @function
         * @public
         * @returns {string} Authorization token.
         */
        get: function () {
            return this.properties.getProperty(PropertyId_1.PropertyId.SpeechServiceAuthorization_Token);
        },
        /**
         * Sets the authorization token used to communicate with the service.
         * @member DialogServiceConnector.prototype.authorizationToken
         * @function
         * @public
         * @param {string} token - Authorization token.
         */
        set: function (token) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token");
            this.properties.setProperty(PropertyId_1.PropertyId.SpeechServiceAuthorization_Token, token);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DialogServiceConnector.prototype, "properties", {
        /**
         * The collection of properties and their values defined for this DialogServiceConnector.
         * @member DialogServiceConnector.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The collection of properties and their values defined for this DialogServiceConnector.
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DialogServiceConnector.prototype, "speechActivityTemplate", {
        /** Gets the template for the activity generated by service from speech.
         * Properties from the template will be stamped on the generated activity.
         * It can be empty
         */
        get: function () {
            return this.properties.getProperty(PropertyId_1.PropertyId.Conversation_Speech_Activity_Template);
        },
        /** Sets the template for the activity generated by service from speech.
         * Properties from the template will be stamped on the generated activity.
         * It can be null or empty.
         * Note: it has to be a valid Json object.
         */
        set: function (speechActivityTemplate) {
            this.properties.setProperty(PropertyId_1.PropertyId.Conversation_Speech_Activity_Template, speechActivityTemplate);
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Starts recognition and stops after the first utterance is recognized.
     * @member DialogServiceConnector.prototype.listenOnceAsync
     * @function
     * @public
     * @param cb - Callback that received the result when the reco has completed.
     * @param err - Callback invoked in case of an error.
     */
    DialogServiceConnector.prototype.listenOnceAsync = function (cb, err) {
        var _this = this;
        if (this.isTurnComplete) {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            var callbackHolder = function () { return __awaiter(_this, void 0, void 0, function () {
                var ret, e;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.privReco.connect()];
                        case 1:
                            _a.sent();
                            return [4 /*yield*/, this.implRecognizerStop()];
                        case 2:
                            _a.sent();
                            this.isTurnComplete = false;
                            ret = new Exports_2.Deferred();
                            return [4 /*yield*/, this.privReco.recognize(Exports_1.RecognitionMode.Conversation, ret.resolve, ret.reject)];
                        case 3:
                            _a.sent();
                            return [4 /*yield*/, ret.promise];
                        case 4:
                            e = _a.sent();
                            return [4 /*yield*/, this.implRecognizerStop()];
                        case 5:
                            _a.sent();
                            return [2 /*return*/, e];
                    }
                });
            }); };
            var retPromise = callbackHolder();
            retPromise.catch(function () {
                // Destroy the recognizer.
                /* tslint:disable:no-empty */ // We've done all we can here.
                _this.dispose(true).catch(function () { });
            });
            Exports_2.marshalPromiseToCallbacks(retPromise.finally(function () {
                _this.isTurnComplete = true;
            }), cb, err);
        }
    };
    DialogServiceConnector.prototype.sendActivityAsync = function (activity, cb, errCb) {
        Exports_2.marshalPromiseToCallbacks(this.privReco.sendMessage(activity), cb, errCb);
    };
    /**
     * closes all external resources held by an instance of this class.
     * @member DialogServiceConnector.prototype.close
     * @function
     * @public
     */
    DialogServiceConnector.prototype.close = function (cb, err) {
        Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
        Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, err);
    };
    DialogServiceConnector.prototype.dispose = function (disposing) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privIsDisposed) {
                            return [2 /*return*/];
                        }
                        if (!disposing) return [3 /*break*/, 3];
                        this.privIsDisposed = true;
                        return [4 /*yield*/, this.implRecognizerStop()];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    DialogServiceConnector.prototype.createRecognizerConfig = function (speechConfig) {
        return new Exports_1.RecognizerConfig(speechConfig, this.privProperties);
    };
    DialogServiceConnector.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) {
        var audioSource = audioConfig;
        return new Exports_1.DialogServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this);
    };
    DialogServiceConnector.prototype.buildAgentConfig = function () {
        var communicationType = this.properties.getProperty("Conversation_Communication_Type", "Default");
        return {
            botInfo: {
                commType: communicationType,
                commandsCulture: undefined,
                connectionId: this.properties.getProperty(PropertyId_1.PropertyId.Conversation_Agent_Connection_Id),
                conversationId: this.properties.getProperty(PropertyId_1.PropertyId.Conversation_Conversation_Id, undefined),
                fromId: this.properties.getProperty(PropertyId_1.PropertyId.Conversation_From_Id, undefined),
                ttsAudioFormat: this.properties.getProperty(PropertyId_1.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)
            },
            version: 0.2
        };
    };
    return DialogServiceConnector;
}(Exports_3.Recognizer));
exports.DialogServiceConnector = DialogServiceConnector;



/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogConnectionFactory = void 0;
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(53);
var Exports_3 = __webpack_require__(61);
var ConnectionFactoryBase_1 = __webpack_require__(123);
var Exports_4 = __webpack_require__(53);
var HeaderNames_1 = __webpack_require__(55);
var QueryParameterNames_1 = __webpack_require__(124);
var DialogConnectionFactory = /** @class */ (function (_super) {
    __extends(DialogConnectionFactory, _super);
    function DialogConnectionFactory() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.create = function (config, authInfo, connectionId) {
            var applicationId = config.parameters.getProperty(Exports_3.PropertyId.Conversation_ApplicationId, "");
            var dialogType = config.parameters.getProperty(Exports_3.PropertyId.Conversation_DialogType);
            var region = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Region);
            var language = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage, "en-US");
            var requestTurnStatus = config.parameters.getProperty(Exports_3.PropertyId.Conversation_Request_Bot_Status_Messages, "true");
            var queryParams = {};
            queryParams[HeaderNames_1.HeaderNames.ConnectionId] = connectionId;
            queryParams[QueryParameterNames_1.QueryParameterNames.Format] = config.parameters.getProperty(Exports_2.OutputFormatPropertyName, Exports_3.OutputFormat[Exports_3.OutputFormat.Simple]).toLowerCase();
            queryParams[QueryParameterNames_1.QueryParameterNames.Language] = language;
            queryParams[QueryParameterNames_1.QueryParameterNames.RequestBotStatusMessages] = requestTurnStatus;
            if (applicationId) {
                queryParams[QueryParameterNames_1.QueryParameterNames.BotId] = applicationId;
                if (dialogType === Exports_3.DialogServiceConfig.DialogTypes.CustomCommands) {
                    queryParams[HeaderNames_1.HeaderNames.CustomCommandsAppId] = applicationId;
                }
            }
            var resourceInfix = dialogType === Exports_3.DialogServiceConfig.DialogTypes.CustomCommands ? "commands/"
                : "";
            var version = dialogType === Exports_3.DialogServiceConfig.DialogTypes.CustomCommands ? "v1"
                : dialogType === Exports_3.DialogServiceConfig.DialogTypes.BotFramework ? "v3"
                    : "v0";
            var headers = {};
            if (authInfo.token != null && authInfo.token !== "") {
                headers[authInfo.headerName] = authInfo.token;
            }
            // The URL used for connection is chosen in a priority order of specification:
            //  1. If a custom endpoint is provided, that URL is used verbatim.
            //  2. If a custom host is provided (e.g. "wss://my.custom.endpoint.com:1123"), a URL is constructed from it.
            //  3. If no custom connection details are provided, a URL is constructed from default values.
            var endpoint = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Endpoint, "");
            if (!endpoint) {
                var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region);
                var host = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Host, "wss://" + region + "." + DialogConnectionFactory.Constants.BaseUrl + hostSuffix);
                var standardizedHost = host.endsWith("/") ? host : host + "/";
                endpoint = "" + standardizedHost + resourceInfix + DialogConnectionFactory.Constants.ApiKey + "/" + version;
            }
            _this.setCommonUrlParams(config, queryParams, endpoint);
            var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
            return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_4.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);
        };
        return _this;
    }
    var _a;
    DialogConnectionFactory.Constants = (_a = /** @class */ (function () {
            function class_1() {
            }
            return class_1;
        }()),
        _a.ApiKey = "api",
        _a.BaseUrl = "convai.speech",
        _a);
    return DialogConnectionFactory;
}(ConnectionFactoryBase_1.ConnectionFactoryBase));
exports.DialogConnectionFactory = DialogConnectionFactory;



/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionFactoryBase = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(61);
var QueryParameterNames_1 = __webpack_require__(124);
var ConnectionFactoryBase = /** @class */ (function () {
    function ConnectionFactoryBase() {
    }
    ConnectionFactoryBase.getHostSuffix = function (region) {
        if (!!region) {
            if (region.toLowerCase().startsWith("china")) {
                return ".azure.cn";
            }
            if (region.toLowerCase().startsWith("usgov")) {
                return ".azure.us";
            }
        }
        return ".microsoft.com";
    };
    ConnectionFactoryBase.prototype.setCommonUrlParams = function (config, queryParams, endpoint) {
        this.setUrlParameter(Exports_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, QueryParameterNames_1.QueryParameterNames.EnableAudioLogging, config, queryParams, endpoint);
        this.setUrlParameter(Exports_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, QueryParameterNames_1.QueryParameterNames.EnableWordLevelTimestamps, config, queryParams, endpoint);
        this.setUrlParameter(Exports_2.PropertyId.SpeechServiceResponse_ProfanityOption, QueryParameterNames_1.QueryParameterNames.Profanity, config, queryParams, endpoint);
        this.setUrlParameter(Exports_2.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs, QueryParameterNames_1.QueryParameterNames.InitialSilenceTimeoutMs, config, queryParams, endpoint);
        this.setUrlParameter(Exports_2.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs, QueryParameterNames_1.QueryParameterNames.EndSilenceTimeoutMs, config, queryParams, endpoint);
        this.setUrlParameter(Exports_2.PropertyId.SpeechServiceResponse_StablePartialResultThreshold, QueryParameterNames_1.QueryParameterNames.StableIntermediateThreshold, config, queryParams, endpoint);
        var serviceProperties = JSON.parse(config.parameters.getProperty(Exports_1.ServicePropertiesPropertyName, "{}"));
        Object.keys(serviceProperties).forEach(function (value, num, array) {
            queryParams[value] = serviceProperties[value];
        });
    };
    ConnectionFactoryBase.prototype.setUrlParameter = function (propId, parameterName, config, queryParams, endpoint) {
        var value = config.parameters.getProperty(propId, undefined);
        if (value && (!endpoint || endpoint.search(parameterName) === -1)) {
            queryParams[parameterName] = value.toLocaleLowerCase();
        }
    };
    return ConnectionFactoryBase;
}());
exports.ConnectionFactoryBase = ConnectionFactoryBase;



/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.QueryParameterNames = void 0;
var QueryParameterNames = /** @class */ (function () {
    function QueryParameterNames() {
    }
    QueryParameterNames.BotId = "botid";
    QueryParameterNames.CustomSpeechDeploymentId = "cid";
    QueryParameterNames.CustomVoiceDeploymentId = "deploymentId";
    QueryParameterNames.EnableAudioLogging = "storeAudio";
    QueryParameterNames.EnableLanguageId = "lidEnabled";
    QueryParameterNames.EnableWordLevelTimestamps = "wordLevelTimestamps";
    QueryParameterNames.EndSilenceTimeoutMs = "endSilenceTimeoutMs";
    QueryParameterNames.Format = "format";
    QueryParameterNames.InitialSilenceTimeoutMs = "initialSilenceTimeoutMs";
    QueryParameterNames.Language = "language";
    QueryParameterNames.Profanity = "profanity";
    QueryParameterNames.RequestBotStatusMessages = "enableBotMessageStatus";
    QueryParameterNames.StableIntermediateThreshold = "stableIntermediateThreshold";
    QueryParameterNames.StableTranslation = "stableTranslation";
    QueryParameterNames.TestHooks = "testhooks";
    return QueryParameterNames;
}());
exports.QueryParameterNames = QueryParameterNames;



/***/ }),
/* 125 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActivityReceivedEventArgs = void 0;
/**
 * Defines contents of received message/events.
 * @class ActivityReceivedEventArgs
 */
var ActivityReceivedEventArgs = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {any} activity - The activity..
     */
    function ActivityReceivedEventArgs(activity, audioStream) {
        this.privActivity = activity;
        this.privAudioStream = audioStream;
    }
    Object.defineProperty(ActivityReceivedEventArgs.prototype, "activity", {
        /**
         * Gets the received activity
         * @member ActivityReceivedEventArgs.prototype.activity
         * @function
         * @public
         * @returns {any} the received activity.
         */
        get: function () {
            return this.privActivity;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ActivityReceivedEventArgs.prototype, "audioStream", {
        get: function () {
            return this.privAudioStream;
        },
        enumerable: false,
        configurable: true
    });
    return ActivityReceivedEventArgs;
}());
exports.ActivityReceivedEventArgs = ActivityReceivedEventArgs;



/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TurnStatusReceivedEventArgs = void 0;
var TurnStatusPayload_1 = __webpack_require__(127);
/**
 * Defines contents of received message/events.
 * @class TurnStatusReceivedEventArgs
 */
var TurnStatusReceivedEventArgs = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {string} turnStatus - The JSON-encoded turn status message.
     */
    function TurnStatusReceivedEventArgs(turnStatus) {
        this.privTurnStatus = TurnStatusPayload_1.TurnStatusResponsePayload.fromJSON(turnStatus);
    }
    Object.defineProperty(TurnStatusReceivedEventArgs.prototype, "interactionId", {
        /**
         * Gets the interaction identifier associated with this turn status event.
         * @member TurnStatusReceivedEventArgs.prototype.interactionId
         * @function
         * @public
         * @returns {any} the received interaction id.
         */
        get: function () {
            return this.privTurnStatus.interactionId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TurnStatusReceivedEventArgs.prototype, "conversationId", {
        /**
         * Gets the conversation identifier associated with this turn status event.
         * @member TurnStatusReceivedEventArgs.prototype.conversationId
         * @function
         * @public
         * @returns {any} the received conversation id.
         */
        get: function () {
            return this.privTurnStatus.conversationId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TurnStatusReceivedEventArgs.prototype, "statusCode", {
        /**
         * Gets the received turn status code.
         * @member TurnStatusReceivedEventArgs.prototype.statusCode
         * @function
         * @public
         * @returns {number} the received turn status.
         */
        get: function () {
            return this.privTurnStatus.statusCode;
        },
        enumerable: false,
        configurable: true
    });
    return TurnStatusReceivedEventArgs;
}());
exports.TurnStatusReceivedEventArgs = TurnStatusReceivedEventArgs;



/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TurnStatusResponsePayload = void 0;
var TurnStatusResponsePayload = /** @class */ (function () {
    function TurnStatusResponsePayload(json) {
        this.privMessageStatusResponse = JSON.parse(json);
    }
    TurnStatusResponsePayload.fromJSON = function (json) {
        return new TurnStatusResponsePayload(json);
    };
    Object.defineProperty(TurnStatusResponsePayload.prototype, "interactionId", {
        get: function () {
            return this.privMessageStatusResponse.interactionId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TurnStatusResponsePayload.prototype, "conversationId", {
        get: function () {
            return this.privMessageStatusResponse.conversationId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TurnStatusResponsePayload.prototype, "statusCode", {
        get: function () {
            // Payloads may contain a limited set of textual representations or a numeric status
            // code. The textual values are here converted into numeric ones.
            switch (this.privMessageStatusResponse.statusCode) {
                case "Success":
                    return 200;
                case "Failed":
                    return 400;
                case "TimedOut":
                    return 429;
                default:
                    return this.privMessageStatusResponse.statusCode;
            }
        },
        enumerable: false,
        configurable: true
    });
    return TurnStatusResponsePayload;
}());
exports.TurnStatusResponsePayload = TurnStatusResponsePayload;



/***/ }),
/* 128 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServicePropertyChannel = void 0;
/**
 * Defines channels used to pass property settings to service.
 * Added in version 1.7.0.
 */
var ServicePropertyChannel;
(function (ServicePropertyChannel) {
    /**
     * Uses URI query parameter to pass property settings to service.
     */
    ServicePropertyChannel[ServicePropertyChannel["UriQueryParameter"] = 0] = "UriQueryParameter";
})(ServicePropertyChannel = exports.ServicePropertyChannel || (exports.ServicePropertyChannel = {}));



/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProfanityOption = void 0;
/**
 * Profanity option.
 * Added in version 1.7.0.
 */
var ProfanityOption;
(function (ProfanityOption) {
    ProfanityOption[ProfanityOption["Masked"] = 0] = "Masked";
    ProfanityOption[ProfanityOption["Removed"] = 1] = "Removed";
    ProfanityOption[ProfanityOption["Raw"] = 2] = "Raw";
})(ProfanityOption = exports.ProfanityOption || (exports.ProfanityOption = {}));



/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseAudioPlayer = void 0;
var Error_1 = __webpack_require__(25);
var Promise_1 = __webpack_require__(40);
var Exports_1 = __webpack_require__(61);
var AudioStreamFormat_1 = __webpack_require__(72);
/**
 * Base audio player class
 * TODO: Plays only PCM for now.
 * @class
 */
var BaseAudioPlayer = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {AudioStreamFormat} audioFormat audio stream format recognized by the player.
     */
    function BaseAudioPlayer(audioFormat) {
        this.audioContext = null;
        this.gainNode = null;
        this.autoUpdateBufferTimer = 0;
        if (audioFormat === undefined) {
            audioFormat = Exports_1.AudioStreamFormat.getDefaultInputFormat();
        }
        this.init(audioFormat);
    }
    /**
     * play Audio sample
     * @param newAudioData audio data to be played.
     */
    BaseAudioPlayer.prototype.playAudioSample = function (newAudioData, cb, err) {
        var _this = this;
        Promise_1.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () {
            var audioData, newSamplesData;
            return __generator(this, function (_a) {
                this.ensureInitializedContext();
                audioData = this.formatAudioData(newAudioData);
                newSamplesData = new Float32Array(this.samples.length + audioData.length);
                newSamplesData.set(this.samples, 0);
                newSamplesData.set(audioData, this.samples.length);
                this.samples = newSamplesData;
                return [2 /*return*/];
            });
        }); })(), cb, err);
    };
    /**
     * stops audio and clears the buffers
     */
    BaseAudioPlayer.prototype.stopAudio = function (cb, err) {
        if (this.audioContext !== null) {
            this.samples = new Float32Array();
            clearInterval(this.autoUpdateBufferTimer);
            this.audioContext.close().then(function () {
                if (!!cb) {
                    cb();
                }
            }, function (error) {
                if (!!err) {
                    err(error);
                }
            });
            this.audioContext = null;
        }
    };
    BaseAudioPlayer.prototype.init = function (audioFormat) {
        this.audioFormat = audioFormat;
        this.samples = new Float32Array();
    };
    BaseAudioPlayer.prototype.ensureInitializedContext = function () {
        var _this = this;
        if (this.audioContext === null) {
            this.createAudioContext();
            var timerPeriod = 200;
            this.autoUpdateBufferTimer = setInterval(function () {
                _this.updateAudioBuffer();
            }, timerPeriod);
        }
    };
    BaseAudioPlayer.prototype.createAudioContext = function () {
        // new ((window as any).AudioContext || (window as any).webkitAudioContext)();
        this.audioContext = AudioStreamFormat_1.AudioStreamFormatImpl.getAudioContext();
        // TODO: Various examples shows this gain node, it does not seem to be needed unless we plan
        // to control the volume, not likely
        this.gainNode = this.audioContext.createGain();
        this.gainNode.gain.value = 1;
        this.gainNode.connect(this.audioContext.destination);
        this.startTime = this.audioContext.currentTime;
    };
    BaseAudioPlayer.prototype.formatAudioData = function (audioData) {
        switch (this.audioFormat.bitsPerSample) {
            case 8:
                return this.formatArrayBuffer(new Int8Array(audioData), 128);
            case 16:
                return this.formatArrayBuffer(new Int16Array(audioData), 32768);
            case 32:
                return this.formatArrayBuffer(new Int32Array(audioData), 2147483648);
            default:
                throw new Error_1.InvalidOperationError("Only WAVE_FORMAT_PCM (8/16/32 bps) format supported at this time");
        }
    };
    BaseAudioPlayer.prototype.formatArrayBuffer = function (audioData, maxValue) {
        var float32Data = new Float32Array(audioData.length);
        for (var i = 0; i < audioData.length; i++) {
            float32Data[i] = audioData[i] / maxValue;
        }
        return float32Data;
    };
    BaseAudioPlayer.prototype.updateAudioBuffer = function () {
        if (this.samples.length === 0) {
            return;
        }
        var channelCount = this.audioFormat.channels;
        var bufferSource = this.audioContext.createBufferSource();
        var frameCount = this.samples.length / channelCount;
        var audioBuffer = this.audioContext.createBuffer(channelCount, frameCount, this.audioFormat.samplesPerSec);
        // TODO: Should we do the conversion in the pushAudioSample instead?
        for (var channel = 0; channel < channelCount; channel++) {
            // Fill in individual channel data
            var channelOffset = channel;
            var audioData = audioBuffer.getChannelData(channel);
            for (var i = 0; i < this.samples.length; i++, channelOffset += channelCount) {
                audioData[i] = this.samples[channelOffset];
            }
        }
        if (this.startTime < this.audioContext.currentTime) {
            this.startTime = this.audioContext.currentTime;
        }
        bufferSource.buffer = audioBuffer;
        bufferSource.connect(this.gainNode);
        bufferSource.start(this.startTime);
        // Make sure we play the next sample after the current one.
        this.startTime += audioBuffer.duration;
        // Clear the samples for the next pushed data.
        this.samples = new Float32Array();
    };
    BaseAudioPlayer.prototype.playAudio = function (audioData) {
        return __awaiter(this, void 0, void 0, function () {
            var source, destination;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.audioContext === null) {
                            this.createAudioContext();
                        }
                        source = this.audioContext.createBufferSource();
                        destination = this.audioContext.destination;
                        return [4 /*yield*/, this.audioContext.decodeAudioData(audioData, function (newBuffer) {
                                source.buffer = newBuffer;
                                source.connect(destination);
                                source.start(0);
                            })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return BaseAudioPlayer;
}());
exports.BaseAudioPlayer = BaseAudioPlayer;



/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionMessageEventArgs = void 0;
var ConnectionMessageEventArgs = /** @class */ (function () {
    function ConnectionMessageEventArgs(message) {
        this.privConnectionMessage = message;
    }
    Object.defineProperty(ConnectionMessageEventArgs.prototype, "message", {
        /**
         * Gets the <see cref="ConnectionMessage"/> associated with this <see cref="ConnectionMessageEventArgs"/>.
         */
        get: function () {
            return this.privConnectionMessage;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Returns a string that represents the connection message event.
     */
    ConnectionMessageEventArgs.prototype.toString = function () {
        return "Message: " + this.privConnectionMessage.toString();
    };
    return ConnectionMessageEventArgs;
}());
exports.ConnectionMessageEventArgs = ConnectionMessageEventArgs;



/***/ }),
/* 132 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfile = void 0;
/**
 * Defines Voice Profile class for Speaker Recognition
 * @class VoiceProfile
 */
var VoiceProfile = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {string} profileId - profileId of this Voice Profile.
     * @param {VoiceProfileType} profileType - profileType of this Voice Profile.
     */
    function VoiceProfile(profileId, profileType) {
        this.privId = profileId;
        this.privProfileType = profileType;
    }
    Object.defineProperty(VoiceProfile.prototype, "profileId", {
        /**
         * profileId of this Voice Profile instance
         * @member VoiceProfile.prototype.profileId
         * @function
         * @public
         * @returns {string} profileId of this Voice Profile instance.
         */
        get: function () {
            return this.privId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceProfile.prototype, "profileType", {
        /**
         * profileType of this Voice Profile instance
         * @member VoiceProfile.prototype.profileType
         * @function
         * @public
         * @returns {VoiceProfileType} profile type of this Voice Profile instance.
         */
        get: function () {
            return this.privProfileType;
        },
        enumerable: false,
        configurable: true
    });
    return VoiceProfile;
}());
exports.VoiceProfile = VoiceProfile;



/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfileEnrollmentCancellationDetails = exports.VoiceProfileEnrollmentResult = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(61);
/**
 * Output format
 * @class VoiceProfileEnrollmentResult
 */
var VoiceProfileEnrollmentResult = /** @class */ (function () {
    function VoiceProfileEnrollmentResult(reason, json, statusText) {
        this.privReason = reason;
        this.privProperties = new Exports_2.PropertyCollection();
        if (this.privReason !== Exports_2.ResultReason.Canceled) {
            if (!!json) {
                this.privDetails = JSON.parse(json);
                if (this.privDetails.enrollmentStatus.toLowerCase() === "enrolling") {
                    this.privReason = Exports_2.ResultReason.EnrollingVoiceProfile;
                }
            }
        }
        else {
            this.privErrorDetails = statusText;
            this.privProperties.setProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.ServiceError]);
        }
    }
    VoiceProfileEnrollmentResult.FromIdentificationProfileList = function (json) {
        var results = [];
        for (var _i = 0, _a = json.value; _i < _a.length; _i++) {
            var item = _a[_i];
            var reason = item.enrollmentStatus.toLowerCase() === "enrolling" ?
                Exports_2.ResultReason.EnrollingVoiceProfile : item.enrollmentStatus.toLowerCase() === "enrolled" ?
                Exports_2.ResultReason.EnrolledVoiceProfile : Exports_2.ResultReason.Canceled;
            var result = new VoiceProfileEnrollmentResult(reason, null, null);
            result.privDetails = this.getIdentificationDetails(item);
            results.push(result);
        }
        return results;
    };
    VoiceProfileEnrollmentResult.FromVerificationProfileList = function (json) {
        var results = [];
        for (var _i = 0, _a = json.value; _i < _a.length; _i++) {
            var item = _a[_i];
            var reason = item.enrollmentStatus.toLowerCase() === "enrolling" ?
                Exports_2.ResultReason.EnrollingVoiceProfile : item.enrollmentStatus.toLowerCase() === "enrolled" ?
                Exports_2.ResultReason.EnrolledVoiceProfile : Exports_2.ResultReason.Canceled;
            var result = new VoiceProfileEnrollmentResult(reason, null, null);
            result.privDetails = this.getVerificationDetails(item);
            results.push(result);
        }
        return results;
    };
    Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "reason", {
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "enrollmentsCount", {
        get: function () {
            return this.privDetails.enrollmentsCount;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "enrollmentsLengthInSec", {
        get: function () {
            return this.privDetails.enrollmentsLengthInSec;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "properties", {
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "enrollmentResultDetails", {
        get: function () {
            return this.privDetails;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceProfileEnrollmentResult.prototype, "errorDetails", {
        get: function () {
            return this.privErrorDetails;
        },
        enumerable: false,
        configurable: true
    });
    VoiceProfileEnrollmentResult.getIdentificationDetails = function (json) {
        return {
            audioLengthInSec: json.audioLengthInSec ? parseFloat(json.audioLengthInSec) : 0,
            audioSpeechLengthInSec: json.audioSpeechLengthInSec ? parseFloat(json.audioSpeechLengthInSec) : 0,
            enrollmentStatus: json.enrollmentStatus,
            enrollmentsCount: json.enrollmentsCount || 0,
            enrollmentsLengthInSec: json.enrollmentsLengthInSec ? parseFloat(json.enrollmentsLengthInSec) : 0,
            enrollmentsSpeechLengthInSec: json.enrollmentsSpeechLengthInSec ? parseFloat(json.enrollmentsSpeechLengthInSec) : 0,
            profileId: json.profileId || json.identificationProfileId,
            remainingEnrollmentsSpeechLengthInSec: json.remainingEnrollmentsSpeechLengthInSec ? parseFloat(json.remainingEnrollmentsSpeechLengthInSec) : 0
        };
    };
    VoiceProfileEnrollmentResult.getVerificationDetails = function (json) {
        return {
            audioLengthInSec: json.audioLengthInSec ? parseFloat(json.audioLengthInSec) : 0,
            audioSpeechLengthInSec: json.audioSpeechLengthInSec ? parseFloat(json.audioSpeechLengthInSec) : 0,
            enrollmentStatus: json.enrollmentStatus,
            enrollmentsCount: json.enrollmentsCount,
            enrollmentsLengthInSec: json.enrollmentsLengthInSec ? parseFloat(json.enrollmentsLengthInSec) : 0,
            enrollmentsSpeechLengthInSec: json.enrollmentsSpeechLengthInSec ? parseFloat(json.enrollmentsSpeechLengthInSec) : 0,
            profileId: json.profileId || json.verificationProfileId,
            remainingEnrollmentsCount: json.remainingEnrollments || json.remainingEnrollmentsCount,
            remainingEnrollmentsSpeechLengthInSec: json.remainingEnrollmentsSpeechLengthInSec ? parseFloat(json.remainingEnrollmentsSpeechLengthInSec) : 0
        };
    };
    return VoiceProfileEnrollmentResult;
}());
exports.VoiceProfileEnrollmentResult = VoiceProfileEnrollmentResult;
/**
 * @class VoiceProfileEnrollmentCancellationDetails
 */
// tslint:disable-next-line:max-classes-per-file
var VoiceProfileEnrollmentCancellationDetails = /** @class */ (function (_super) {
    __extends(VoiceProfileEnrollmentCancellationDetails, _super);
    function VoiceProfileEnrollmentCancellationDetails(reason, errorDetails, errorCode) {
        return _super.call(this, reason, errorDetails, errorCode) || this;
    }
    /**
     * Creates an instance of VoiceProfileEnrollmentCancellationDetails object for the canceled VoiceProfileEnrollmentResult.
     * @member VoiceProfileEnrollmentCancellationDetails.fromResult
     * @function
     * @public
     * @param {VoiceProfileEnrollmentResult} result - The result that was canceled.
     * @returns {VoiceProfileEnrollmentCancellationDetails} The cancellation details object being created.
     */
    VoiceProfileEnrollmentCancellationDetails.fromResult = function (result) {
        var reason = Exports_2.CancellationReason.Error;
        var errorCode = Exports_2.CancellationErrorCode.NoError;
        if (!!result.properties) {
            errorCode = Exports_2.CancellationErrorCode[result.properties.getProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.NoError])];
        }
        return new VoiceProfileEnrollmentCancellationDetails(reason, result.errorDetails, errorCode);
    };
    return VoiceProfileEnrollmentCancellationDetails;
}(Exports_2.CancellationDetailsBase));
exports.VoiceProfileEnrollmentCancellationDetails = VoiceProfileEnrollmentCancellationDetails;



/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfileCancellationDetails = exports.VoiceProfileResult = void 0;
var Exports_1 = __webpack_require__(53);
var Contracts_1 = __webpack_require__(63);
var Exports_2 = __webpack_require__(61);
/**
 * Output format
 * @class VoiceProfileResult
 */
var VoiceProfileResult = /** @class */ (function () {
    function VoiceProfileResult(reason, statusText) {
        this.privReason = reason;
        this.privProperties = new Exports_2.PropertyCollection();
        if (reason === Exports_2.ResultReason.Canceled) {
            Contracts_1.Contracts.throwIfNullOrUndefined(statusText, "statusText");
            this.privErrorDetails = statusText;
            this.privProperties.setProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.ServiceError]);
        }
    }
    Object.defineProperty(VoiceProfileResult.prototype, "reason", {
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceProfileResult.prototype, "properties", {
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceProfileResult.prototype, "errorDetails", {
        get: function () {
            return this.privErrorDetails;
        },
        enumerable: false,
        configurable: true
    });
    return VoiceProfileResult;
}());
exports.VoiceProfileResult = VoiceProfileResult;
/**
 * @class VoiceProfileCancellationDetails
 */
// tslint:disable-next-line:max-classes-per-file
var VoiceProfileCancellationDetails = /** @class */ (function (_super) {
    __extends(VoiceProfileCancellationDetails, _super);
    function VoiceProfileCancellationDetails(reason, errorDetails, errorCode) {
        return _super.call(this, reason, errorDetails, errorCode) || this;
    }
    /**
     * Creates an instance of VoiceProfileCancellationDetails object for the canceled VoiceProfileResult.
     * @member VoiceProfileCancellationDetails.fromResult
     * @function
     * @public
     * @param {VoiceProfileResult} result - The result that was canceled.
     * @returns {VoiceProfileCancellationDetails} The cancellation details object being created.
     */
    VoiceProfileCancellationDetails.fromResult = function (result) {
        var reason = Exports_2.CancellationReason.Error;
        var errorCode = Exports_2.CancellationErrorCode.NoError;
        if (!!result.properties) {
            errorCode = Exports_2.CancellationErrorCode[result.properties.getProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.NoError])];
        }
        return new VoiceProfileCancellationDetails(reason, result.errorDetails, errorCode);
    };
    return VoiceProfileCancellationDetails;
}(Exports_2.CancellationDetailsBase));
exports.VoiceProfileCancellationDetails = VoiceProfileCancellationDetails;



/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfilePhraseResult = void 0;
var Contracts_1 = __webpack_require__(63);
var Exports_1 = __webpack_require__(61);
/**
 * Output format
 * @class VoiceProfilePhraseResult
 */
var VoiceProfilePhraseResult = /** @class */ (function (_super) {
    __extends(VoiceProfilePhraseResult, _super);
    function VoiceProfilePhraseResult(reason, statusText, json) {
        var _this = _super.call(this, reason, statusText) || this;
        _this.privPhrases = [];
        Contracts_1.Contracts.throwIfNullOrUndefined(json, "phrase result JSON");
        if (!!json.value && !!json.value[0]) {
            for (var _i = 0, _a = json.value; _i < _a.length; _i++) {
                var item = _a[_i];
                _this.privPhrases.push(item.passPhrase || item.activationPhrase);
            }
        }
        return _this;
    }
    Object.defineProperty(VoiceProfilePhraseResult.prototype, "phrases", {
        get: function () {
            return this.privPhrases;
        },
        enumerable: false,
        configurable: true
    });
    return VoiceProfilePhraseResult;
}(Exports_1.VoiceProfileResult));
exports.VoiceProfilePhraseResult = VoiceProfilePhraseResult;



/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfileClient = void 0;
var Exports_1 = __webpack_require__(53);
var Contracts_1 = __webpack_require__(63);
var Exports_2 = __webpack_require__(61);
/**
 * Defines VoiceProfileClient class for Speaker Recognition
 * Handles operations from user for Voice Profile operations (e.g. createProfile, deleteProfile)
 * @class VoiceProfileClient
 */
var VoiceProfileClient = /** @class */ (function () {
    /**
     * VoiceProfileClient constructor.
     * @constructor
     * @param {SpeechConfig} speechConfig - An set of initial properties for this synthesizer (authentication key, region, &c)
     */
    function VoiceProfileClient(speechConfig) {
        var speechConfigImpl = speechConfig;
        Contracts_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig");
        this.privProperties = speechConfigImpl.properties.clone();
        this.implClientSetup();
    }
    Object.defineProperty(VoiceProfileClient.prototype, "authorizationToken", {
        /**
         * Gets the authorization token used to communicate with the service.
         * @member VoiceProfileClient.prototype.authorizationToken
         * @function
         * @public
         * @returns {string} Authorization token.
         */
        get: function () {
            return this.properties.getProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token);
        },
        /**
         * Gets/Sets the authorization token used to communicate with the service.
         * @member VoiceProfileClient.prototype.authorizationToken
         * @function
         * @public
         * @param {string} token - Authorization token.
         */
        set: function (token) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token");
            this.properties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, token);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceProfileClient.prototype, "properties", {
        /**
         * The collection of properties and their values defined for this VoiceProfileClient.
         * @member VoiceProfileClient.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The collection of properties and their values defined for this VoiceProfileClient.
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Create a speaker recognition voice profile
     * @member VoiceProfileClient.prototype.createProfileAsync
     * @function
     * @public
     * @async
     * @param {VoiceProfileType} profileType Type of Voice Profile to be created
     *        specifies the keyword to be recognized.
     * @param {string} lang Language string (locale) for Voice Profile
     * @return {Promise<VoiceProfile>} - Promise of a VoiceProfile.
     */
    VoiceProfileClient.prototype.createProfileAsync = function (profileType, lang) {
        return __awaiter(this, void 0, void 0, function () {
            var result, response, profile;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.privAdapter.createProfile(profileType, lang)];
                    case 1:
                        result = _a.sent();
                        if (!result.ok) {
                            throw new Error("createProfileAsync failed with code: " + result.status + ", message: " + result.statusText);
                        }
                        response = result.json;
                        profile = new Exports_2.VoiceProfile(response.profileId, profileType);
                        return [2 /*return*/, profile];
                }
            });
        });
    };
    /**
     * Get current information of a voice profile
     * @member VoiceProfileClient.prototype.retrieveEnrollmentResultAsync
     * @function
     * @public
     * @async
     * @param {VoiceProfile} profile Voice Profile to retrieve info for
     * @return {Promise<VoiceProfileEnrollmentResult>} - Promise of a VoiceProfileEnrollmentResult.
     */
    VoiceProfileClient.prototype.retrieveEnrollmentResultAsync = function (profile) {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.privAdapter.getProfileStatus(profile)];
                    case 1:
                        result = _a.sent();
                        return [2 /*return*/, new Exports_2.VoiceProfileEnrollmentResult(result.ok ? Exports_2.ResultReason.EnrolledVoiceProfile : Exports_2.ResultReason.Canceled, result.data, result.statusText)];
                }
            });
        });
    };
    /**
     * Get all voice profiles on account with given voice profile type
     * @member VoiceProfileClient.prototype.getAllProfilesAsync
     * @function
     * @public
     * @async
     * @param {VoiceProfileType} profileType profile type (identification/verification) for which to list profiles
     * @return {Promise<VoiceProfileEnrollmentResult[]>} - Promise of an array of VoiceProfileEnrollmentResults.
     */
    VoiceProfileClient.prototype.getAllProfilesAsync = function (profileType) {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.privAdapter.getProfiles(profileType)];
                    case 1:
                        result = _a.sent();
                        if (profileType === Exports_2.VoiceProfileType.TextIndependentIdentification) {
                            return [2 /*return*/, Exports_2.VoiceProfileEnrollmentResult.FromIdentificationProfileList(result.json)];
                        }
                        return [2 /*return*/, Exports_2.VoiceProfileEnrollmentResult.FromVerificationProfileList(result.json)];
                }
            });
        });
    };
    /**
     * Get valid authorization phrases for voice profile enrollment
     * @member VoiceProfileClient.prototype.getAuthorizationPhrasesAsync
     * @function
     * @public
     * @async
     * @param {VoiceProfileType} profileType Profile Type to get activation phrases for
     * @param {string} lang Language string (locale) for Voice Profile
     */
    VoiceProfileClient.prototype.getActivationPhrasesAsync = function (profileType, lang) {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.privAdapter.getPhrases(profileType, lang)];
                    case 1:
                        result = _a.sent();
                        return [2 /*return*/, new Exports_2.VoiceProfilePhraseResult(result.ok ? Exports_2.ResultReason.EnrollingVoiceProfile : Exports_2.ResultReason.Canceled, result.statusText, result.json)];
                }
            });
        });
    };
    /**
     * Create a speaker recognition voice profile
     * @member VoiceProfileClient.prototype.enrollProfileAsync
     * @function
     * @public
     * @async
     * @param {VoiceProfile} profile Voice Profile to create enrollment for
     * @param {AudioConfig} audioConfig source info from which to create enrollment
     * @return {Promise<VoiceProfileEnrollmentResult>} - Promise of a VoiceProfileEnrollmentResult.
     */
    VoiceProfileClient.prototype.enrollProfileAsync = function (profile, audioConfig) {
        return __awaiter(this, void 0, void 0, function () {
            var configImpl, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        configImpl = audioConfig;
                        Contracts_1.Contracts.throwIfNullOrUndefined(configImpl, "audioConfig");
                        return [4 /*yield*/, this.privAdapter.createEnrollment(profile, configImpl)];
                    case 1:
                        result = _a.sent();
                        return [2 /*return*/, new Exports_2.VoiceProfileEnrollmentResult(result.ok ? Exports_2.ResultReason.EnrolledVoiceProfile : Exports_2.ResultReason.Canceled, result.data, result.statusText)];
                }
            });
        });
    };
    /**
     * Delete a speaker recognition voice profile
     * @member VoiceProfileClient.prototype.deleteProfileAsync
     * @function
     * @public
     * @async
     * @param {VoiceProfile} profile Voice Profile to be deleted
     * @return {Promise<VoiceProfileResult>} - Promise of a VoiceProfileResult.
     */
    VoiceProfileClient.prototype.deleteProfileAsync = function (profile) {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.privAdapter.deleteProfile(profile)];
                    case 1:
                        result = _a.sent();
                        return [2 /*return*/, this.getResult(result, Exports_2.ResultReason.DeletedVoiceProfile)];
                }
            });
        });
    };
    /**
     * Remove all enrollments for a speaker recognition voice profile
     * @member VoiceProfileClient.prototype.resetProfileAsync
     * @function
     * @public
     * @async
     * @param {VoiceProfile} profile Voice Profile to be reset
     * @return {Promise<VoiceProfileResult>} - Promise of a VoiceProfileResult.
     */
    VoiceProfileClient.prototype.resetProfileAsync = function (profile) {
        return __awaiter(this, void 0, void 0, function () {
            var result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.privAdapter.resetProfile(profile)];
                    case 1:
                        result = _a.sent();
                        return [2 /*return*/, this.getResult(result, Exports_2.ResultReason.ResetVoiceProfile)];
                }
            });
        });
    };
    /**
     * Included for compatibility
     * @member VoiceProfileClient.prototype.close
     * @function
     * @public
     */
    VoiceProfileClient.prototype.close = function () {
        return;
    };
    // Does class setup, swiped from Recognizer.
    VoiceProfileClient.prototype.implClientSetup = function () {
        var osPlatform = (typeof window !== "undefined") ? "Browser" : "Node";
        var osName = "unknown";
        var osVersion = "unknown";
        if (typeof navigator !== "undefined") {
            osPlatform = osPlatform + "/" + navigator.platform;
            osName = navigator.userAgent;
            osVersion = navigator.appVersion;
        }
        var recognizerConfig = new Exports_1.SpeakerRecognitionConfig(new Exports_1.Context(new Exports_1.OS(osPlatform, osName, osVersion)), this.privProperties);
        this.privAdapter = new Exports_1.SpeakerIdMessageAdapter(recognizerConfig);
    };
    VoiceProfileClient.prototype.getResult = function (result, successReason, cb) {
        var response = new Exports_2.VoiceProfileResult(result.ok ? successReason : Exports_2.ResultReason.Canceled, result.statusText);
        return (response);
    };
    return VoiceProfileClient;
}());
exports.VoiceProfileClient = VoiceProfileClient;



/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerRecognizer = void 0;
var Exports_1 = __webpack_require__(53);
var Contracts_1 = __webpack_require__(63);
var Exports_2 = __webpack_require__(61);
/**
 * Defines SpeakerRecognizer class for Speaker Recognition
 * Handles operations from user for Voice Profile operations (e.g. createProfile, deleteProfile)
 * @class SpeakerRecognizer
 */
var SpeakerRecognizer = /** @class */ (function () {
    /**
     * SpeakerRecognizer constructor.
     * @constructor
     * @param {SpeechConfig} speechConfig - An set of initial properties for this recognizer (authentication key, region, &c)
     */
    function SpeakerRecognizer(speechConfig, audioConfig) {
        var speechConfigImpl = speechConfig;
        Contracts_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig");
        this.privAudioConfigImpl = audioConfig;
        Contracts_1.Contracts.throwIfNull(this.privAudioConfigImpl, "audioConfig");
        this.privProperties = speechConfigImpl.properties.clone();
        this.implSRSetup();
    }
    Object.defineProperty(SpeakerRecognizer.prototype, "authorizationToken", {
        /**
         * Gets the authorization token used to communicate with the service.
         * @member SpeakerRecognizer.prototype.authorizationToken
         * @function
         * @public
         * @returns {string} Authorization token.
         */
        get: function () {
            return this.properties.getProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token);
        },
        /**
         * Gets/Sets the authorization token used to communicate with the service.
         * @member SpeakerRecognizer.prototype.authorizationToken
         * @function
         * @public
         * @param {string} token - Authorization token.
         */
        set: function (token) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token");
            this.properties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, token);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeakerRecognizer.prototype, "properties", {
        /**
         * The collection of properties and their values defined for this SpeakerRecognizer.
         * @member SpeakerRecognizer.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The collection of properties and their values defined for this SpeakerRecognizer.
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Get recognition result for model using given audio
     * @member SpeakerRecognizer.prototype.recognizeOnceAsync
     * @function
     * @public
     * @async
     * @param {SpeakerIdentificationModel} model Model containing Voice Profiles to be identified
     * @param cb - Callback invoked once result is returned.
     * @param err - Callback invoked in case of an error.
     */
    SpeakerRecognizer.prototype.recognizeOnceAsync = function (model) {
        return __awaiter(this, void 0, void 0, function () {
            var responsePromise, responsePromise;
            return __generator(this, function (_a) {
                if (model instanceof Exports_2.SpeakerIdentificationModel) {
                    responsePromise = this.privAdapter.identifySpeaker(model, this.privAudioConfigImpl);
                    return [2 /*return*/, this.getResult(responsePromise, Exports_2.SpeakerRecognitionResultType.Identify, undefined)];
                }
                else if (model instanceof Exports_2.SpeakerVerificationModel) {
                    responsePromise = this.privAdapter.verifySpeaker(model, this.privAudioConfigImpl);
                    return [2 /*return*/, this.getResult(responsePromise, Exports_2.SpeakerRecognitionResultType.Verify, model.voiceProfile.profileId)];
                }
                else {
                    throw new Error("SpeakerRecognizer.recognizeOnce: Unexpected model type");
                }
                return [2 /*return*/];
            });
        });
    };
    /**
     * Included for compatibility
     * @member SpeakerRecognizer.prototype.close
     * @function
     * @public
     */
    SpeakerRecognizer.prototype.close = function () {
        return;
    };
    // Does class setup, swiped from Recognizer.
    SpeakerRecognizer.prototype.implSRSetup = function () {
        var osPlatform = (typeof window !== "undefined") ? "Browser" : "Node";
        var osName = "unknown";
        var osVersion = "unknown";
        if (typeof navigator !== "undefined") {
            osPlatform = osPlatform + "/" + navigator.platform;
            osName = navigator.userAgent;
            osVersion = navigator.appVersion;
        }
        var recognizerConfig = new Exports_1.SpeakerRecognitionConfig(new Exports_1.Context(new Exports_1.OS(osPlatform, osName, osVersion)), this.privProperties);
        this.privAdapter = new Exports_1.SpeakerIdMessageAdapter(recognizerConfig);
    };
    SpeakerRecognizer.prototype.getResult = function (responsePromise, resultType, profileId) {
        return __awaiter(this, void 0, void 0, function () {
            var response;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, responsePromise];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, new Exports_2.SpeakerRecognitionResult(resultType, response.data, profileId, response.ok ? Exports_2.ResultReason.RecognizedSpeaker : Exports_2.ResultReason.Canceled)];
                }
            });
        });
    };
    return SpeakerRecognizer;
}());
exports.SpeakerRecognizer = SpeakerRecognizer;



/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerIdentificationModel = void 0;
var Contracts_1 = __webpack_require__(63);
var Exports_1 = __webpack_require__(61);
/**
 * Defines SpeakerIdentificationModel class for Speaker Recognition
 * Model contains a set of profiles against which to identify speaker(s)
 * @class SpeakerIdentificationModel
 */
var SpeakerIdentificationModel = /** @class */ (function () {
    function SpeakerIdentificationModel(profiles) {
        var _this = this;
        this.privVoiceProfiles = [];
        Contracts_1.Contracts.throwIfNullOrUndefined(profiles, "VoiceProfiles");
        if (profiles.length === 0) {
            throw new Error("Empty Voice Profiles array");
        }
        profiles.forEach(function (profile) {
            if (profile.profileType !== Exports_1.VoiceProfileType.TextIndependentIdentification) {
                throw new Error("Identification model can only be created from Identification profile: " + profile.profileId);
            }
            _this.privVoiceProfiles.push(profile);
        });
    }
    SpeakerIdentificationModel.fromProfiles = function (profiles) {
        return new SpeakerIdentificationModel(profiles);
    };
    Object.defineProperty(SpeakerIdentificationModel.prototype, "voiceProfileIds", {
        get: function () {
            return this.privVoiceProfiles.map(function (profile) { return profile.profileId; }).join(",");
        },
        enumerable: false,
        configurable: true
    });
    return SpeakerIdentificationModel;
}());
exports.SpeakerIdentificationModel = SpeakerIdentificationModel;



/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerVerificationModel = void 0;
var Contracts_1 = __webpack_require__(63);
var Exports_1 = __webpack_require__(61);
/**
 * Defines SpeakerVerificationModel class for Speaker Recognition
 * Model contains a profile against which to verify a speaker
 * @class SpeakerVerificationModel
 */
var SpeakerVerificationModel = /** @class */ (function () {
    function SpeakerVerificationModel(profile) {
        Contracts_1.Contracts.throwIfNullOrUndefined(profile, "VoiceProfile");
        if (profile.profileType === Exports_1.VoiceProfileType.TextIndependentIdentification) {
            throw new Error("Verification model cannot be created from Identification profile");
        }
        this.privVoiceProfile = profile;
    }
    SpeakerVerificationModel.fromProfile = function (profile) {
        return new SpeakerVerificationModel(profile);
    };
    Object.defineProperty(SpeakerVerificationModel.prototype, "voiceProfile", {
        get: function () {
            return this.privVoiceProfile;
        },
        enumerable: false,
        configurable: true
    });
    return SpeakerVerificationModel;
}());
exports.SpeakerVerificationModel = SpeakerVerificationModel;



/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutoDetectSourceLanguageConfig = void 0;
var Exports_1 = __webpack_require__(53);
var Contracts_1 = __webpack_require__(63);
var Exports_2 = __webpack_require__(61);
/**
 * Language auto detect configuration.
 * @class AutoDetectSourceLanguageConfig
 * Added in version 1.13.0.
 */
var AutoDetectSourceLanguageConfig = /** @class */ (function () {
    function AutoDetectSourceLanguageConfig() {
        this.privProperties = new Exports_2.PropertyCollection();
    }
    /**
     * @member AutoDetectSourceLanguageConfig.fromOpenRange
     * @function
     * @public
     * Only [[SpeechSynthesizer]] supports source language auto detection from open range,
     * for [[Recognizer]], please use AutoDetectSourceLanguageConfig with specific source languages.
     * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig
     * @summary Creates an instance of the AutoDetectSourceLanguageConfig with open range.
     */
    AutoDetectSourceLanguageConfig.fromOpenRange = function () {
        var config = new AutoDetectSourceLanguageConfig();
        config.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, Exports_1.AutoDetectSourceLanguagesOpenRangeOptionName);
        return config;
    };
    /**
     * @member AutoDetectSourceLanguageConfig.fromLanguages
     * @function
     * @public
     * @param {string[]} languages Comma-separated string of languages (eg. "en-US,fr-FR") to populate properties of config.
     * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig
     * @summary Creates an instance of the AutoDetectSourceLanguageConfig with given languages.
     */
    AutoDetectSourceLanguageConfig.fromLanguages = function (languages) {
        Contracts_1.Contracts.throwIfArrayEmptyOrWhitespace(languages, "languages");
        var config = new AutoDetectSourceLanguageConfig();
        config.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, languages.join());
        return config;
    };
    /**
     * @member AutoDetectSourceLanguageConfig.fromSourceLanguageConfigs
     * @function
     * @public
     * @param {SourceLanguageConfig[]} configs SourceLanguageConfigs to populate properties of config.
     * @return {AutoDetectSourceLanguageConfig} Instance of AutoDetectSourceLanguageConfig
     * @summary Creates an instance of the AutoDetectSourceLanguageConfig with given SourceLanguageConfigs.
     */
    AutoDetectSourceLanguageConfig.fromSourceLanguageConfigs = function (configs) {
        if (configs.length < 1) {
            throw new Error("Expected non-empty SourceLanguageConfig array.");
        }
        var autoConfig = new AutoDetectSourceLanguageConfig();
        var langs = [];
        configs.forEach(function (config) {
            langs.push(config.language);
            if (config.endpointId !== undefined && config.endpointId !== "") {
                var customProperty = config.language + Exports_2.PropertyId.SpeechServiceConnection_EndpointId.toString();
                autoConfig.properties.setProperty(customProperty, config.endpointId);
            }
        });
        autoConfig.properties.setProperty(Exports_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, langs.join());
        return autoConfig;
    };
    Object.defineProperty(AutoDetectSourceLanguageConfig.prototype, "properties", {
        /**
         * @member AutoDetectSourceLanguageConfig.prototype.properties
         * @function
         * @public
         * @return {PropertyCollection} Properties of the config.
         * @summary Gets an auto detected language config properties
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    return AutoDetectSourceLanguageConfig;
}());
exports.AutoDetectSourceLanguageConfig = AutoDetectSourceLanguageConfig;



/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutoDetectSourceLanguageResult = void 0;
var Contracts_1 = __webpack_require__(63);
/**
 * Output format
 * @class AutoDetectSourceLanguageResult
 */
var AutoDetectSourceLanguageResult = /** @class */ (function () {
    function AutoDetectSourceLanguageResult(language, languageDetectionConfidence) {
        Contracts_1.Contracts.throwIfNullOrUndefined(language, "language");
        Contracts_1.Contracts.throwIfNullOrUndefined(languageDetectionConfidence, "languageDetectionConfidence");
        this.privLanguage = language;
        this.privLanguageDetectionConfidence = languageDetectionConfidence;
    }
    /**
     * Creates an instance of AutoDetectSourceLanguageResult object from a SpeechRecognitionResult instance.
     * @member AutoDetectSourceLanguageResult.fromResult
     * @function
     * @public
     * @param {SpeechRecognitionResult} result - The recognition result.
     * @returns {AutoDetectSourceLanguageResult} AutoDetectSourceLanguageResult object being created.
     */
    AutoDetectSourceLanguageResult.fromResult = function (result) {
        return new AutoDetectSourceLanguageResult(result.language, result.languageDetectionConfidence);
    };
    Object.defineProperty(AutoDetectSourceLanguageResult.prototype, "language", {
        get: function () {
            return this.privLanguage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AutoDetectSourceLanguageResult.prototype, "languageDetectionConfidence", {
        get: function () {
            return this.privLanguageDetectionConfidence;
        },
        enumerable: false,
        configurable: true
    });
    return AutoDetectSourceLanguageResult;
}());
exports.AutoDetectSourceLanguageResult = AutoDetectSourceLanguageResult;



/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourceLanguageConfig = void 0;
var Contracts_1 = __webpack_require__(63);
/**
 * Source Language configuration.
 * @class SourceLanguageConfig
 */
var SourceLanguageConfig = /** @class */ (function () {
    function SourceLanguageConfig(language, endpointId) {
        Contracts_1.Contracts.throwIfNullOrUndefined(language, "language");
        this.privLanguage = language;
        this.privEndpointId = endpointId;
    }
    /**
     * @member SourceLanguageConfig.fromLanguage
     * @function
     * @public
     * @param {string} language language (eg. "en-US") value of config.
     * @param {string?} endpointId endpointId of model bound to given language of config.
     * @return {SourceLanguageConfig} Instance of SourceLanguageConfig
     * @summary Creates an instance of the SourceLanguageConfig with the given language and optional endpointId.
     * Added in version 1.13.0.
     */
    SourceLanguageConfig.fromLanguage = function (language, endpointId) {
        return new SourceLanguageConfig(language, endpointId);
    };
    Object.defineProperty(SourceLanguageConfig.prototype, "language", {
        get: function () {
            return this.privLanguage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SourceLanguageConfig.prototype, "endpointId", {
        get: function () {
            return this.privEndpointId;
        },
        enumerable: false,
        configurable: true
    });
    return SourceLanguageConfig;
}());
exports.SourceLanguageConfig = SourceLanguageConfig;



/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerRecognitionCancellationDetails = exports.SpeakerRecognitionResult = exports.SpeakerRecognitionResultType = void 0;
var Exports_1 = __webpack_require__(53);
var Contracts_1 = __webpack_require__(63);
var Exports_2 = __webpack_require__(61);
var SpeakerRecognitionResultType;
(function (SpeakerRecognitionResultType) {
    SpeakerRecognitionResultType[SpeakerRecognitionResultType["Verify"] = 0] = "Verify";
    SpeakerRecognitionResultType[SpeakerRecognitionResultType["Identify"] = 1] = "Identify";
})(SpeakerRecognitionResultType = exports.SpeakerRecognitionResultType || (exports.SpeakerRecognitionResultType = {}));
/**
 * Output format
 * @class SpeakerRecognitionResult
 */
var SpeakerRecognitionResult = /** @class */ (function () {
    function SpeakerRecognitionResult(resultType, data, profileId, resultReason) {
        if (resultReason === void 0) { resultReason = Exports_2.ResultReason.RecognizedSpeaker; }
        this.privProperties = new Exports_2.PropertyCollection();
        this.privReason = resultReason;
        if (this.privReason !== Exports_2.ResultReason.Canceled) {
            if (resultType === SpeakerRecognitionResultType.Identify) {
                var json = JSON.parse(data);
                Contracts_1.Contracts.throwIfNullOrUndefined(json, "JSON");
                this.privProfileId = json.identifiedProfile.profileId;
                this.privScore = json.identifiedProfile.score;
            }
            else {
                var json = JSON.parse(data);
                Contracts_1.Contracts.throwIfNullOrUndefined(json, "JSON");
                this.privScore = json.score;
                if (json.recognitionResult.toLowerCase() !== "accept") {
                    this.privReason = Exports_2.ResultReason.NoMatch;
                }
                if (profileId !== undefined && profileId !== "") {
                    this.privProfileId = profileId;
                }
            }
        }
        else {
            var json = JSON.parse(data);
            Contracts_1.Contracts.throwIfNullOrUndefined(json, "JSON");
            this.privErrorDetails = json.statusText;
            this.privProperties.setProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.ServiceError]);
        }
        this.privProperties.setProperty(Exports_2.PropertyId.SpeechServiceResponse_JsonResult, data);
    }
    Object.defineProperty(SpeakerRecognitionResult.prototype, "properties", {
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeakerRecognitionResult.prototype, "reason", {
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeakerRecognitionResult.prototype, "profileId", {
        get: function () {
            return this.privProfileId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeakerRecognitionResult.prototype, "errorDetails", {
        get: function () {
            return this.privErrorDetails;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeakerRecognitionResult.prototype, "score", {
        get: function () {
            return this.privScore;
        },
        enumerable: false,
        configurable: true
    });
    return SpeakerRecognitionResult;
}());
exports.SpeakerRecognitionResult = SpeakerRecognitionResult;
/**
 * @class SpeakerRecognitionCancellationDetails
 */
// tslint:disable-next-line:max-classes-per-file
var SpeakerRecognitionCancellationDetails = /** @class */ (function (_super) {
    __extends(SpeakerRecognitionCancellationDetails, _super);
    function SpeakerRecognitionCancellationDetails(reason, errorDetails, errorCode) {
        return _super.call(this, reason, errorDetails, errorCode) || this;
    }
    /**
     * Creates an instance of SpeakerRecognitionCancellationDetails object for the canceled SpeakerRecognitionResult
     * @member SpeakerRecognitionCancellationDetails.fromResult
     * @function
     * @public
     * @param {SpeakerRecognitionResult} result - The result that was canceled.
     * @returns {SpeakerRecognitionCancellationDetails} The cancellation details object being created.
     */
    SpeakerRecognitionCancellationDetails.fromResult = function (result) {
        var reason = Exports_2.CancellationReason.Error;
        var errorCode = Exports_2.CancellationErrorCode.NoError;
        if (!!result.properties) {
            errorCode = Exports_2.CancellationErrorCode[result.properties.getProperty(Exports_1.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[Exports_2.CancellationErrorCode.NoError])];
        }
        return new SpeakerRecognitionCancellationDetails(reason, result.errorDetails, errorCode);
    };
    return SpeakerRecognitionCancellationDetails;
}(Exports_2.CancellationDetailsBase));
exports.SpeakerRecognitionCancellationDetails = SpeakerRecognitionCancellationDetails;



/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Multi-device Conversation is a Preview feature.
Object.defineProperty(exports, "__esModule", { value: true });
var Conversation_1 = __webpack_require__(145);
Object.defineProperty(exports, "Conversation", { enumerable: true, get: function () { return Conversation_1.Conversation; } });
Object.defineProperty(exports, "ConversationImpl", { enumerable: true, get: function () { return Conversation_1.ConversationImpl; } });
var ConversationCommon_1 = __webpack_require__(146);
Object.defineProperty(exports, "ConversationCommon", { enumerable: true, get: function () { return ConversationCommon_1.ConversationCommon; } });
var ConversationExpirationEventArgs_1 = __webpack_require__(147);
Object.defineProperty(exports, "ConversationExpirationEventArgs", { enumerable: true, get: function () { return ConversationExpirationEventArgs_1.ConversationExpirationEventArgs; } });
var ConversationParticipantsChangedEventArgs_1 = __webpack_require__(148);
Object.defineProperty(exports, "ConversationParticipantsChangedEventArgs", { enumerable: true, get: function () { return ConversationParticipantsChangedEventArgs_1.ConversationParticipantsChangedEventArgs; } });
var ConversationTranslationCanceledEventArgs_1 = __webpack_require__(149);
Object.defineProperty(exports, "ConversationTranslationCanceledEventArgs", { enumerable: true, get: function () { return ConversationTranslationCanceledEventArgs_1.ConversationTranslationCanceledEventArgs; } });
var ConversationTranslationEventArgs_1 = __webpack_require__(150);
Object.defineProperty(exports, "ConversationTranslationEventArgs", { enumerable: true, get: function () { return ConversationTranslationEventArgs_1.ConversationTranslationEventArgs; } });
var ConversationTranslationResult_1 = __webpack_require__(151);
Object.defineProperty(exports, "ConversationTranslationResult", { enumerable: true, get: function () { return ConversationTranslationResult_1.ConversationTranslationResult; } });
var ConversationTranslator_1 = __webpack_require__(152);
Object.defineProperty(exports, "ConversationTranslator", { enumerable: true, get: function () { return ConversationTranslator_1.ConversationTranslator; } });
var ConversationTranscriber_1 = __webpack_require__(153);
Object.defineProperty(exports, "ConversationTranscriber", { enumerable: true, get: function () { return ConversationTranscriber_1.ConversationTranscriber; } });
var IParticipant_1 = __webpack_require__(154);
Object.defineProperty(exports, "Participant", { enumerable: true, get: function () { return IParticipant_1.Participant; } });
Object.defineProperty(exports, "User", { enumerable: true, get: function () { return IParticipant_1.User; } });
var ParticipantChangedReason_1 = __webpack_require__(155);
Object.defineProperty(exports, "ParticipantChangedReason", { enumerable: true, get: function () { return ParticipantChangedReason_1.ParticipantChangedReason; } });



/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Multi-device Conversation is a Preview feature.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationImpl = exports.Conversation = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
var Conversation = /** @class */ (function () {
    function Conversation() {
    }
    /**
     * Create a conversation
     * @param speechConfig
     * @param cb
     * @param err
     */
    Conversation.createConversationAsync = function (speechConfig, arg2, arg3, arg4) {
        Contracts_1.Contracts.throwIfNullOrUndefined(speechConfig, Exports_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "config"));
        Contracts_1.Contracts.throwIfNullOrUndefined(speechConfig.region, Exports_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "SpeechServiceConnection_Region"));
        if (!speechConfig.subscriptionKey && !speechConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceAuthorization_Token])) {
            Contracts_1.Contracts.throwIfNullOrUndefined(speechConfig.subscriptionKey, Exports_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "SpeechServiceConnection_Key"));
        }
        var conversationImpl;
        var cb;
        var err;
        if (typeof arg2 === "string") {
            conversationImpl = new ConversationImpl(speechConfig, arg2);
            cb = arg3;
            err = arg4;
        }
        else {
            conversationImpl = new ConversationImpl(speechConfig);
            cb = arg2;
            err = arg3;
        }
        conversationImpl.createConversationAsync((function () {
            if (!!cb) {
                cb();
            }
        }), function (error) {
            if (!!err) {
                err(error);
            }
        });
        return conversationImpl;
    };
    return Conversation;
}());
exports.Conversation = Conversation;
// tslint:disable-next-line:max-classes-per-file
var ConversationImpl = /** @class */ (function (_super) {
    __extends(ConversationImpl, _super);
    /**
     * Create a conversation impl
     * @param speechConfig
     * @param {string} id - optional conversationId
     */
    function ConversationImpl(speechConfig, id) {
        var _this = _super.call(this) || this;
        _this.privIsDisposed = false;
        _this.privIsConnected = false;
        _this.privErrors = Exports_1.ConversationConnectionConfig.restErrors;
        _this.privConversationId = "";
        /** websocket callbacks */
        _this.onConnected = function (e) {
            var _a, _b;
            _this.privIsConnected = true;
            try {
                if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.sessionStarted)) {
                    _this.privConversationTranslator.sessionStarted(_this.privConversationTranslator, e);
                }
                if (!!((_b = _this.privTranscriberRecognizer) === null || _b === void 0 ? void 0 : _b.conversationStarted)) {
                    _this.privTranscriberRecognizer.conversationStarted(_this.privTranscriberRecognizer, e);
                }
            }
            catch (e) {
                //
            }
        };
        _this.onDisconnected = function (e) { return __awaiter(_this, void 0, void 0, function () {
            var e_1;
            var _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _c.trys.push([0, 1, 2, 4]);
                        if (!!((_a = this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.sessionStopped)) {
                            this.privConversationTranslator.sessionStopped(this.privConversationTranslator, e);
                        }
                        if (!!((_b = this.privTranscriberRecognizer) === null || _b === void 0 ? void 0 : _b.conversationStopped)) {
                            this.privTranscriberRecognizer.conversationStopped(this.privTranscriberRecognizer, e);
                        }
                        return [3 /*break*/, 4];
                    case 1:
                        e_1 = _c.sent();
                        return [3 /*break*/, 4];
                    case 2: return [4 /*yield*/, this.close(false)];
                    case 3:
                        _c.sent();
                        return [7 /*endfinally*/];
                    case 4: return [2 /*return*/];
                }
            });
        }); };
        _this.onCanceled = function (r, e) { return __awaiter(_this, void 0, void 0, function () {
            var _a, _b;
            return __generator(this, function (_c) {
                try {
                    if (!!((_a = this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.canceled)) {
                        this.privConversationTranslator.canceled(this.privConversationTranslator, e);
                    }
                    if (!!((_b = this.privTranscriberRecognizer) === null || _b === void 0 ? void 0 : _b.conversationCanceled)) {
                        this.privTranscriberRecognizer.conversationCanceled(this.privTranscriberRecognizer, e);
                    }
                }
                catch (e) {
                    //
                }
                return [2 /*return*/];
            });
        }); };
        _this.onParticipantUpdateCommandReceived = function (r, e) {
            var _a, _b;
            try {
                var updatedParticipant = _this.privParticipants.getParticipant(e.id);
                if (updatedParticipant !== undefined) {
                    switch (e.key) {
                        case Exports_1.ConversationTranslatorCommandTypes.changeNickname:
                            updatedParticipant.displayName = e.value;
                            break;
                        case Exports_1.ConversationTranslatorCommandTypes.setUseTTS:
                            updatedParticipant.useTts = e.value;
                            break;
                        case Exports_1.ConversationTranslatorCommandTypes.setProfanityFiltering:
                            updatedParticipant.profanity = e.value;
                            break;
                        case Exports_1.ConversationTranslatorCommandTypes.setMute:
                            updatedParticipant.isMuted = e.value;
                            break;
                        case Exports_1.ConversationTranslatorCommandTypes.setTranslateToLanguages:
                            updatedParticipant.translateToLanguages = e.value;
                            break;
                    }
                    _this.privParticipants.addOrUpdateParticipant(updatedParticipant);
                    if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.participantsChanged)) {
                        (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.participantsChanged(_this.privConversationTranslator, new Exports_3.ConversationParticipantsChangedEventArgs(Exports_3.ParticipantChangedReason.Updated, [_this.toParticipant(updatedParticipant)], e.sessionId));
                    }
                }
            }
            catch (e) {
                //
            }
        };
        _this.onLockRoomCommandReceived = function (r, e) {
            // TODO
        };
        _this.onMuteAllCommandReceived = function (r, e) {
            var _a, _b;
            try {
                _this.privParticipants.participants.forEach(function (p) { return p.isMuted = (p.isHost ? false : e.isMuted); });
                if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.participantsChanged)) {
                    (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.participantsChanged(_this.privConversationTranslator, new Exports_3.ConversationParticipantsChangedEventArgs(Exports_3.ParticipantChangedReason.Updated, _this.toParticipants(false), e.sessionId));
                }
            }
            catch (e) {
                //
            }
        };
        _this.onParticipantJoinCommandReceived = function (r, e) {
            var _a, _b;
            try {
                var newParticipant = _this.privParticipants.addOrUpdateParticipant(e.participant);
                if (newParticipant !== undefined) {
                    if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.participantsChanged)) {
                        (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.participantsChanged(_this.privConversationTranslator, new Exports_3.ConversationParticipantsChangedEventArgs(Exports_3.ParticipantChangedReason.JoinedConversation, [_this.toParticipant(newParticipant)], e.sessionId));
                    }
                }
            }
            catch (e) {
                //
            }
        };
        _this.onParticipantLeaveCommandReceived = function (r, e) {
            var _a, _b;
            try {
                var ejectedParticipant = _this.privParticipants.getParticipant(e.participant.id);
                if (ejectedParticipant !== undefined) {
                    // remove the participant from the internal participants list
                    _this.privParticipants.deleteParticipant(e.participant.id);
                    if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.participantsChanged)) {
                        // notify subscribers that the participant has left the conversation
                        (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.participantsChanged(_this.privConversationTranslator, new Exports_3.ConversationParticipantsChangedEventArgs(Exports_3.ParticipantChangedReason.LeftConversation, [_this.toParticipant(ejectedParticipant)], e.sessionId));
                    }
                }
            }
            catch (e) {
                //
            }
        };
        _this.onTranslationReceived = function (r, e) {
            var _a, _b, _c, _d, _e, _f;
            try {
                switch (e.command) {
                    case Exports_1.ConversationTranslatorMessageTypes.final:
                        if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.transcribed)) {
                            (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.transcribed(_this.privConversationTranslator, new Exports_3.ConversationTranslationEventArgs(e.payload, undefined, e.sessionId));
                        }
                        break;
                    case Exports_1.ConversationTranslatorMessageTypes.partial:
                        if (!!((_c = _this.privConversationTranslator) === null || _c === void 0 ? void 0 : _c.transcribing)) {
                            (_d = _this.privConversationTranslator) === null || _d === void 0 ? void 0 : _d.transcribing(_this.privConversationTranslator, new Exports_3.ConversationTranslationEventArgs(e.payload, undefined, e.sessionId));
                        }
                        break;
                    case Exports_1.ConversationTranslatorMessageTypes.instantMessage:
                        if (!!((_e = _this.privConversationTranslator) === null || _e === void 0 ? void 0 : _e.textMessageReceived)) {
                            (_f = _this.privConversationTranslator) === null || _f === void 0 ? void 0 : _f.textMessageReceived(_this.privConversationTranslator, new Exports_3.ConversationTranslationEventArgs(e.payload, undefined, e.sessionId));
                        }
                        break;
                }
            }
            catch (e) {
                //
            }
        };
        _this.onParticipantsListReceived = function (r, e) {
            var _a, _b, _c;
            try {
                // check if the session token needs to be updated
                if (e.sessionToken !== undefined && e.sessionToken !== null) {
                    _this.privRoom.token = e.sessionToken;
                }
                // save the participants
                _this.privParticipants.participants = __spreadArrays(e.participants);
                // enable the conversation
                if (_this.privParticipants.me !== undefined) {
                    _this.privIsReady = true;
                }
                if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.participantsChanged)) {
                    (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.participantsChanged(_this.privConversationTranslator, new Exports_3.ConversationParticipantsChangedEventArgs(Exports_3.ParticipantChangedReason.JoinedConversation, _this.toParticipants(true), e.sessionId));
                }
                // if this is the host, update the nickname if needed
                if (_this.me.isHost) {
                    var nickname = (_c = _this.privConversationTranslator) === null || _c === void 0 ? void 0 : _c.properties.getProperty(Exports_3.PropertyId.ConversationTranslator_Name);
                    if (nickname !== undefined && nickname.length > 0 && nickname !== _this.me.displayName) {
                        // issue a change nickname request
                        _this.changeNicknameAsync(nickname);
                    }
                }
            }
            catch (e) {
                //
            }
        };
        _this.onConversationExpiration = function (r, e) {
            var _a, _b;
            try {
                if (!!((_a = _this.privConversationTranslator) === null || _a === void 0 ? void 0 : _a.conversationExpiration)) {
                    (_b = _this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.conversationExpiration(_this.privConversationTranslator, e);
                }
            }
            catch (e) {
                //
            }
        };
        _this.privProperties = new Exports_3.PropertyCollection();
        _this.privManager = new Exports_1.ConversationManager();
        // check the speech language
        var language = speechConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
        if (!language) {
            speechConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage], Exports_1.ConversationConnectionConfig.defaultLanguageCode);
        }
        _this.privLanguage = speechConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
        if (!id) {
            // check the target language(s)
            if (speechConfig.targetLanguages.length === 0) {
                speechConfig.addTargetLanguage(_this.privLanguage);
            }
            // check the profanity setting: speech and conversationTranslator should be in sync
            var profanity = speechConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceResponse_ProfanityOption]);
            if (!profanity) {
                speechConfig.setProfanity(Exports_3.ProfanityOption.Masked);
            }
            // check the nickname: it should pass this regex: ^\w+([\s-][\w\(\)]+)*$"
            // TODO: specify the regex required. Nicknames must be unique or get the duplicate nickname error
            // TODO: check what the max length is and if a truncation is required or if the service handles it without an error
            var hostNickname = speechConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.ConversationTranslator_Name]);
            if (hostNickname === undefined || hostNickname === null || hostNickname.length <= 1 || hostNickname.length > 50) {
                hostNickname = "Host";
            }
            speechConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.ConversationTranslator_Name], hostNickname);
        }
        else {
            _this.privConversationId = id;
        }
        // save the speech config for future usage
        _this.privConfig = speechConfig;
        // save the config properties
        var configImpl = speechConfig;
        Contracts_1.Contracts.throwIfNull(configImpl, "speechConfig");
        _this.privProperties = configImpl.properties.clone();
        _this.privIsConnected = false;
        _this.privParticipants = new Exports_1.InternalParticipants();
        _this.privIsReady = false;
        _this.privTextMessageMaxLength = 1000;
        return _this;
    }
    Object.defineProperty(ConversationImpl.prototype, "conversationTranslator", {
        set: function (conversationTranslator) {
            this.privConversationTranslator = conversationTranslator;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "room", {
        // get the internal data about a conversation
        get: function () {
            return this.privRoom;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "connection", {
        // get the wrapper for connecting to the websockets
        get: function () {
            return this.privConversationRecognizer; // this.privConnection;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "authorizationToken", {
        // get / set the speech auth token
        get: function () {
            return this.privToken;
        },
        set: function (value) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(value, "authorizationToken");
            this.privToken = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "config", {
        // get the config
        get: function () {
            return this.privConfig;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "conversationId", {
        // get the conversation Id
        get: function () {
            return this.privRoom ? this.privRoom.roomId : this.privConversationId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "properties", {
        // get the properties
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "speechRecognitionLanguage", {
        // get the speech language
        get: function () {
            return this.privLanguage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "isMutedByHost", {
        get: function () {
            var _a, _b;
            return ((_a = this.privParticipants.me) === null || _a === void 0 ? void 0 : _a.isHost) ? false : (_b = this.privParticipants.me) === null || _b === void 0 ? void 0 : _b.isMuted;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "isConnected", {
        get: function () {
            return this.privIsConnected && this.privIsReady;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "participants", {
        get: function () {
            return this.toParticipants(true);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "me", {
        get: function () {
            return this.toParticipant(this.privParticipants.me);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "host", {
        get: function () {
            return this.toParticipant(this.privParticipants.host);
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Create a new conversation as Host
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.createConversationAsync = function (cb, err) {
        var _this = this;
        try {
            if (!!this.privConversationRecognizer) {
                this.handleError(new Error(this.privErrors.permissionDeniedStart), err);
            }
            this.privManager.createOrJoin(this.privProperties, undefined, (function (room) {
                if (!room) {
                    _this.handleError(new Error(_this.privErrors.permissionDeniedConnect), err);
                }
                _this.privRoom = room;
                _this.handleCallback(cb, err);
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Starts a new conversation as host.
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.startConversationAsync = function (cb, err) {
        var _this = this;
        try {
            // check if there is already a recognizer
            if (!!this.privConversationRecognizer) {
                this.handleError(new Error(this.privErrors.permissionDeniedStart), err);
            }
            // check if there is conversation data available
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedConnect);
            // connect to the conversation websocket
            this.privParticipants.meId = this.privRoom.participantId;
            this.privConversationRecognizer = Exports_1.ConversationRecognizerFactory.fromConfig(this, this.privConfig);
            // Because ConversationTranslator manually sets up and manages the connection, Conversation
            // has to forward serviceRecognizer connection events that usually get passed automatically
            this.privConversationRecognizer.connected = this.onConnected;
            this.privConversationRecognizer.disconnected = this.onDisconnected;
            this.privConversationRecognizer.canceled = this.onCanceled;
            this.privConversationRecognizer.participantUpdateCommandReceived = this.onParticipantUpdateCommandReceived;
            this.privConversationRecognizer.lockRoomCommandReceived = this.onLockRoomCommandReceived;
            this.privConversationRecognizer.muteAllCommandReceived = this.onMuteAllCommandReceived;
            this.privConversationRecognizer.participantJoinCommandReceived = this.onParticipantJoinCommandReceived;
            this.privConversationRecognizer.participantLeaveCommandReceived = this.onParticipantLeaveCommandReceived;
            this.privConversationRecognizer.translationReceived = this.onTranslationReceived;
            this.privConversationRecognizer.participantsListReceived = this.onParticipantsListReceived;
            this.privConversationRecognizer.conversationExpiration = this.onConversationExpiration;
            this.privConversationRecognizer.connect(this.privRoom.token, (function () {
                _this.handleCallback(cb, err);
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Join a conversation as a participant.
     * @param { IParticipant } participant - participant to add
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.addParticipantAsync = function (participant, cb, err) {
        Contracts_1.Contracts.throwIfNullOrUndefined(participant, "Participant");
        Exports_2.marshalPromiseToCallbacks(this.addParticipantImplAsync(participant), cb, err);
    };
    /**
     * Join a conversation as a participant.
     * @param conversation
     * @param nickname
     * @param lang
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.joinConversationAsync = function (conversationId, nickname, lang, cb, err) {
        var _this = this;
        try {
            // TODO
            // if (!!this.privConversationRecognizer) {
            //     throw new Error(this.privErrors.permissionDeniedStart);
            // }
            Contracts_1.Contracts.throwIfNullOrWhitespace(conversationId, this.privErrors.invalidArgs.replace("{arg}", "conversationId"));
            Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname"));
            Contracts_1.Contracts.throwIfNullOrWhitespace(lang, this.privErrors.invalidArgs.replace("{arg}", "language"));
            // join the conversation
            this.privManager.createOrJoin(this.privProperties, conversationId, (function (room) {
                Contracts_1.Contracts.throwIfNullOrUndefined(room, _this.privErrors.permissionDeniedConnect);
                _this.privRoom = room;
                _this.privConfig.authorizationToken = room.cognitiveSpeechAuthToken;
                // join callback
                if (!!cb) {
                    cb(room.cognitiveSpeechAuthToken);
                }
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Deletes a conversation
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.deleteConversationAsync = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.deleteConversationImplAsync(), cb, err);
    };
    ConversationImpl.prototype.deleteConversationImplAsync = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        Contracts_1.Contracts.throwIfNullOrUndefined(this.privProperties, this.privErrors.permissionDeniedConnect);
                        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.token, this.privErrors.permissionDeniedConnect);
                        return [4 /*yield*/, this.privManager.leave(this.privProperties, this.privRoom.token)];
                    case 1:
                        _a.sent();
                        this.dispose();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Issues a request to close the client websockets
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.endConversationAsync = function (cb, err) {
        Exports_2.marshalPromiseToCallbacks(this.endConversationImplAsync(), cb, err);
    };
    ConversationImpl.prototype.endConversationImplAsync = function () {
        return this.close(true);
    };
    /**
     * Issues a request to lock the conversation
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.lockConversationAsync = function (cb, err) {
        var _this = this;
        var _a;
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
            if (!this.canSendAsHost) {
                this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "lock")), err);
            }
            (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getLockCommand(true), (function () {
                _this.handleCallback(cb, err);
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Issues a request to mute the conversation
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.muteAllParticipantsAsync = function (cb, err) {
        var _this = this;
        var _a;
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversationRecognizer, this.privErrors.permissionDeniedSend);
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
            // check the user's permissions
            if (!this.canSendAsHost) {
                this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "mute")), err);
            }
            (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getMuteAllCommand(true), (function () {
                _this.handleCallback(cb, err);
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Issues a request to mute a participant in the conversation
     * @param userId
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.muteParticipantAsync = function (userId, cb, err) {
        var _this = this;
        var _a;
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
            Contracts_1.Contracts.throwIfNullOrWhitespace(userId, this.privErrors.invalidArgs.replace("{arg}", "userId"));
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
            // check the connection is open (host + participant can perform the mute command)
            if (!this.canSend) {
                this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
            }
            // if not host, check the participant is not muting another participant
            if (!this.me.isHost && this.me.id !== userId) {
                this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "mute")), err);
            }
            // check the user exists
            var exists = this.privParticipants.getParticipantIndex(userId);
            if (exists === -1) {
                this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);
            }
            (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getMuteCommand(userId, true), (function () {
                _this.handleCallback(cb, err);
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Issues a request to remove a participant from the conversation
     * @param userId
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.removeParticipantAsync = function (userId, cb, err) {
        var _this = this;
        var _a;
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            if (!!this.privTranscriberRecognizer && userId.hasOwnProperty("id")) {
                // Assume this is a transcription participant
                Exports_2.marshalPromiseToCallbacks(this.removeParticipantImplAsync(userId), cb, err);
            }
            else {
                Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
                Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
                if (!this.canSendAsHost) {
                    this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "remove")), err);
                }
                var participantId_1 = "";
                if (typeof userId === "string") {
                    participantId_1 = userId;
                }
                else if (userId.hasOwnProperty("id")) {
                    var participant = userId;
                    participantId_1 = participant.id;
                }
                else if (userId.hasOwnProperty("userId")) {
                    var user = userId;
                    participantId_1 = user.userId;
                }
                Contracts_1.Contracts.throwIfNullOrWhitespace(participantId_1, this.privErrors.invalidArgs.replace("{arg}", "userId"));
                // check the participant exists
                var index = this.participants.findIndex(function (p) { return p.id === participantId_1; });
                if (index === -1) {
                    this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);
                }
                (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getEjectCommand(participantId_1), (function () {
                    _this.handleCallback(cb, err);
                }), (function (error) {
                    _this.handleError(error, err);
                }));
            }
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Issues a request to unlock the conversation
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.unlockConversationAsync = function (cb, err) {
        var _this = this;
        var _a;
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
            if (!this.canSendAsHost) {
                this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "unlock")), err);
            }
            (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getLockCommand(false), (function () {
                _this.handleCallback(cb, err);
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Issues a request to unmute all participants in the conversation
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.unmuteAllParticipantsAsync = function (cb, err) {
        var _this = this;
        var _a;
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
            if (!this.canSendAsHost) {
                this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "unmute all")), err);
            }
            (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getMuteAllCommand(false), (function () {
                _this.handleCallback(cb, err);
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Issues a request to unmute a participant in the conversation
     * @param userId
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.unmuteParticipantAsync = function (userId, cb, err) {
        var _this = this;
        var _a;
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
            Contracts_1.Contracts.throwIfNullOrWhitespace(userId, this.privErrors.invalidArgs.replace("{arg}", "userId"));
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
            // check the connection is open (host + participant can perform the mute command)
            if (!this.canSend) {
                this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
            }
            // if not host, check the participant is not muting another participant
            if (!this.me.isHost && this.me.id !== userId) {
                this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "mute")), err);
            }
            // check the user exists
            var exists = this.privParticipants.getParticipantIndex(userId);
            if (exists === -1) {
                this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);
            }
            (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getMuteCommand(userId, false), (function () {
                _this.handleCallback(cb, err);
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Send a text message
     * @param message
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.sendTextMessageAsync = function (message, cb, err) {
        var _this = this;
        var _a;
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
            Contracts_1.Contracts.throwIfNullOrWhitespace(message, this.privErrors.invalidArgs.replace("{arg}", "message"));
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
            if (!this.canSend) {
                this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
            }
            // TODO: is a max length check required?
            if (message.length > this.privTextMessageMaxLength) {
                this.handleError(new Error(this.privErrors.invalidArgs.replace("{arg}", "message length")), err);
            }
            (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getMessageCommand(message), (function () {
                _this.handleCallback(cb, err);
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Change nickname
     * @param message
     * @param cb
     * @param err
     */
    ConversationImpl.prototype.changeNicknameAsync = function (nickname, cb, err) {
        var _this = this;
        var _a;
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            Contracts_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
            Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname"));
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
            if (!this.canSend) {
                this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
            }
            (_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.sendRequest(this.getChangeNicknameCommand(nickname), (function () {
                _this.handleCallback(cb, err);
            }), (function (error) {
                _this.handleError(error, err);
            }));
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    ConversationImpl.prototype.isDisposed = function () {
        return this.privIsDisposed;
    };
    ConversationImpl.prototype.dispose = function (reason) {
        var _a;
        if (this.isDisposed) {
            return;
        }
        this.privIsDisposed = true;
        (_a = this.config) === null || _a === void 0 ? void 0 : _a.close();
        this.privConfig = undefined;
        this.privLanguage = undefined;
        this.privProperties = undefined;
        this.privRoom = undefined;
        this.privToken = undefined;
        this.privManager = undefined;
        this.privIsConnected = false;
        this.privIsReady = false;
        this.privParticipants = undefined;
    };
    Object.defineProperty(ConversationImpl.prototype, "transcriberRecognizer", {
        get: function () {
            return this.privTranscriberRecognizer;
        },
        enumerable: false,
        configurable: true
    });
    ConversationImpl.prototype.connectTranscriberRecognizer = function (recognizer) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!!this.privTranscriberRecognizer) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.privTranscriberRecognizer.close()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        this.privTranscriberRecognizer = recognizer;
                        this.privTranscriberRecognizer.conversation = this;
                        return [2 /*return*/];
                }
            });
        });
    };
    Object.defineProperty(ConversationImpl.prototype, "conversationInfo", {
        get: function () {
            var convId = this.conversationId;
            var p = this.participants.map(function (part) {
                return {
                    id: part.id,
                    preferredLanguage: part.preferredLanguage,
                    voice: part.voice
                };
            });
            var props = {};
            for (var _i = 0, _a = Exports_1.ConversationConnectionConfig.transcriptionEventKeys; _i < _a.length; _i++) {
                var key = _a[_i];
                var val = this.properties.getProperty(key, "");
                if (val !== "") {
                    props[key] = val;
                }
            }
            var info = { id: convId, participants: p, conversationProperties: props };
            return info;
        },
        enumerable: false,
        configurable: true
    });
    ConversationImpl.prototype.getKeepAlive = function () {
        var nickname = (!!this.me) ? this.me.displayName : "default_nickname";
        return JSON.stringify({
            // tslint:disable-next-line: object-literal-shorthand
            id: "0",
            nickname: nickname,
            participantId: this.privRoom.participantId,
            roomId: this.privRoom.roomId,
            type: Exports_1.ConversationTranslatorMessageTypes.keepAlive
        });
    };
    ConversationImpl.prototype.addParticipantImplAsync = function (participant) {
        var newParticipant = this.privParticipants.addOrUpdateParticipant(participant);
        if (newParticipant !== undefined) {
            if (!!this.privTranscriberRecognizer) {
                var conversationInfo = this.conversationInfo;
                conversationInfo.participants = [participant];
                return this.privTranscriberRecognizer.pushConversationEvent(conversationInfo, "join");
            }
        }
    };
    ConversationImpl.prototype.removeParticipantImplAsync = function (participant) {
        this.privParticipants.deleteParticipant(participant.id);
        var conversationInfo = this.conversationInfo;
        conversationInfo.participants = [participant];
        return this.privTranscriberRecognizer.pushConversationEvent(conversationInfo, "leave");
    };
    ConversationImpl.prototype.close = function (dispose) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function () {
            var e_2;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _c.trys.push([0, 2, , 3]);
                        this.privIsConnected = false;
                        return [4 /*yield*/, ((_a = this.privConversationRecognizer) === null || _a === void 0 ? void 0 : _a.close())];
                    case 1:
                        _c.sent();
                        this.privConversationRecognizer = undefined;
                        (_b = this.privConversationTranslator) === null || _b === void 0 ? void 0 : _b.dispose();
                        return [3 /*break*/, 3];
                    case 2:
                        e_2 = _c.sent();
                        // ignore error
                        throw e_2;
                    case 3:
                        if (dispose) {
                            this.dispose();
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    Object.defineProperty(ConversationImpl.prototype, "canSend", {
        /** Helpers */
        get: function () {
            var _a;
            return this.privIsConnected && !((_a = this.privParticipants.me) === null || _a === void 0 ? void 0 : _a.isMuted);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationImpl.prototype, "canSendAsHost", {
        get: function () {
            var _a;
            return this.privIsConnected && ((_a = this.privParticipants.me) === null || _a === void 0 ? void 0 : _a.isHost);
        },
        enumerable: false,
        configurable: true
    });
    ConversationImpl.prototype.handleCallback = function (cb, err) {
        if (!!cb) {
            try {
                cb();
            }
            catch (e) {
                if (!!err) {
                    err(e);
                }
            }
            cb = undefined;
        }
    };
    ConversationImpl.prototype.handleError = function (error, err) {
        if (!!err) {
            if (error instanceof Error) {
                var typedError = error;
                err(typedError.name + ": " + typedError.message);
            }
            else {
                err(error);
            }
        }
    };
    /** Participant Helpers */
    ConversationImpl.prototype.toParticipants = function (includeHost) {
        var _this = this;
        var participants = this.privParticipants.participants.map(function (p) {
            return _this.toParticipant(p);
        });
        if (!includeHost) {
            return participants.filter(function (p) { return p.isHost === false; });
        }
        else {
            return participants;
        }
    };
    ConversationImpl.prototype.toParticipant = function (p) {
        return new Exports_3.Participant(p.id, p.avatar, p.displayName, p.isHost, p.isMuted, p.isUsingTts, p.preferredLanguage, p.voice);
    };
    ConversationImpl.prototype.getMuteAllCommand = function (isMuted) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
        return JSON.stringify({
            command: Exports_1.ConversationTranslatorCommandTypes.setMuteAll,
            // tslint:disable-next-line: object-literal-shorthand
            participantId: this.privRoom.participantId,
            roomid: this.privRoom.roomId,
            type: Exports_1.ConversationTranslatorMessageTypes.participantCommand,
            value: isMuted
        });
    };
    ConversationImpl.prototype.getMuteCommand = function (participantId, isMuted) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(participantId, "participantId");
        return JSON.stringify({
            command: Exports_1.ConversationTranslatorCommandTypes.setMute,
            // tslint:disable-next-line: object-literal-shorthand
            participantId: participantId,
            roomid: this.privRoom.roomId,
            type: Exports_1.ConversationTranslatorMessageTypes.participantCommand,
            value: isMuted
        });
    };
    ConversationImpl.prototype.getLockCommand = function (isLocked) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
        return JSON.stringify({
            command: Exports_1.ConversationTranslatorCommandTypes.setLockState,
            // tslint:disable-next-line: object-literal-shorthand
            participantId: this.privRoom.participantId,
            roomid: this.privRoom.roomId,
            type: Exports_1.ConversationTranslatorMessageTypes.participantCommand,
            value: isLocked
        });
    };
    ConversationImpl.prototype.getEjectCommand = function (participantId) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(participantId, "participantId");
        return JSON.stringify({
            command: Exports_1.ConversationTranslatorCommandTypes.ejectParticipant,
            // tslint:disable-next-line: object-literal-shorthand
            participantId: participantId,
            roomid: this.privRoom.roomId,
            type: Exports_1.ConversationTranslatorMessageTypes.participantCommand,
        });
    };
    ConversationImpl.prototype.getChangeNicknameCommand = function (nickname) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, "nickname");
        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
        return JSON.stringify({
            command: Exports_1.ConversationTranslatorCommandTypes.changeNickname,
            nickname: nickname,
            // tslint:disable-next-line: object-literal-shorthand
            participantId: this.privRoom.participantId,
            roomid: this.privRoom.roomId,
            type: Exports_1.ConversationTranslatorMessageTypes.participantCommand,
            value: nickname
        });
    };
    ConversationImpl.prototype.getMessageCommand = function (message) {
        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
        Contracts_1.Contracts.throwIfNullOrWhitespace(message, "message");
        return JSON.stringify({
            // tslint:disable-next-line: object-literal-shorthand
            participantId: this.privRoom.participantId,
            roomId: this.privRoom.roomId,
            text: message,
            type: Exports_1.ConversationTranslatorMessageTypes.instantMessage
        });
    };
    return ConversationImpl;
}(Conversation));
exports.ConversationImpl = ConversationImpl;



/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationCommon = void 0;
var ConversationCommon = /** @class */ (function () {
    function ConversationCommon(audioConfig) {
        this.privAudioConfig = audioConfig;
    }
    ConversationCommon.prototype.handleCallback = function (cb, err) {
        if (!!cb) {
            try {
                cb();
            }
            catch (e) {
                if (!!err) {
                    err(e);
                }
            }
            cb = undefined;
        }
    };
    ConversationCommon.prototype.handleError = function (error, err) {
        if (!!err) {
            if (error instanceof Error) {
                var typedError = error;
                err(typedError.name + ": " + typedError.message);
            }
            else {
                err(error);
            }
        }
    };
    return ConversationCommon;
}());
exports.ConversationCommon = ConversationCommon;



/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Multi-device Conversation is a Preview feature.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationExpirationEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
var ConversationExpirationEventArgs = /** @class */ (function (_super) {
    __extends(ConversationExpirationEventArgs, _super);
    function ConversationExpirationEventArgs(expirationTime, sessionId) {
        var _this = _super.call(this, sessionId) || this;
        _this.privExpirationTime = expirationTime;
        return _this;
    }
    Object.defineProperty(ConversationExpirationEventArgs.prototype, "expirationTime", {
        /** How much longer until the conversation expires (in minutes). */
        get: function () {
            return this.privExpirationTime;
        },
        enumerable: false,
        configurable: true
    });
    return ConversationExpirationEventArgs;
}(Exports_1.SessionEventArgs));
exports.ConversationExpirationEventArgs = ConversationExpirationEventArgs;



/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Multi-device Conversation is a Preview feature.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationParticipantsChangedEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
var ConversationParticipantsChangedEventArgs = /** @class */ (function (_super) {
    __extends(ConversationParticipantsChangedEventArgs, _super);
    function ConversationParticipantsChangedEventArgs(reason, participants, sessionId) {
        var _this = _super.call(this, sessionId) || this;
        _this.privReason = reason;
        _this.privParticipant = participants;
        return _this;
    }
    Object.defineProperty(ConversationParticipantsChangedEventArgs.prototype, "reason", {
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationParticipantsChangedEventArgs.prototype, "participants", {
        get: function () {
            return this.privParticipant;
        },
        enumerable: false,
        configurable: true
    });
    return ConversationParticipantsChangedEventArgs;
}(Exports_1.SessionEventArgs));
exports.ConversationParticipantsChangedEventArgs = ConversationParticipantsChangedEventArgs;



/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Multi-device Conversation is a Preview feature.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslationCanceledEventArgs = void 0;
var CancellationEventArgsBase_1 = __webpack_require__(90);
var ConversationTranslationCanceledEventArgs = /** @class */ (function (_super) {
    __extends(ConversationTranslationCanceledEventArgs, _super);
    function ConversationTranslationCanceledEventArgs() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ConversationTranslationCanceledEventArgs;
}(CancellationEventArgsBase_1.CancellationEventArgsBase));
exports.ConversationTranslationCanceledEventArgs = ConversationTranslationCanceledEventArgs;



/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Multi-device Conversation is a Preview feature.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslationEventArgs = void 0;
var Exports_1 = __webpack_require__(61);
var ConversationTranslationEventArgs = /** @class */ (function (_super) {
    __extends(ConversationTranslationEventArgs, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {ConversationTranslationResult} result - The translation recognition result.
     * @param {number} offset - The offset.
     * @param {string} sessionId - The session id.
     */
    function ConversationTranslationEventArgs(result, offset, sessionId) {
        var _this = _super.call(this, offset, sessionId) || this;
        _this.privResult = result;
        return _this;
    }
    Object.defineProperty(ConversationTranslationEventArgs.prototype, "result", {
        /**
         * Specifies the recognition result.
         * @returns {ConversationTranslationResult} the recognition result.
         */
        get: function () {
            return this.privResult;
        },
        enumerable: false,
        configurable: true
    });
    return ConversationTranslationEventArgs;
}(Exports_1.RecognitionEventArgs));
exports.ConversationTranslationEventArgs = ConversationTranslationEventArgs;



/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Multi-device Conversation is a Preview feature.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslationResult = void 0;
var TranslationRecognitionResult_1 = __webpack_require__(93);
var ConversationTranslationResult = /** @class */ (function (_super) {
    __extends(ConversationTranslationResult, _super);
    function ConversationTranslationResult(participantId, translations, originalLanguage, resultId, reason, text, duration, offset, errorDetails, json, properties) {
        var _this = _super.call(this, translations, resultId, reason, text, duration, offset, errorDetails, json, properties) || this;
        _this.privId = participantId;
        _this.privOrigLang = originalLanguage;
        return _this;
    }
    Object.defineProperty(ConversationTranslationResult.prototype, "participantId", {
        /**
         * The unique identifier for the participant this result is for.
         */
        get: function () {
            return this.privId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationTranslationResult.prototype, "originalLang", {
        /**
         * The original language this result was in.
         */
        get: function () {
            return this.privOrigLang;
        },
        enumerable: false,
        configurable: true
    });
    return ConversationTranslationResult;
}(TranslationRecognitionResult_1.TranslationRecognitionResult));
exports.ConversationTranslationResult = ConversationTranslationResult;



/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Multi-device Conversation is a Preview feature.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslator = exports.SpeechState = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
var Conversation_1 = __webpack_require__(145);
var Exports_4 = __webpack_require__(144);
var SpeechState;
(function (SpeechState) {
    SpeechState[SpeechState["Inactive"] = 0] = "Inactive";
    SpeechState[SpeechState["Connecting"] = 1] = "Connecting";
    SpeechState[SpeechState["Connected"] = 2] = "Connected";
})(SpeechState = exports.SpeechState || (exports.SpeechState = {}));
// tslint:disable:max-classes-per-file
// child class of TranslationRecognizer meant only for use with ConversationTranslator
var ConversationTranslationRecognizer = /** @class */ (function (_super) {
    __extends(ConversationTranslationRecognizer, _super);
    function ConversationTranslationRecognizer(speechConfig, audioConfig, translator) {
        var _this = _super.call(this, speechConfig, audioConfig) || this;
        _this.privSpeechState = SpeechState.Inactive;
        if (!!translator) {
            _this.privTranslator = translator;
            _this.sessionStarted = function () {
                _this.privSpeechState = SpeechState.Connected;
            };
            _this.sessionStopped = function () {
                _this.privSpeechState = SpeechState.Inactive;
            };
            _this.recognized = function (tr, e) { return __awaiter(_this, void 0, void 0, function () {
                var _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (!((_a = e.result) === null || _a === void 0 ? void 0 : _a.errorDetails)) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.cancelSpeech()];
                        case 1:
                            _b.sent();
                            // TODO: format the error message contained in 'errorDetails'
                            this.fireCancelEvent(e.result.errorDetails);
                            _b.label = 2;
                        case 2: return [2 /*return*/];
                    }
                });
            }); };
            _this.canceled = function (r, e) { return __awaiter(_this, void 0, void 0, function () {
                var error_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!(this.privSpeechState !== SpeechState.Inactive)) return [3 /*break*/, 4];
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 3, , 4]);
                            return [4 /*yield*/, this.cancelSpeech()];
                        case 2:
                            _a.sent();
                            return [3 /*break*/, 4];
                        case 3:
                            error_1 = _a.sent();
                            this.privSpeechState = SpeechState.Inactive;
                            return [3 /*break*/, 4];
                        case 4: return [2 /*return*/];
                    }
                });
            }); };
        }
        return _this;
    }
    Object.defineProperty(ConversationTranslationRecognizer.prototype, "state", {
        get: function () {
            return this.privSpeechState;
        },
        set: function (newState) {
            this.privSpeechState = newState;
        },
        enumerable: false,
        configurable: true
    });
    ConversationTranslationRecognizer.prototype.onConnection = function () {
        this.privSpeechState = SpeechState.Connected;
    };
    ConversationTranslationRecognizer.prototype.onDisconnection = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.privSpeechState = SpeechState.Inactive;
                        return [4 /*yield*/, this.cancelSpeech()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Fire a cancel event
     * @param error
     */
    ConversationTranslationRecognizer.prototype.fireCancelEvent = function (error) {
        var _a, _b, _c;
        try {
            if (!!this.privTranslator.canceled) {
                var cancelEvent = new Exports_4.ConversationTranslationCanceledEventArgs((_a = error === null || error === void 0 ? void 0 : error.reason) !== null && _a !== void 0 ? _a : Exports_3.CancellationReason.Error, (_b = error === null || error === void 0 ? void 0 : error.errorDetails) !== null && _b !== void 0 ? _b : error, (_c = error === null || error === void 0 ? void 0 : error.errorCode) !== null && _c !== void 0 ? _c : Exports_3.CancellationErrorCode.RuntimeError, undefined, error === null || error === void 0 ? void 0 : error.sessionId);
                this.privTranslator.canceled(this.privTranslator, cancelEvent);
            }
        }
        catch (e) {
            //
        }
    };
    ConversationTranslationRecognizer.prototype.cancelSpeech = function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var e_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 2, , 3]);
                        this.stopContinuousRecognitionAsync();
                        return [4 /*yield*/, ((_a = this.privReco) === null || _a === void 0 ? void 0 : _a.disconnect())];
                    case 1:
                        _b.sent();
                        this.privSpeechState = SpeechState.Inactive;
                        return [3 /*break*/, 3];
                    case 2:
                        e_1 = _b.sent();
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    return ConversationTranslationRecognizer;
}(Exports_3.TranslationRecognizer));
/***
 * Join, leave or connect to a conversation.
 */
var ConversationTranslator = /** @class */ (function (_super) {
    __extends(ConversationTranslator, _super);
    function ConversationTranslator(audioConfig) {
        var _this = _super.call(this, audioConfig) || this;
        _this.privIsDisposed = false;
        _this.privIsSpeaking = false;
        _this.privErrors = Exports_1.ConversationConnectionConfig.restErrors;
        _this.privPlaceholderKey = "abcdefghijklmnopqrstuvwxyz012345";
        _this.privPlaceholderRegion = "westus";
        _this.privProperties = new Exports_3.PropertyCollection();
        return _this;
    }
    Object.defineProperty(ConversationTranslator.prototype, "properties", {
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationTranslator.prototype, "speechRecognitionLanguage", {
        get: function () {
            return this.privSpeechRecognitionLanguage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationTranslator.prototype, "participants", {
        get: function () {
            var _a;
            return (_a = this.privConversation) === null || _a === void 0 ? void 0 : _a.participants;
        },
        enumerable: false,
        configurable: true
    });
    ConversationTranslator.prototype.joinConversationAsync = function (conversation, nickname, param1, param2, param3) {
        var _this = this;
        try {
            if (typeof conversation === "string") {
                Contracts_1.Contracts.throwIfNullOrUndefined(conversation, this.privErrors.invalidArgs.replace("{arg}", "conversation id"));
                Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname"));
                if (!!this.privConversation) {
                    this.handleError(new Error(this.privErrors.permissionDeniedStart), param3);
                }
                var lang = param1;
                if (lang === undefined || lang === null || lang === "") {
                    lang = Exports_1.ConversationConnectionConfig.defaultLanguageCode;
                }
                // create a placeholder config
                this.privSpeechTranslationConfig = Exports_3.SpeechTranslationConfig.fromSubscription(this.privPlaceholderKey, this.privPlaceholderRegion);
                this.privSpeechTranslationConfig.setProfanity(Exports_3.ProfanityOption.Masked);
                this.privSpeechTranslationConfig.addTargetLanguage(lang);
                this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage], lang);
                this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.ConversationTranslator_Name], nickname);
                var endpoint = this.privProperties.getProperty(Exports_3.PropertyId.ConversationTranslator_Host);
                if (endpoint) {
                    this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.ConversationTranslator_Host], endpoint);
                }
                var speechEndpointHost = this.privProperties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Host);
                if (speechEndpointHost) {
                    this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Host], speechEndpointHost);
                }
                // join the conversation
                this.privConversation = new Conversation_1.ConversationImpl(this.privSpeechTranslationConfig);
                this.privConversation.conversationTranslator = this;
                this.privConversation.joinConversationAsync(conversation, nickname, lang, (function (result) {
                    if (!result) {
                        _this.handleError(new Error(_this.privErrors.permissionDeniedConnect), param3);
                    }
                    _this.privSpeechTranslationConfig.authorizationToken = result;
                    // connect to the ws
                    _this.privConversation.startConversationAsync((function () {
                        _this.handleCallback(param2, param3);
                    }), (function (error) {
                        _this.handleError(error, param3);
                    }));
                }), (function (error) {
                    _this.handleError(error, param3);
                }));
            }
            else if (typeof conversation === "object") {
                Contracts_1.Contracts.throwIfNullOrUndefined(conversation, this.privErrors.invalidArgs.replace("{arg}", "conversation id"));
                Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname"));
                // save the nickname
                this.privProperties.setProperty(Exports_3.PropertyId.ConversationTranslator_Name, nickname);
                // ref the conversation object
                this.privConversation = conversation;
                // ref the conversation translator object
                this.privConversation.conversationTranslator = this;
                Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedConnect);
                Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation.room.token, this.privErrors.permissionDeniedConnect);
                this.privSpeechTranslationConfig = conversation.config;
                this.handleCallback(param1, param2);
            }
            else {
                this.handleError(new Error(this.privErrors.invalidArgs.replace("{arg}", "invalid conversation type")), param2);
            }
        }
        catch (error) {
            this.handleError(error, typeof param1 === "string" ? param3 : param2);
        }
    };
    /**
     * Leave the conversation
     * @param cb
     * @param err
     */
    ConversationTranslator.prototype.leaveConversationAsync = function (cb, err) {
        var _this = this;
        Exports_2.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: 
                    // stop the speech websocket
                    return [4 /*yield*/, this.cancelSpeech()];
                    case 1:
                        // stop the speech websocket
                        _a.sent();
                        // stop the websocket
                        return [4 /*yield*/, this.privConversation.endConversationImplAsync()];
                    case 2:
                        // stop the websocket
                        _a.sent();
                        // https delete request
                        return [4 /*yield*/, this.privConversation.deleteConversationImplAsync()];
                    case 3:
                        // https delete request
                        _a.sent();
                        this.dispose();
                        return [2 /*return*/];
                }
            });
        }); })(), cb, err);
    };
    /**
     * Send a text message
     * @param message
     * @param cb
     * @param err
     */
    ConversationTranslator.prototype.sendTextMessageAsync = function (message, cb, err) {
        var _a;
        try {
            Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedSend);
            Contracts_1.Contracts.throwIfNullOrWhitespace(message, this.privErrors.invalidArgs.replace("{arg}", message));
            (_a = this.privConversation) === null || _a === void 0 ? void 0 : _a.sendTextMessageAsync(message, cb, err);
        }
        catch (error) {
            this.handleError(error, err);
        }
    };
    /**
     * Start speaking
     * @param cb
     * @param err
     */
    ConversationTranslator.prototype.startTranscribingAsync = function (cb, err) {
        var _this = this;
        Exports_2.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () {
            var error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 4, , 6]);
                        Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedSend);
                        Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation.room.token, this.privErrors.permissionDeniedConnect);
                        if (!(this.privCTRecognizer === undefined)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.connectTranslatorRecognizer()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        Contracts_1.Contracts.throwIfNullOrUndefined(this.privCTRecognizer, this.privErrors.permissionDeniedSend);
                        if (!this.canSpeak) {
                            this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
                        }
                        return [4 /*yield*/, this.startContinuousRecognition()];
                    case 3:
                        _a.sent();
                        this.privIsSpeaking = true;
                        return [3 /*break*/, 6];
                    case 4:
                        error_2 = _a.sent();
                        this.privIsSpeaking = false;
                        return [4 /*yield*/, this.cancelSpeech()];
                    case 5:
                        _a.sent();
                        throw error_2;
                    case 6: return [2 /*return*/];
                }
            });
        }); })(), cb, err);
    };
    /**
     * Stop speaking
     * @param cb
     * @param err
     */
    ConversationTranslator.prototype.stopTranscribingAsync = function (cb, err) {
        var _this = this;
        Exports_2.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () {
            var error_3;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 4, , 6]);
                        if (!!this.privIsSpeaking) return [3 /*break*/, 2];
                        // stop speech
                        return [4 /*yield*/, this.cancelSpeech()];
                    case 1:
                        // stop speech
                        _a.sent();
                        return [2 /*return*/];
                    case 2:
                        // stop the recognition but leave the websocket open
                        this.privIsSpeaking = false;
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                var _a;
                                (_a = _this.privCTRecognizer) === null || _a === void 0 ? void 0 : _a.stopContinuousRecognitionAsync(resolve, reject);
                            })];
                    case 3:
                        _a.sent();
                        return [3 /*break*/, 6];
                    case 4:
                        error_3 = _a.sent();
                        return [4 /*yield*/, this.cancelSpeech()];
                    case 5:
                        _a.sent();
                        return [3 /*break*/, 6];
                    case 6: return [2 /*return*/];
                }
            });
        }); })(), cb, err);
    };
    ConversationTranslator.prototype.isDisposed = function () {
        return this.privIsDisposed;
    };
    ConversationTranslator.prototype.dispose = function (reason, success, err) {
        var _this = this;
        Exports_2.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () {
            var _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (this.isDisposed && !this.privIsSpeaking) {
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, this.cancelSpeech()];
                    case 1:
                        _c.sent();
                        this.privIsDisposed = true;
                        (_a = this.privSpeechTranslationConfig) === null || _a === void 0 ? void 0 : _a.close();
                        this.privSpeechRecognitionLanguage = undefined;
                        this.privProperties = undefined;
                        this.privAudioConfig = undefined;
                        this.privSpeechTranslationConfig = undefined;
                        (_b = this.privConversation) === null || _b === void 0 ? void 0 : _b.dispose();
                        this.privConversation = undefined;
                        return [2 /*return*/];
                }
            });
        }); })(), success, err);
    };
    /**
     * Cancel the speech websocket
     */
    ConversationTranslator.prototype.cancelSpeech = function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var e_2;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 2, , 3]);
                        this.privIsSpeaking = false;
                        return [4 /*yield*/, ((_a = this.privCTRecognizer) === null || _a === void 0 ? void 0 : _a.onDisconnection())];
                    case 1:
                        _b.sent();
                        this.privCTRecognizer = undefined;
                        return [3 /*break*/, 3];
                    case 2:
                        e_2 = _b.sent();
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Connect to the speech translation recognizer.
     * Currently there is no language validation performed before sending the SpeechLanguage code to the service.
     * If it's an invalid language the raw error will be: 'Error during WebSocket handshake: Unexpected response code: 400'
     * e.g. pass in 'fr' instead of 'fr-FR', or a text-only language 'cy'
     */
    ConversationTranslator.prototype.connectTranslatorRecognizer = function () {
        return __awaiter(this, void 0, void 0, function () {
            var token, endpointHost, url, error_4;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 1, , 3]);
                        if (this.privAudioConfig === undefined) {
                            this.privAudioConfig = Exports_3.AudioConfig.fromDefaultMicrophoneInput();
                        }
                        // clear the temp subscription key if it's a participant joining
                        if (this.privSpeechTranslationConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Key])
                            === this.privPlaceholderKey) {
                            this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Key], "");
                        }
                        token = encodeURIComponent(this.privConversation.room.token);
                        endpointHost = this.privSpeechTranslationConfig.getProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Host], Exports_1.ConversationConnectionConfig.speechHost);
                        endpointHost = endpointHost.replace("{region}", this.privConversation.room.cognitiveSpeechRegion);
                        url = "wss://" + endpointHost + Exports_1.ConversationConnectionConfig.speechPath + "?" + Exports_1.ConversationConnectionConfig.configParams.token + "=" + token;
                        this.privSpeechTranslationConfig.setProperty(Exports_3.PropertyId[Exports_3.PropertyId.SpeechServiceConnection_Endpoint], url);
                        this.privCTRecognizer = new ConversationTranslationRecognizer(this.privSpeechTranslationConfig, this.privAudioConfig, this);
                        return [3 /*break*/, 3];
                    case 1:
                        error_4 = _a.sent();
                        return [4 /*yield*/, this.cancelSpeech()];
                    case 2:
                        _a.sent();
                        throw error_4;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Handle the start speaking request
     */
    ConversationTranslator.prototype.startContinuousRecognition = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this.privCTRecognizer.startContinuousRecognitionAsync(resolve, reject);
        });
    };
    Object.defineProperty(ConversationTranslator.prototype, "canSpeak", {
        get: function () {
            // is there a Conversation websocket available and has the Recognizer been set up
            if (!this.privConversation.isConnected || !this.privCTRecognizer) {
                return false;
            }
            // is the user already speaking
            if (this.privIsSpeaking || this.privCTRecognizer.state === SpeechState.Connected || this.privCTRecognizer.state === SpeechState.Connecting) {
                return false;
            }
            // is the user muted
            if (this.privConversation.isMutedByHost) {
                return false;
            }
            return true;
        },
        enumerable: false,
        configurable: true
    });
    return ConversationTranslator;
}(Exports_4.ConversationCommon));
exports.ConversationTranslator = ConversationTranslator;



/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranscriber = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
var ConversationTranscriber = /** @class */ (function () {
    /**
     * ConversationTranscriber constructor.
     * @constructor
     * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer
     */
    function ConversationTranscriber(audioConfig) {
        this.privAudioConfig = audioConfig;
        this.privProperties = new Exports_3.PropertyCollection();
        this.privRecognizer = undefined;
        this.privDisposedRecognizer = false;
    }
    /**
     * @param {Conversation} converation - conversation to be recognized
     */
    ConversationTranscriber.prototype.joinConversationAsync = function (conversation, cb, err) {
        var conversationImpl = conversation;
        Contracts_1.Contracts.throwIfNullOrUndefined(conversationImpl, "Conversation");
        // ref the conversation object
        // create recognizer and subscribe to recognizer events
        this.privRecognizer = new Exports_1.TranscriberRecognizer(conversation.config, this.privAudioConfig);
        Contracts_1.Contracts.throwIfNullOrUndefined(this.privRecognizer, "Recognizer");
        this.privRecognizer.connectCallbacks(this);
        Exports_2.marshalPromiseToCallbacks(conversationImpl.connectTranscriberRecognizer(this.privRecognizer), cb, err);
    };
    Object.defineProperty(ConversationTranscriber.prototype, "authorizationToken", {
        /**
         * Gets the authorization token used to communicate with the service.
         * @member ConversationTranscriber.prototype.authorizationToken
         * @function
         * @public
         * @returns {string} Authorization token.
         */
        get: function () {
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token);
        },
        /**
         * Gets/Sets the authorization token used to communicate with the service.
         * @member ConversationTranscriber.prototype.authorizationToken
         * @function
         * @public
         * @param {string} token - Authorization token.
         */
        set: function (token) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token");
            this.properties.setProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, token);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationTranscriber.prototype, "speechRecognitionLanguage", {
        /**
         * Gets the spoken language of recognition.
         * @member ConversationTranscriber.prototype.speechRecognitionLanguage
         * @function
         * @public
         * @returns {string} The spoken language of recognition.
         */
        get: function () {
            Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationTranscriber.prototype, "properties", {
        /**
         * The collection of properties and their values defined for this ConversationTranscriber.
         * @member ConversationTranscriber.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The collection of properties and their values defined for this ConversationTranscriber.
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * Starts conversation transcription, until stopTranscribingAsync() is called.
     * User must subscribe to events to receive transcription results.
     * @member ConversationTranscriber.prototype.startTranscribingAsync
     * @function
     * @public
     * @param cb - Callback invoked once the transcription has started.
     * @param err - Callback invoked in case of an error.
     */
    ConversationTranscriber.prototype.startTranscribingAsync = function (cb, err) {
        this.privRecognizer.startContinuousRecognitionAsync(cb, err);
    };
    /**
     * Starts conversation transcription, until stopTranscribingAsync() is called.
     * User must subscribe to events to receive transcription results.
     * @member ConversationTranscriber.prototype.stopTranscribingAsync
     * @function
     * @public
     * @param cb - Callback invoked once the transcription has started.
     * @param err - Callback invoked in case of an error.
     */
    ConversationTranscriber.prototype.stopTranscribingAsync = function (cb, err) {
        this.privRecognizer.stopContinuousRecognitionAsync(cb, err);
    };
    /**
     * Leave the current conversation. After this is called, you will no longer receive any events.
     */
    ConversationTranscriber.prototype.leaveConversationAsync = function (cb, err) {
        var _this = this;
        this.privRecognizer.disconnectCallbacks();
        Exports_2.marshalPromiseToCallbacks((function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
            return [2 /*return*/];
        }); }); })(), cb, err);
    };
    /**
     * closes all external resources held by an instance of this class.
     * @member ConversationTranscriber.prototype.close
     * @function
     * @public
     */
    ConversationTranscriber.prototype.close = function (cb, errorCb) {
        Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
        Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, errorCb);
    };
    /**
     * Disposes any resources held by the object.
     * @member ConversationTranscriber.prototype.dispose
     * @function
     * @public
     * @param {boolean} disposing - true if disposing the object.
     */
    ConversationTranscriber.prototype.dispose = function (disposing) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privDisposedRecognizer) {
                            return [2 /*return*/];
                        }
                        if (!!!this.privRecognizer) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.privRecognizer.close()];
                    case 1:
                        _a.sent();
                        this.privRecognizer = undefined;
                        _a.label = 2;
                    case 2:
                        if (disposing) {
                            this.privDisposedRecognizer = true;
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    return ConversationTranscriber;
}());
exports.ConversationTranscriber = ConversationTranscriber;



/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Multi-device Conversation is a Preview feature.
Object.defineProperty(exports, "__esModule", { value: true });
exports.Participant = exports.User = void 0;
var Exports_1 = __webpack_require__(61);
var User = /** @class */ (function () {
    function User(userId) {
        this.privUserId = userId;
    }
    Object.defineProperty(User.prototype, "userId", {
        get: function () {
            return this.privUserId;
        },
        enumerable: false,
        configurable: true
    });
    return User;
}());
exports.User = User;
// tslint:disable-next-line: max-classes-per-file
var Participant = /** @class */ (function () {
    function Participant(id, avatar, displayName, isHost, isMuted, isUsingTts, preferredLanguage, voice) {
        this.privId = id;
        this.privAvatar = avatar;
        this.privDisplayName = displayName;
        this.privIsHost = isHost;
        this.privIsMuted = isMuted;
        this.privIsUsingTts = isUsingTts;
        this.privPreferredLanguage = preferredLanguage;
        this.privVoice = voice;
        this.privProperties = new Exports_1.PropertyCollection();
    }
    Participant.From = function (id, language, voice) {
        return new Participant(id, "", id, false, false, false, language, voice);
    };
    Object.defineProperty(Participant.prototype, "avatar", {
        get: function () {
            return this.privAvatar;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Participant.prototype, "displayName", {
        get: function () {
            return this.privDisplayName;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Participant.prototype, "id", {
        get: function () {
            return this.privId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Participant.prototype, "preferredLanguage", {
        get: function () {
            return this.privPreferredLanguage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Participant.prototype, "isHost", {
        get: function () {
            return this.privIsHost;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Participant.prototype, "isMuted", {
        get: function () {
            return this.privIsMuted;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Participant.prototype, "isUsingTts", {
        get: function () {
            return this.privIsUsingTts;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Participant.prototype, "voice", {
        get: function () {
            return this.privVoice;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Participant.prototype, "properties", {
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    return Participant;
}());
exports.Participant = Participant;



/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// Multi-device Conversation is a Preview feature.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParticipantChangedReason = void 0;
var ParticipantChangedReason;
(function (ParticipantChangedReason) {
    /** Participant has joined the conversation. */
    ParticipantChangedReason[ParticipantChangedReason["JoinedConversation"] = 0] = "JoinedConversation";
    /** Participant has left the conversation. This could be voluntary, or involuntary
     *  (e.g. they are experiencing networking issues).
     */
    ParticipantChangedReason[ParticipantChangedReason["LeftConversation"] = 1] = "LeftConversation";
    /** The participants' state has changed (e.g. they became muted, changed their nickname). */
    ParticipantChangedReason[ParticipantChangedReason["Updated"] = 2] = "Updated";
})(ParticipantChangedReason = exports.ParticipantChangedReason || (exports.ParticipantChangedReason = {}));



/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisRequest = exports.SpeechSynthesizer = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var AudioFileWriter_1 = __webpack_require__(64);
var AudioOutputFormat_1 = __webpack_require__(74);
var AudioOutputStream_1 = __webpack_require__(73);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
/**
 * Defines the class SpeechSynthesizer for text to speech.
 * Updated in version 1.16.0
 * @class SpeechSynthesizer
 */
var SpeechSynthesizer = /** @class */ (function () {
    /**
     * SpeechSynthesizer constructor.
     * @constructor
     * @param {SpeechConfig} speechConfig - An set of initial properties for this synthesizer.
     * @param {AudioConfig} audioConfig - An optional audio configuration associated with the synthesizer.
     */
    function SpeechSynthesizer(speechConfig, audioConfig) {
        var speechConfigImpl = speechConfig;
        Contracts_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig");
        if (audioConfig !== null) {
            if (audioConfig === undefined) {
                this.audioConfig = (typeof window === "undefined") ? undefined : Exports_3.AudioConfig.fromDefaultSpeakerOutput();
            }
            else {
                this.audioConfig = audioConfig;
            }
        }
        this.privProperties = speechConfigImpl.properties.clone();
        this.privDisposed = false;
        this.privSynthesizing = false;
        this.privConnectionFactory = new Exports_1.SpeechSynthesisConnectionFactory();
        this.synthesisRequestQueue = new Exports_2.Queue();
        this.implCommonSynthesizeSetup();
    }
    Object.defineProperty(SpeechSynthesizer.prototype, "authorizationToken", {
        /**
         * Gets the authorization token used to communicate with the service.
         * @member SpeechSynthesizer.prototype.authorizationToken
         * @function
         * @public
         * @returns {string} Authorization token.
         */
        get: function () {
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token);
        },
        /**
         * Gets/Sets the authorization token used to communicate with the service.
         * @member SpeechSynthesizer.prototype.authorizationToken
         * @function
         * @public
         * @param {string} token - Authorization token.
         */
        set: function (token) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token");
            this.properties.setProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, token);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechSynthesizer.prototype, "properties", {
        /**
         * The collection of properties and their values defined for this SpeechSynthesizer.
         * @member SpeechSynthesizer.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The collection of properties and their values defined for this SpeechSynthesizer.
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechSynthesizer.prototype, "autoDetectSourceLanguage", {
        /**
         * Indicates if auto detect source language is enabled
         * @member SpeechSynthesizer.prototype.properties
         * @function
         * @public
         * @returns {boolean} if auto detect source language is enabled
         */
        get: function () {
            return this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages) === Exports_1.AutoDetectSourceLanguagesOpenRangeOptionName;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * SpeechSynthesizer constructor.
     * @constructor
     * @param {SpeechConfig} speechConfig - an set of initial properties for this synthesizer
     * @param {AutoDetectSourceLanguageConfig} autoDetectSourceLanguageConfig - An source language detection configuration associated with the synthesizer
     * @param {AudioConfig} audioConfig - An optional audio configuration associated with the synthesizer
     */
    SpeechSynthesizer.FromConfig = function (speechConfig, autoDetectSourceLanguageConfig, audioConfig) {
        var speechConfigImpl = speechConfig;
        autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties);
        return new SpeechSynthesizer(speechConfig, audioConfig);
    };
    SpeechSynthesizer.prototype.buildSsml = function (text) {
        var _a;
        var languageToDefaultVoice = (_a = {},
            _a["af-ZA"] = "af-ZA-AdriNeural",
            _a["am-ET"] = "am-ET-AmehaNeural",
            _a["ar-AE"] = "ar-AE-FatimaNeural",
            _a["ar-BH"] = "ar-BH-AliNeural",
            _a["ar-DZ"] = "ar-DZ-AminaNeural",
            _a["ar-EG"] = "ar-EG-SalmaNeural",
            _a["ar-IQ"] = "ar-IQ-BasselNeural",
            _a["ar-JO"] = "ar-JO-SanaNeural",
            _a["ar-KW"] = "ar-KW-FahedNeural",
            _a["ar-LY"] = "ar-LY-ImanNeural",
            _a["ar-MA"] = "ar-MA-JamalNeural",
            _a["ar-QA"] = "ar-QA-AmalNeural",
            _a["ar-SA"] = "ar-SA-HamedNeural",
            _a["ar-SY"] = "ar-SY-AmanyNeural",
            _a["ar-TN"] = "ar-TN-HediNeural",
            _a["ar-YE"] = "ar-YE-MaryamNeural",
            _a["bg-BG"] = "bg-BG-BorislavNeural",
            _a["bn-BD"] = "bn-BD-NabanitaNeural",
            _a["ca-ES"] = "ca-ES-JoanaNeural",
            _a["cs-CZ"] = "cs-CZ-AntoninNeural",
            _a["cy-GB"] = "cy-GB-AledNeural",
            _a["da-DK"] = "da-DK-ChristelNeural",
            _a["de-AT"] = "de-AT-IngridNeural",
            _a["de-CH"] = "de-CH-JanNeural",
            _a["de-DE"] = "de-DE-KatjaNeural",
            _a["el-GR"] = "el-GR-AthinaNeural",
            _a["en-AU"] = "en-AU-NatashaNeural",
            _a["en-CA"] = "en-CA-ClaraNeural",
            _a["en-GB"] = "en-GB-LibbyNeural",
            _a["en-HK"] = "en-HK-SamNeural",
            _a["en-IE"] = "en-IE-ConnorNeural",
            _a["en-IN"] = "en-IN-NeerjaNeural",
            _a["en-KE"] = "en-KE-AsiliaNeural",
            _a["en-NG"] = "en-NG-AbeoNeural",
            _a["en-NZ"] = "en-NZ-MitchellNeural",
            _a["en-PH"] = "en-PH-JamesNeural",
            _a["en-SG"] = "en-SG-LunaNeural",
            _a["en-TZ"] = "en-TZ-ElimuNeural",
            _a["en-US"] = "en-US-JennyNeural",
            _a["en-ZA"] = "en-ZA-LeahNeural",
            _a["es-AR"] = "es-AR-ElenaNeural",
            _a["es-BO"] = "es-BO-MarceloNeural",
            _a["es-CL"] = "es-CL-CatalinaNeural",
            _a["es-CO"] = "es-CO-GonzaloNeural",
            _a["es-CR"] = "es-CR-JuanNeural",
            _a["es-CU"] = "es-CU-BelkysNeural",
            _a["es-DO"] = "es-DO-EmilioNeural",
            _a["es-EC"] = "es-EC-AndreaNeural",
            _a["es-ES"] = "es-ES-AlvaroNeural",
            _a["es-GQ"] = "es-GQ-JavierNeural",
            _a["es-GT"] = "es-GT-AndresNeural",
            _a["es-HN"] = "es-HN-CarlosNeural",
            _a["es-MX"] = "es-MX-DaliaNeural",
            _a["es-NI"] = "es-NI-FedericoNeural",
            _a["es-PA"] = "es-PA-MargaritaNeural",
            _a["es-PE"] = "es-PE-AlexNeural",
            _a["es-PR"] = "es-PR-KarinaNeural",
            _a["es-PY"] = "es-PY-MarioNeural",
            _a["es-SV"] = "es-SV-LorenaNeural",
            _a["es-US"] = "es-US-AlonsoNeural",
            _a["es-UY"] = "es-UY-MateoNeural",
            _a["es-VE"] = "es-VE-PaolaNeural",
            _a["et-EE"] = "et-EE-AnuNeural",
            _a["fa-IR"] = "fa-IR-DilaraNeural",
            _a["fi-FI"] = "fi-FI-SelmaNeural",
            _a["fil-PH"] = "fil-PH-AngeloNeural",
            _a["fr-BE"] = "fr-BE-CharlineNeural",
            _a["fr-CA"] = "fr-CA-SylvieNeural",
            _a["fr-CH"] = "fr-CH-ArianeNeural",
            _a["fr-FR"] = "fr-FR-DeniseNeural",
            _a["ga-IE"] = "ga-IE-ColmNeural",
            _a["gl-ES"] = "gl-ES-RoiNeural",
            _a["gu-IN"] = "gu-IN-DhwaniNeural",
            _a["he-IL"] = "he-IL-AvriNeural",
            _a["hi-IN"] = "hi-IN-MadhurNeural",
            _a["hr-HR"] = "hr-HR-GabrijelaNeural",
            _a["hu-HU"] = "hu-HU-NoemiNeural",
            _a["id-ID"] = "id-ID-ArdiNeural",
            _a["it-IT"] = "it-IT-IsabellaNeural",
            _a["ja-JP"] = "ja-JP-NanamiNeural",
            _a["jv-ID"] = "jv-ID-DimasNeural",
            _a["km-KH"] = "km-KH-PisethNeural",
            _a["ko-KR"] = "ko-KR-SunHiNeural",
            _a["lt-LT"] = "lt-LT-LeonasNeural",
            _a["lv-LV"] = "lv-LV-EveritaNeural",
            _a["mr-IN"] = "mr-IN-AarohiNeural",
            _a["ms-MY"] = "ms-MY-OsmanNeural",
            _a["mt-MT"] = "mt-MT-GraceNeural",
            _a["my-MM"] = "my-MM-NilarNeural",
            _a["nb-NO"] = "nb-NO-PernilleNeural",
            _a["nl-BE"] = "nl-BE-ArnaudNeural",
            _a["nl-NL"] = "nl-NL-ColetteNeural",
            _a["pl-PL"] = "pl-PL-AgnieszkaNeural",
            _a["pt-BR"] = "pt-BR-FranciscaNeural",
            _a["pt-PT"] = "pt-PT-DuarteNeural",
            _a["ro-RO"] = "ro-RO-AlinaNeural",
            _a["ru-RU"] = "ru-RU-SvetlanaNeural",
            _a["sk-SK"] = "sk-SK-LukasNeural",
            _a["sl-SI"] = "sl-SI-PetraNeural",
            _a["so-SO"] = "so-SO-MuuseNeural",
            _a["su-ID"] = "su-ID-JajangNeural",
            _a["sv-SE"] = "sv-SE-SofieNeural",
            _a["sw-KE"] = "sw-KE-RafikiNeural",
            _a["sw-TZ"] = "sw-TZ-DaudiNeural",
            _a["ta-IN"] = "ta-IN-PallaviNeural",
            _a["ta-LK"] = "ta-LK-KumarNeural",
            _a["ta-SG"] = "ta-SG-AnbuNeural",
            _a["te-IN"] = "te-IN-MohanNeural",
            _a["th-TH"] = "th-TH-PremwadeeNeural",
            _a["tr-TR"] = "tr-TR-AhmetNeural",
            _a["uk-UA"] = "uk-UA-OstapNeural",
            _a["ur-IN"] = "ur-IN-GulNeural",
            _a["ur-PK"] = "ur-PK-AsadNeural",
            _a["uz-UZ"] = "uz-UZ-MadinaNeural",
            _a["vi-VN"] = "vi-VN-HoaiMyNeural",
            _a["zh-CN"] = "zh-CN-XiaoxiaoNeural",
            _a["zh-HK"] = "zh-HK-HiuMaanNeural",
            _a["zh-TW"] = "zh-TW-HsiaoChenNeural",
            _a["zu-ZA"] = "zu-ZA-ThandoNeural",
            _a);
        var language = this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_SynthLanguage, "en-US");
        var voice = this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_SynthVoice, "");
        var ssml = SpeechSynthesizer.XMLEncode(text);
        if (this.autoDetectSourceLanguage) {
            language = "en-US";
        }
        else {
            voice = voice || languageToDefaultVoice[language];
        }
        if (voice) {
            ssml = "<voice name='" + voice + "'>" + ssml + "</voice>";
        }
        ssml = "<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xmlns:mstts='http://www.w3.org/2001/mstts' xmlns:emo='http://www.w3.org/2009/10/emotionml' xml:lang='" + language + "'>" + ssml + "</speak>";
        return ssml;
    };
    /**
     * Executes speech synthesis on plain text.
     * The task returns the synthesis result.
     * @member SpeechSynthesizer.prototype.speakTextAsync
     * @function
     * @public
     * @param text - Text to be synthesized.
     * @param cb - Callback that received the SpeechSynthesisResult.
     * @param err - Callback invoked in case of an error.
     * @param stream - AudioOutputStream to receive the synthesized audio.
     */
    SpeechSynthesizer.prototype.speakTextAsync = function (text, cb, err, stream) {
        this.speakImpl(text, false, cb, err, stream);
    };
    /**
     * Executes speech synthesis on SSML.
     * The task returns the synthesis result.
     * @member SpeechSynthesizer.prototype.speakSsmlAsync
     * @function
     * @public
     * @param ssml - SSML to be synthesized.
     * @param cb - Callback that received the SpeechSynthesisResult.
     * @param err - Callback invoked in case of an error.
     * @param stream - AudioOutputStream to receive the synthesized audio.
     */
    SpeechSynthesizer.prototype.speakSsmlAsync = function (ssml, cb, err, stream) {
        this.speakImpl(ssml, true, cb, err, stream);
    };
    /**
     * Get list of synthesis voices available.
     * The task returns the synthesis voice result.
     * @member SpeechSynthesizer.prototype.getVoicesAsync
     * @function
     * @async
     * @public
     * @param locale - Locale of voices in BCP-47 format; if left empty, get all available voices.
     * @return {Promise<SynthesisVoicesResult>} - Promise of a SynthesisVoicesResult.
     */
    SpeechSynthesizer.prototype.getVoicesAsync = function (locale) {
        if (locale === void 0) { locale = ""; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.getVoices(locale)];
            });
        });
    };
    /**
     * Dispose of associated resources.
     * @member SpeechSynthesizer.prototype.close
     * @function
     * @public
     */
    SpeechSynthesizer.prototype.close = function (cb, err) {
        Contracts_1.Contracts.throwIfDisposed(this.privDisposed);
        Exports_2.marshalPromiseToCallbacks(this.dispose(true), cb, err);
    };
    Object.defineProperty(SpeechSynthesizer.prototype, "internalData", {
        /**
         * @Internal
         * Do not use externally, object returned will change without warning or notice.
         */
        get: function () {
            return this.privAdapter;
        },
        enumerable: false,
        configurable: true
    });
    /**
     * This method performs cleanup of resources.
     * The Boolean parameter disposing indicates whether the method is called
     * from Dispose (if disposing is true) or from the finalizer (if disposing is false).
     * Derived classes should override this method to dispose resource if needed.
     * @member SpeechSynthesizer.prototype.dispose
     * @function
     * @public
     * @param {boolean} disposing - Flag to request disposal.
     */
    SpeechSynthesizer.prototype.dispose = function (disposing) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privDisposed) {
                            return [2 /*return*/];
                        }
                        if (!disposing) return [3 /*break*/, 2];
                        if (!this.privAdapter) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.privAdapter.dispose()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        this.privDisposed = true;
                        return [2 /*return*/];
                }
            });
        });
    };
    //
    // ################################################################################################################
    // IMPLEMENTATION.
    // Move to independent class
    // ################################################################################################################
    //
    SpeechSynthesizer.prototype.createSynthesizerConfig = function (speechConfig) {
        return new Exports_1.SynthesizerConfig(speechConfig, this.privProperties);
    };
    // Creates the synthesis adapter
    SpeechSynthesizer.prototype.createSynthesisAdapter = function (authentication, connectionFactory, audioConfig, synthesizerConfig) {
        return new Exports_1.SynthesisAdapterBase(authentication, connectionFactory, synthesizerConfig, this, this.audioConfig);
    };
    SpeechSynthesizer.prototype.implCommonSynthesizeSetup = function () {
        var _this = this;
        var osPlatform = (typeof window !== "undefined") ? "Browser" : "Node";
        var osName = "unknown";
        var osVersion = "unknown";
        if (typeof navigator !== "undefined") {
            osPlatform = osPlatform + "/" + navigator.platform;
            osName = navigator.userAgent;
            osVersion = navigator.appVersion;
        }
        var synthesizerConfig = this.createSynthesizerConfig(new Exports_1.SpeechServiceConfig(new Exports_1.Context(new Exports_1.OS(osPlatform, osName, osVersion))));
        var subscriptionKey = this.privProperties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Key, undefined);
        var authentication = (subscriptionKey && subscriptionKey !== "") ?
            new Exports_1.CognitiveSubscriptionKeyAuthentication(subscriptionKey) :
            new Exports_1.CognitiveTokenAuthentication(function (authFetchEventId) {
                var authorizationToken = _this.privProperties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, undefined);
                return Promise.resolve(authorizationToken);
            }, function (authFetchEventId) {
                var authorizationToken = _this.privProperties.getProperty(Exports_3.PropertyId.SpeechServiceAuthorization_Token, undefined);
                return Promise.resolve(authorizationToken);
            });
        this.privAdapter = this.createSynthesisAdapter(authentication, this.privConnectionFactory, this.audioConfig, synthesizerConfig);
        this.privAdapter.audioOutputFormat = AudioOutputFormat_1.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(Exports_3.SpeechSynthesisOutputFormat[this.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)]);
        this.privRestAdapter = new Exports_1.SynthesisRestAdapter(synthesizerConfig);
    };
    SpeechSynthesizer.prototype.speakImpl = function (text, IsSsml, cb, err, dataStream) {
        var _this = this;
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privDisposed);
            var requestId = Exports_2.createNoDashGuid();
            var audioDestination = void 0;
            if (dataStream instanceof Exports_3.PushAudioOutputStreamCallback) {
                audioDestination = new AudioOutputStream_1.PushAudioOutputStreamImpl(dataStream);
            }
            else if (dataStream instanceof Exports_3.PullAudioOutputStream) {
                audioDestination = dataStream;
            }
            else if (dataStream !== undefined) {
                audioDestination = new AudioFileWriter_1.AudioFileWriter(dataStream);
            }
            else {
                audioDestination = undefined;
            }
            this.synthesisRequestQueue.enqueue(new SynthesisRequest(requestId, text, IsSsml, function (e) {
                _this.privSynthesizing = false;
                if (!!cb) {
                    try {
                        cb(e);
                    }
                    catch (e) {
                        if (!!err) {
                            err(e);
                        }
                    }
                }
                cb = undefined;
                /* tslint:disable:no-empty */
                _this.adapterSpeak().catch(function () { });
            }, function (e) {
                if (!!err) {
                    err(e);
                }
            }, audioDestination));
            /* tslint:disable:no-empty */
            this.adapterSpeak().catch(function () { });
        }
        catch (error) {
            if (!!err) {
                if (error instanceof Error) {
                    var typedError = error;
                    err(typedError.name + ": " + typedError.message);
                }
                else {
                    err(error);
                }
            }
            // Destroy the synthesizer.
            /* tslint:disable:no-empty */
            this.dispose(true).catch(function () { });
        }
    };
    SpeechSynthesizer.prototype.getVoices = function (locale) {
        return __awaiter(this, void 0, void 0, function () {
            var requestId, response, json;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        requestId = Exports_2.createNoDashGuid();
                        return [4 /*yield*/, this.privRestAdapter.getVoicesList(requestId)];
                    case 1:
                        response = _a.sent();
                        if (response.ok && Array.isArray(response.json)) {
                            json = response.json;
                            if (!!locale && locale.length > 0) {
                                json = json.filter(function (item) { return !!item.Locale && item.Locale.toLowerCase() === locale.toLowerCase(); });
                            }
                            return [2 /*return*/, new Exports_3.SynthesisVoicesResult(requestId, json)];
                        }
                        else {
                            return [2 /*return*/, new Exports_3.SynthesisVoicesResult(requestId, { errorDetails: "Error: " + response.status + ": " + response.statusText })];
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    SpeechSynthesizer.prototype.adapterSpeak = function () {
        return __awaiter(this, void 0, void 0, function () {
            var request;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(!this.privDisposed && !this.privSynthesizing)) return [3 /*break*/, 2];
                        this.privSynthesizing = true;
                        return [4 /*yield*/, this.synthesisRequestQueue.dequeue()];
                    case 1:
                        request = _a.sent();
                        return [2 /*return*/, this.privAdapter.Speak(request.text, request.isSSML, request.requestId, request.cb, request.err, request.dataStream)];
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    SpeechSynthesizer.XMLEncode = function (text) {
        return text.replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&apos;");
    };
    return SpeechSynthesizer;
}());
exports.SpeechSynthesizer = SpeechSynthesizer;
// tslint:disable-next-line:max-classes-per-file
var SynthesisRequest = /** @class */ (function () {
    function SynthesisRequest(requestId, text, isSSML, cb, err, dataStream) {
        this.requestId = requestId;
        this.text = text;
        this.isSSML = isSSML;
        this.cb = cb;
        this.err = err;
        this.dataStream = dataStream;
    }
    return SynthesisRequest;
}());
exports.SynthesisRequest = SynthesisRequest;



/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisResult = void 0;
/**
 * Base class for synthesis results
 * @class SynthesisResult
 * Added in version 1.20.0
 */
var SynthesisResult = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {string} resultId - The result id.
     * @param {ResultReason} reason - The reason.
     * @param {string} errorDetails - Error details, if provided.
     * @param {PropertyCollection} properties - Additional properties, if provided.
     */
    function SynthesisResult(resultId, reason, errorDetails, properties) {
        this.privResultId = resultId;
        this.privReason = reason;
        this.privErrorDetails = errorDetails;
        this.privProperties = properties;
    }
    Object.defineProperty(SynthesisResult.prototype, "resultId", {
        /**
         * Specifies the result identifier.
         * @member SynthesisResult.prototype.resultId
         * @function
         * @public
         * @returns {string} Specifies the result identifier.
         */
        get: function () {
            return this.privResultId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisResult.prototype, "reason", {
        /**
         * Specifies status of the result.
         * @member SynthesisResult.prototype.reason
         * @function
         * @public
         * @returns {ResultReason} Specifies status of the result.
         */
        get: function () {
            return this.privReason;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisResult.prototype, "errorDetails", {
        /**
         * In case of an unsuccessful synthesis, provides details of the occurred error.
         * @member SynthesisResult.prototype.errorDetails
         * @function
         * @public
         * @returns {string} a brief description of an error.
         */
        get: function () {
            return this.privErrorDetails;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisResult.prototype, "properties", {
        /**
         *  The set of properties exposed in the result.
         * @member SynthesisResult.prototype.properties
         * @function
         * @public
         * @returns {PropertyCollection} The set of properties exposed in the result.
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    return SynthesisResult;
}());
exports.SynthesisResult = SynthesisResult;



/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisResult = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Defines result of speech synthesis.
 * @class SpeechSynthesisResult
 * Added in version 1.11.0
 */
var SpeechSynthesisResult = /** @class */ (function (_super) {
    __extends(SpeechSynthesisResult, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {string} resultId - The result id.
     * @param {ResultReason} reason - The reason.
     * @param {number} audioData - The offset into the stream.
     * @param {string} errorDetails - Error details, if provided.
     * @param {PropertyCollection} properties - Additional properties, if provided.
     */
    function SpeechSynthesisResult(resultId, reason, audioData, errorDetails, properties) {
        var _this = _super.call(this, resultId, reason, errorDetails, properties) || this;
        _this.privAudioData = audioData;
        return _this;
    }
    Object.defineProperty(SpeechSynthesisResult.prototype, "audioData", {
        /**
         * The synthesized audio data
         * @member SpeechSynthesisResult.prototype.audioData
         * @function
         * @public
         * @returns {ArrayBuffer} The synthesized audio data.
         */
        get: function () {
            return this.privAudioData;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechSynthesisResult;
}(Exports_1.SynthesisResult));
exports.SpeechSynthesisResult = SpeechSynthesisResult;



/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisEventArgs = void 0;
/**
 * Defines contents of speech synthesis events.
 * @class SpeechSynthesisEventArgs
 * Added in version 1.11.0
 */
var SpeechSynthesisEventArgs = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {SpeechSynthesisResult} result - The speech synthesis result.
     */
    function SpeechSynthesisEventArgs(result) {
        this.privResult = result;
    }
    Object.defineProperty(SpeechSynthesisEventArgs.prototype, "result", {
        /**
         * Specifies the synthesis result.
         * @member SpeechSynthesisEventArgs.prototype.result
         * @function
         * @public
         * @returns {SpeechSynthesisResult} the synthesis result.
         */
        get: function () {
            return this.privResult;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechSynthesisEventArgs;
}());
exports.SpeechSynthesisEventArgs = SpeechSynthesisEventArgs;



/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisWordBoundaryEventArgs = void 0;
/**
 * Defines contents of speech synthesis word boundary event.
 * @class SpeechSynthesisWordBoundaryEventArgs
 * Added in version 1.11.0
 */
var SpeechSynthesisWordBoundaryEventArgs = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {number} audioOffset - The audio offset.
     * @param {string} text - The text.
     * @param {number} wordLength - The length of the word.
     * @param {number} textOffset - The text offset.
     */
    function SpeechSynthesisWordBoundaryEventArgs(audioOffset, text, wordLength, textOffset) {
        this.privAudioOffset = audioOffset;
        this.privText = text;
        this.privWordLength = wordLength;
        this.privTextOffset = textOffset;
    }
    Object.defineProperty(SpeechSynthesisWordBoundaryEventArgs.prototype, "audioOffset", {
        /**
         * Specifies the audio offset.
         * @member SpeechSynthesisWordBoundaryEventArgs.prototype.audioOffset
         * @function
         * @public
         * @returns {number} the audio offset.
         */
        get: function () {
            return this.privAudioOffset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechSynthesisWordBoundaryEventArgs.prototype, "text", {
        /**
         * Specifies the text of the word boundary event.
         * @member SpeechSynthesisWordBoundaryEventArgs.prototype.text
         * @function
         * @public
         * @returns {string} the text.
         */
        get: function () {
            return this.privText;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechSynthesisWordBoundaryEventArgs.prototype, "wordLength", {
        /**
         * Specifies the word length
         * @member SpeechSynthesisWordBoundaryEventArgs.prototype.wordLength
         * @function
         * @public
         * @returns {number} the word length
         */
        get: function () {
            return this.privWordLength;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechSynthesisWordBoundaryEventArgs.prototype, "textOffset", {
        /**
         * Specifies the text offset.
         * @member SpeechSynthesisWordBoundaryEventArgs.prototype.textOffset
         * @function
         * @public
         * @returns {number} the text offset.
         */
        get: function () {
            return this.privTextOffset;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechSynthesisWordBoundaryEventArgs;
}());
exports.SpeechSynthesisWordBoundaryEventArgs = SpeechSynthesisWordBoundaryEventArgs;



/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisBookmarkEventArgs = void 0;
/**
 * Defines contents of speech synthesis bookmark event.
 * @class SpeechSynthesisBookmarkEventArgs
 * Added in version 1.16.0
 */
var SpeechSynthesisBookmarkEventArgs = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {number} audioOffset - The audio offset.
     * @param {string} text - The bookmark text.
     */
    function SpeechSynthesisBookmarkEventArgs(audioOffset, text) {
        this.privAudioOffset = audioOffset;
        this.privText = text;
    }
    Object.defineProperty(SpeechSynthesisBookmarkEventArgs.prototype, "audioOffset", {
        /**
         * Specifies the audio offset.
         * @member SpeechSynthesisBookmarkEventArgs.prototype.audioOffset
         * @function
         * @public
         * @returns {number} the audio offset.
         */
        get: function () {
            return this.privAudioOffset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechSynthesisBookmarkEventArgs.prototype, "text", {
        /**
         * Specifies the bookmark.
         * @member SpeechSynthesisBookmarkEventArgs.prototype.text
         * @function
         * @public
         * @returns {string} the bookmark text.
         */
        get: function () {
            return this.privText;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechSynthesisBookmarkEventArgs;
}());
exports.SpeechSynthesisBookmarkEventArgs = SpeechSynthesisBookmarkEventArgs;



/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisVisemeEventArgs = void 0;
/**
 * Defines contents of speech synthesis viseme event.
 * @class SpeechSynthesisVisemeEventArgs
 * Added in version 1.16.0
 */
var SpeechSynthesisVisemeEventArgs = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param {number} audioOffset - The audio offset.
     * @param {number} visemeId - The viseme ID.
     * @param {string} animation - The animation, could be in svg or other format.
     */
    function SpeechSynthesisVisemeEventArgs(audioOffset, visemeId, animation) {
        this.privAudioOffset = audioOffset;
        this.privVisemeId = visemeId;
        this.privAnimation = animation;
    }
    Object.defineProperty(SpeechSynthesisVisemeEventArgs.prototype, "audioOffset", {
        /**
         * Specifies the audio offset.
         * @member SpeechSynthesisVisemeEventArgs.prototype.audioOffset
         * @function
         * @public
         * @returns {number} the audio offset.
         */
        get: function () {
            return this.privAudioOffset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechSynthesisVisemeEventArgs.prototype, "visemeId", {
        /**
         * Specifies the viseme ID.
         * @member SpeechSynthesisVisemeEventArgs.prototype.visemeId
         * @function
         * @public
         * @returns {number} the viseme ID.
         */
        get: function () {
            return this.privVisemeId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechSynthesisVisemeEventArgs.prototype, "animation", {
        /**
         * Specifies the animation.
         * @member SpeechSynthesisVisemeEventArgs.prototype.animation
         * @function
         * @public
         * @returns {string} the animation, could be in svg or other format.
         */
        get: function () {
            return this.privAnimation;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechSynthesisVisemeEventArgs;
}());
exports.SpeechSynthesisVisemeEventArgs = SpeechSynthesisVisemeEventArgs;



/***/ }),
/* 163 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisVoicesResult = void 0;
var Exports_1 = __webpack_require__(61);
/**
 * Defines result of speech synthesis.
 * @class SynthesisVoicesResult
 * Added in version 1.20.0
 */
var SynthesisVoicesResult = /** @class */ (function (_super) {
    __extends(SynthesisVoicesResult, _super);
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param requestId - result id for request.
     * @param json - json payload from endpoint.
     */
    function SynthesisVoicesResult(requestId, json) {
        var _this = this;
        if (Array.isArray(json)) {
            _this = _super.call(this, requestId, Exports_1.ResultReason.VoicesListRetrieved, undefined, new Exports_1.PropertyCollection()) || this;
            _this.privVoices = [];
            for (var _i = 0, json_1 = json; _i < json_1.length; _i++) {
                var item = json_1[_i];
                _this.privVoices.push(new Exports_1.VoiceInfo(item));
            }
        }
        else {
            _this = _super.call(this, requestId, Exports_1.ResultReason.Canceled, !!json.errorDetails ? json.errorDetails : "Error information unavailable", new Exports_1.PropertyCollection()) || this;
        }
        return _this;
    }
    Object.defineProperty(SynthesisVoicesResult.prototype, "voices", {
        /**
         * The list of voices
         * @member SynthesisVoicesResult.prototype.voices
         * @function
         * @public
         * @returns {VoiceInfo[]} List of synthesized voices.
         */
        get: function () {
            return this.privVoices;
        },
        enumerable: false,
        configurable: true
    });
    return SynthesisVoicesResult;
}(Exports_1.SynthesisResult));
exports.SynthesisVoicesResult = SynthesisVoicesResult;



/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceInfo = exports.SynthesisVoiceType = exports.SynthesisVoiceGender = void 0;
/**
 *  Defines the gender of synthesis voices.
 *  Added in version 1.20.0.
 */
var SynthesisVoiceGender;
(function (SynthesisVoiceGender) {
    /** Gender unknown */
    SynthesisVoiceGender[SynthesisVoiceGender["Unknown"] = 0] = "Unknown";
    /** Female voice */
    SynthesisVoiceGender[SynthesisVoiceGender["Female"] = 1] = "Female";
    /** Male voice */
    SynthesisVoiceGender[SynthesisVoiceGender["Male"] = 2] = "Male";
})(SynthesisVoiceGender = exports.SynthesisVoiceGender || (exports.SynthesisVoiceGender = {}));
var SynthesisVoiceType;
(function (SynthesisVoiceType) {
    SynthesisVoiceType[SynthesisVoiceType["OnlineNeural"] = 1] = "OnlineNeural";
    SynthesisVoiceType[SynthesisVoiceType["OnlineStandard"] = 2] = "OnlineStandard";
    SynthesisVoiceType[SynthesisVoiceType["OfflineNeural"] = 3] = "OfflineNeural";
    SynthesisVoiceType[SynthesisVoiceType["OfflineStandard"] = 4] = "OfflineStandard";
})(SynthesisVoiceType = exports.SynthesisVoiceType || (exports.SynthesisVoiceType = {}));
/**
 * Information about Speech Synthesis voice
 * Added in version 1.20.0.
 * @class VoiceInfo
 */
var VoiceInfo = /** @class */ (function () {
    function VoiceInfo(json) {
        this.privStyleList = [];
        this.privVoicePath = "";
        if (!!json) {
            this.privName = json.Name;
            this.privLocale = json.Locale;
            this.privShortName = json.ShortName;
            this.privLocalName = json.LocalName;
            this.privVoiceType = json.VoiceType.endsWith("Standard") ? SynthesisVoiceType.OnlineStandard : SynthesisVoiceType.OnlineNeural;
            this.privGender = json.Gender === "Male" ? SynthesisVoiceGender.Male : json.Gender === "Female" ? SynthesisVoiceGender.Female : SynthesisVoiceGender.Unknown;
            if (!!json.StyleList && Array.isArray(json.StyleList)) {
                for (var _i = 0, _a = json.StyleList; _i < _a.length; _i++) {
                    var style = _a[_i];
                    this.privStyleList.push(style);
                }
            }
        }
    }
    Object.defineProperty(VoiceInfo.prototype, "name", {
        get: function () {
            return this.privName;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceInfo.prototype, "locale", {
        get: function () {
            return this.privLocale;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceInfo.prototype, "shortName", {
        get: function () {
            return this.privShortName;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceInfo.prototype, "localName", {
        get: function () {
            return this.privLocalName;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceInfo.prototype, "gender", {
        get: function () {
            return this.privGender;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceInfo.prototype, "voiceType", {
        get: function () {
            return this.privVoiceType;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceInfo.prototype, "styleList", {
        get: function () {
            return this.privStyleList;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VoiceInfo.prototype, "voicePath", {
        get: function () {
            return this.privVoicePath;
        },
        enumerable: false,
        configurable: true
    });
    return VoiceInfo;
}());
exports.VoiceInfo = VoiceInfo;



/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerAudioDestination = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var AudioOutputStream_1 = __webpack_require__(73);
var AudioStreamFormat_1 = __webpack_require__(72);
var MediaDurationPlaceholderSeconds = 60 * 30;
var AudioFormatToMimeType = (_a = {},
    _a[AudioStreamFormat_1.AudioFormatTag.PCM] = "audio/wav",
    _a[AudioStreamFormat_1.AudioFormatTag.MuLaw] = "audio/x-wav",
    _a[AudioStreamFormat_1.AudioFormatTag.MP3] = "audio/mpeg",
    _a[AudioStreamFormat_1.AudioFormatTag.OGG_OPUS] = "audio/ogg",
    _a[AudioStreamFormat_1.AudioFormatTag.WEBM_OPUS] = "audio/webm; codecs=opus",
    _a[AudioStreamFormat_1.AudioFormatTag.ALaw] = "audio/x-wav",
    _a[AudioStreamFormat_1.AudioFormatTag.FLAC] = "audio/flac",
    _a);
/**
 * Represents the speaker playback audio destination, which only works in browser.
 * Note: the SDK will try to use <a href="https://www.w3.org/TR/media-source/">Media Source Extensions</a> to play audio.
 * Mp3 format has better supports on Microsoft Edge, Chrome and Safari (desktop), so, it's better to specify mp3 format for playback.
 * @class SpeakerAudioDestination
 * Updated in version 1.17.0
 */
var SpeakerAudioDestination = /** @class */ (function () {
    function SpeakerAudioDestination(audioDestinationId) {
        this.privPlaybackStarted = false;
        this.privAppendingToBuffer = false;
        this.privMediaSourceOpened = false;
        this.privBytesReceived = 0;
        this.privId = audioDestinationId ? audioDestinationId : Exports_2.createNoDashGuid();
        this.privIsPaused = false;
        this.privIsClosed = false;
    }
    SpeakerAudioDestination.prototype.id = function () {
        return this.privId;
    };
    SpeakerAudioDestination.prototype.write = function (buffer, cb, err) {
        if (this.privAudioBuffer !== undefined) {
            this.privAudioBuffer.push(buffer);
            this.updateSourceBuffer().then(function () {
                if (!!cb) {
                    cb();
                }
            }, function (error) {
                if (!!err) {
                    err(error);
                }
            });
        }
        else if (this.privAudioOutputStream !== undefined) {
            this.privAudioOutputStream.write(buffer);
            this.privBytesReceived += buffer.byteLength;
        }
    };
    SpeakerAudioDestination.prototype.close = function (cb, err) {
        var _this = this;
        this.privIsClosed = true;
        if (this.privSourceBuffer !== undefined) {
            this.handleSourceBufferUpdateEnd().then(function () {
                if (!!cb) {
                    cb();
                }
            }, function (error) {
                if (!!err) {
                    err(error);
                }
            });
        }
        else if (this.privAudioOutputStream !== undefined) {
            if ((this.privFormat.formatTag === AudioStreamFormat_1.AudioFormatTag.PCM || this.privFormat.formatTag === AudioStreamFormat_1.AudioFormatTag.MuLaw
                || this.privFormat.formatTag === AudioStreamFormat_1.AudioFormatTag.ALaw) && this.privFormat.hasHeader === false) {
                // tslint:disable-next-line:no-console
                console.warn("Play back is not supported for raw PCM, mulaw or alaw format without header.");
                if (!!this.onAudioEnd) {
                    this.onAudioEnd(this);
                }
            }
            else {
                var receivedAudio_1 = new ArrayBuffer(this.privBytesReceived);
                this.privAudioOutputStream.read(receivedAudio_1).then(function (_) {
                    receivedAudio_1 = Exports_1.SynthesisAdapterBase.addHeader(receivedAudio_1, _this.privFormat);
                    var audioBlob = new Blob([receivedAudio_1], { type: AudioFormatToMimeType[_this.privFormat.formatTag] });
                    _this.privAudio.src = window.URL.createObjectURL(audioBlob);
                    _this.notifyPlayback().then(function () {
                        if (!!cb) {
                            cb();
                        }
                    }, function (error) {
                        if (!!err) {
                            err(error);
                        }
                    });
                }, function (error) {
                    if (!!err) {
                        err(error);
                    }
                });
            }
        }
        else {
            // unsupported format, call onAudioEnd directly.
            if (!!this.onAudioEnd) {
                this.onAudioEnd(this);
            }
        }
    };
    Object.defineProperty(SpeakerAudioDestination.prototype, "format", {
        set: function (format) {
            var _this = this;
            if (typeof (AudioContext) !== "undefined" || typeof (window.webkitAudioContext) !== "undefined") {
                this.privFormat = format;
                var mimeType_1 = AudioFormatToMimeType[this.privFormat.formatTag];
                if (mimeType_1 === undefined) {
                    // tslint:disable-next-line:no-console
                    console.warn("Unknown mimeType for format " + AudioStreamFormat_1.AudioFormatTag[this.privFormat.formatTag] + "; playback is not supported.");
                }
                else if (typeof (MediaSource) !== "undefined" && MediaSource.isTypeSupported(mimeType_1)) {
                    this.privAudio = new Audio();
                    this.privAudioBuffer = [];
                    this.privMediaSource = new MediaSource();
                    this.privAudio.src = URL.createObjectURL(this.privMediaSource);
                    this.privAudio.load();
                    this.privMediaSource.onsourceopen = function (event) {
                        _this.privMediaSourceOpened = true;
                        _this.privMediaSource.duration = MediaDurationPlaceholderSeconds;
                        _this.privSourceBuffer = _this.privMediaSource.addSourceBuffer(mimeType_1);
                        _this.privSourceBuffer.onupdate = function (_) {
                            _this.updateSourceBuffer().catch(function (reason) {
                                Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason));
                            });
                        };
                        _this.privSourceBuffer.onupdateend = function (_) {
                            _this.handleSourceBufferUpdateEnd().catch(function (reason) {
                                Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason));
                            });
                        };
                        _this.privSourceBuffer.onupdatestart = function (_) {
                            _this.privAppendingToBuffer = false;
                        };
                    };
                    this.updateSourceBuffer().catch(function (reason) {
                        Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason));
                    });
                }
                else {
                    // tslint:disable-next-line:no-console
                    console.warn("Format " + AudioStreamFormat_1.AudioFormatTag[this.privFormat.formatTag] + " could not be played by MSE, streaming playback is not enabled.");
                    this.privAudioOutputStream = new AudioOutputStream_1.PullAudioOutputStreamImpl();
                    this.privAudioOutputStream.format = this.privFormat;
                    this.privAudio = new Audio();
                }
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeakerAudioDestination.prototype, "volume", {
        get: function () {
            return this.privAudio.volume;
        },
        set: function (volume) {
            this.privAudio.volume = volume;
        },
        enumerable: false,
        configurable: true
    });
    SpeakerAudioDestination.prototype.mute = function () {
        this.privAudio.muted = true;
    };
    SpeakerAudioDestination.prototype.unmute = function () {
        this.privAudio.muted = false;
    };
    Object.defineProperty(SpeakerAudioDestination.prototype, "isClosed", {
        get: function () {
            return this.privIsClosed;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeakerAudioDestination.prototype, "currentTime", {
        get: function () {
            if (this.privAudio !== undefined) {
                return this.privAudio.currentTime;
            }
            return -1;
        },
        enumerable: false,
        configurable: true
    });
    SpeakerAudioDestination.prototype.pause = function () {
        if (!this.privIsPaused && this.privAudio !== undefined) {
            this.privAudio.pause();
            this.privIsPaused = true;
        }
    };
    SpeakerAudioDestination.prototype.resume = function (cb, err) {
        if (this.privIsPaused && this.privAudio !== undefined) {
            this.privAudio.play().then(function () {
                if (!!cb) {
                    cb();
                }
            }, function (error) {
                if (!!err) {
                    err(error);
                }
            });
            this.privIsPaused = false;
        }
    };
    Object.defineProperty(SpeakerAudioDestination.prototype, "internalAudio", {
        get: function () {
            return this.privAudio;
        },
        enumerable: false,
        configurable: true
    });
    SpeakerAudioDestination.prototype.updateSourceBuffer = function () {
        return __awaiter(this, void 0, void 0, function () {
            var binary;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.privAudioBuffer !== undefined && (this.privAudioBuffer.length > 0) && this.sourceBufferAvailable())) return [3 /*break*/, 2];
                        this.privAppendingToBuffer = true;
                        binary = this.privAudioBuffer.shift();
                        try {
                            this.privSourceBuffer.appendBuffer(binary);
                        }
                        catch (error) {
                            this.privAudioBuffer.unshift(binary);
                            // tslint:disable-next-line:no-console
                            console.log("buffer filled, pausing addition of binaries until space is made");
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, this.notifyPlayback()];
                    case 1:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 2:
                        if (!this.canEndStream()) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.handleSourceBufferUpdateEnd()];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    SpeakerAudioDestination.prototype.handleSourceBufferUpdateEnd = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.canEndStream() && this.sourceBufferAvailable())) return [3 /*break*/, 2];
                        this.privMediaSource.endOfStream();
                        return [4 /*yield*/, this.notifyPlayback()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    SpeakerAudioDestination.prototype.notifyPlayback = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(!this.privPlaybackStarted && this.privAudio !== undefined)) return [3 /*break*/, 2];
                        this.privPlaybackStarted = true;
                        if (!!this.onAudioStart) {
                            this.onAudioStart(this);
                        }
                        this.privAudio.onended = function () {
                            if (!!_this.onAudioEnd) {
                                _this.onAudioEnd(_this);
                            }
                        };
                        if (!!this.privIsPaused) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.privAudio.play()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    SpeakerAudioDestination.prototype.canEndStream = function () {
        return (this.isClosed && this.privSourceBuffer !== undefined && (this.privAudioBuffer.length === 0)
            && this.privMediaSourceOpened && !this.privAppendingToBuffer && this.privMediaSource.readyState === "open");
    };
    SpeakerAudioDestination.prototype.sourceBufferAvailable = function () {
        return (this.privSourceBuffer !== undefined && !this.privSourceBuffer.updating);
    };
    return SpeakerAudioDestination;
}());
exports.SpeakerAudioDestination = SpeakerAudioDestination;



/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranscriptionCanceledEventArgs = void 0;
var CancellationEventArgsBase_1 = __webpack_require__(90);
/**
 * Defines content of a RecognitionErrorEvent.
 * @class ConversationTranscriptionCanceledEventArgs
 */
var ConversationTranscriptionCanceledEventArgs = /** @class */ (function (_super) {
    __extends(ConversationTranscriptionCanceledEventArgs, _super);
    function ConversationTranscriptionCanceledEventArgs() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return ConversationTranscriptionCanceledEventArgs;
}(CancellationEventArgsBase_1.CancellationEventArgsBase));
exports.ConversationTranscriptionCanceledEventArgs = ConversationTranscriptionCanceledEventArgs;



/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PronunciationAssessmentGradingSystem = void 0;
/**
 * Defines the point system for pronunciation score calibration; default value is FivePoint.
 * Added in version 1.15.0
 * @class PronunciationAssessmentGradingSystem
 */
var PronunciationAssessmentGradingSystem;
(function (PronunciationAssessmentGradingSystem) {
    /**
     * Five point calibration
     * @member PronunciationAssessmentGradingSystem.FivePoint
     */
    PronunciationAssessmentGradingSystem[PronunciationAssessmentGradingSystem["FivePoint"] = 1] = "FivePoint";
    /**
     * Hundred mark
     * @member PronunciationAssessmentGradingSystem.HundredMark
     */
    PronunciationAssessmentGradingSystem[PronunciationAssessmentGradingSystem["HundredMark"] = 2] = "HundredMark";
})(PronunciationAssessmentGradingSystem = exports.PronunciationAssessmentGradingSystem || (exports.PronunciationAssessmentGradingSystem = {}));



/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PronunciationAssessmentGranularity = void 0;
/**
 * Defines the pronunciation evaluation granularity; default value is Phoneme.
 * Added in version 1.15.0
 * @class PronunciationAssessmentGranularity
 */
var PronunciationAssessmentGranularity;
(function (PronunciationAssessmentGranularity) {
    /**
     * Shows the score on the full text, word and phoneme level
     * @member PronunciationAssessmentGranularity.Phoneme
     */
    PronunciationAssessmentGranularity[PronunciationAssessmentGranularity["Phoneme"] = 1] = "Phoneme";
    /**
     * Shows the score on the full text and word level
     * @member PronunciationAssessmentGranularity.Word
     */
    PronunciationAssessmentGranularity[PronunciationAssessmentGranularity["Word"] = 2] = "Word";
    /**
     * Shows the score on the full text level only
     * @member PronunciationAssessmentGranularity.FullText
     */
    PronunciationAssessmentGranularity[PronunciationAssessmentGranularity["FullText"] = 3] = "FullText";
})(PronunciationAssessmentGranularity = exports.PronunciationAssessmentGranularity || (exports.PronunciationAssessmentGranularity = {}));



/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PronunciationAssessmentConfig = void 0;
var Contracts_1 = __webpack_require__(63);
var Exports_1 = __webpack_require__(61);
/**
 * Pronunciation assessment configuration.
 * @class PronunciationAssessmentConfig
 * Added in version 1.15.0.
 */
var PronunciationAssessmentConfig = /** @class */ (function () {
    /**
     * PronunciationAssessmentConfig constructor.
     * @constructor
     * @param {string} referenceText
     * @param gradingSystem
     * @param granularity
     * @param enableMiscue
     */
    function PronunciationAssessmentConfig(referenceText, gradingSystem, granularity, enableMiscue) {
        if (gradingSystem === void 0) { gradingSystem = Exports_1.PronunciationAssessmentGradingSystem.FivePoint; }
        if (granularity === void 0) { granularity = Exports_1.PronunciationAssessmentGranularity.Phoneme; }
        if (enableMiscue === void 0) { enableMiscue = false; }
        Contracts_1.Contracts.throwIfNullOrUndefined(referenceText, "referenceText");
        this.privProperties = new Exports_1.PropertyCollection();
        this.privProperties.setProperty(Exports_1.PropertyId.PronunciationAssessment_ReferenceText, referenceText);
        this.privProperties.setProperty(Exports_1.PropertyId.PronunciationAssessment_GradingSystem, Exports_1.PronunciationAssessmentGradingSystem[gradingSystem]);
        this.privProperties.setProperty(Exports_1.PropertyId.PronunciationAssessment_Granularity, Exports_1.PronunciationAssessmentGranularity[granularity]);
        this.privProperties.setProperty(Exports_1.PropertyId.PronunciationAssessment_EnableMiscue, String(enableMiscue));
    }
    /**
     * @member PronunciationAssessmentConfig.fromJSON
     * @function
     * @public
     * @param {string} json The json string containing the pronunciation assessment parameters.
     * @return {PronunciationAssessmentConfig} Instance of PronunciationAssessmentConfig
     * @summary Creates an instance of the PronunciationAssessmentConfig from json.
     */
    PronunciationAssessmentConfig.fromJSON = function (json) {
        Contracts_1.Contracts.throwIfNullOrUndefined(json, "json");
        var config = new PronunciationAssessmentConfig("");
        config.privProperties = new Exports_1.PropertyCollection();
        config.properties.setProperty(Exports_1.PropertyId.PronunciationAssessment_Json, json);
        return config;
    };
    PronunciationAssessmentConfig.prototype.toJSON = function () {
        this.updateJson();
        return this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_Params);
    };
    PronunciationAssessmentConfig.prototype.applyTo = function (recognizer) {
        this.updateJson();
        var recoBase = recognizer.internalData;
        recoBase.speechContext.setPronunciationAssessmentParams(this.properties.getProperty(Exports_1.PropertyId.PronunciationAssessment_Params));
    };
    Object.defineProperty(PronunciationAssessmentConfig.prototype, "referenceText", {
        /**
         * Gets the reference text.
         * @member PronunciationAssessmentConfig.prototype.referenceText
         * @function
         * @public
         * @returns {string} Reference text.
         */
        get: function () {
            return this.properties.getProperty(Exports_1.PropertyId.PronunciationAssessment_ReferenceText);
        },
        /**
         * Gets/Sets the reference text.
         * @member PronunciationAssessmentConfig.prototype.referenceText
         * @function
         * @public
         * @param {string} referenceText - Reference text.
         */
        set: function (referenceText) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(referenceText, "referenceText");
            this.properties.setProperty(Exports_1.PropertyId.PronunciationAssessment_ReferenceText, referenceText);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PronunciationAssessmentConfig.prototype, "phonemeAlphabet", {
        /**
         * Sets the phoneme alphabet.
         * The valid values are "SAPI" (default) and "IPA".
         * Added in version 1.20.0
         * @member PronunciationAssessmentConfig.prototype.phonemeAlphabet
         * @function
         * @public
         * @param {string} phonemeAlphabet - Phoneme alphabet.
         */
        set: function (phonemeAlphabet) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(phonemeAlphabet, "phonemeAlphabet");
            this.privPhonemeAlphabet = phonemeAlphabet;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PronunciationAssessmentConfig.prototype, "nbestPhonemeCount", {
        /**
         * Sets the nbest phoneme count
         * Added in version 1.20.0
         * @member PronunciationAssessmentConfig.prototype.nbestPhonemeCount
         * @function
         * @public
         * @param {number} nbestPhonemeCount - NBest phoneme count.
         */
        set: function (nbestPhonemeCount) {
            this.privNBestPhonemeCount = nbestPhonemeCount;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PronunciationAssessmentConfig.prototype, "properties", {
        /**
         * @member PronunciationAssessmentConfig.prototype.properties
         * @function
         * @public
         * @return {PropertyCollection} Properties of the config.
         * @summary Gets a pronunciation assessment config properties
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    PronunciationAssessmentConfig.prototype.updateJson = function () {
        var jsonString = this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_Json, "{}");
        var paramsJson = JSON.parse(jsonString);
        var referenceText = this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_ReferenceText);
        if (referenceText) {
            paramsJson.referenceText = referenceText;
        }
        var gradingSystem = this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_GradingSystem);
        if (gradingSystem) {
            paramsJson.gradingSystem = gradingSystem;
        }
        var granularity = this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_Granularity);
        if (granularity) {
            paramsJson.granularity = granularity;
        }
        if (this.privPhonemeAlphabet) {
            paramsJson.phonemeAlphabet = this.privPhonemeAlphabet;
        }
        if (this.privNBestPhonemeCount) {
            paramsJson.nbestPhonemeCount = this.privNBestPhonemeCount;
        }
        // always set dimension to Comprehensive
        paramsJson.dimension = "Comprehensive";
        var enableMiscueString = this.privProperties.getProperty(Exports_1.PropertyId.PronunciationAssessment_EnableMiscue);
        if (enableMiscueString === "true") {
            paramsJson.enableMiscue = true;
        }
        else if (enableMiscueString === "false") {
            paramsJson.enableMiscue = false;
        }
        this.privProperties.setProperty(Exports_1.PropertyId.PronunciationAssessment_Params, JSON.stringify(paramsJson));
    };
    return PronunciationAssessmentConfig;
}());
exports.PronunciationAssessmentConfig = PronunciationAssessmentConfig;



/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PronunciationAssessmentResult = void 0;
var Contracts_1 = __webpack_require__(63);
var Exports_1 = __webpack_require__(61);
/**
 * Pronunciation assessment results.
 * @class PronunciationAssessmentResult
 * Added in version 1.15.0.
 */
var PronunciationAssessmentResult = /** @class */ (function () {
    function PronunciationAssessmentResult(jsonString) {
        var j = JSON.parse(jsonString);
        Contracts_1.Contracts.throwIfNullOrUndefined(j.NBest[0], "NBest");
        this.privPronJson = j.NBest[0];
    }
    /**
     * @member PronunciationAssessmentResult.fromResult
     * @function
     * @public
     * @param {RecognitionResult} result The recognition result.
     * @return {PronunciationAssessmentConfig} Instance of PronunciationAssessmentConfig
     * @summary Creates an instance of the PronunciationAssessmentResult from recognition result.
     */
    PronunciationAssessmentResult.fromResult = function (result) {
        Contracts_1.Contracts.throwIfNullOrUndefined(result, "result");
        var json = result.properties.getProperty(Exports_1.PropertyId.SpeechServiceResponse_JsonResult);
        Contracts_1.Contracts.throwIfNullOrUndefined(json, "json");
        return new PronunciationAssessmentResult(json);
    };
    Object.defineProperty(PronunciationAssessmentResult.prototype, "detailResult", {
        /**
         * Gets the detail result of pronunciation assessment.
         * @member PronunciationAssessmentConfig.prototype.detailResult
         * @function
         * @public
         * @returns {any} detail result.
         */
        get: function () {
            return this.privPronJson;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PronunciationAssessmentResult.prototype, "accuracyScore", {
        /**
         * The score indicating the pronunciation accuracy of the given speech, which indicates
         * how closely the phonemes match a native speaker's pronunciation.
         * @member PronunciationAssessmentResult.prototype.accuracyScore
         * @function
         * @public
         * @returns {number} Accuracy score.
         */
        get: function () {
            return this.detailResult.PronunciationAssessment.AccuracyScore;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PronunciationAssessmentResult.prototype, "pronunciationScore", {
        /**
         * The overall score indicating the pronunciation quality of the given speech.
         * This is calculated from AccuracyScore, FluencyScore and CompletenessScore with weight.
         * @member PronunciationAssessmentResult.prototype.pronunciationScore
         * @function
         * @public
         * @returns {number} Pronunciation score.
         */
        get: function () {
            return this.detailResult.PronunciationAssessment.PronScore;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PronunciationAssessmentResult.prototype, "completenessScore", {
        /**
         * The score indicating the completeness of the given speech by calculating the ratio of pronounced words towards entire input.
         * @member PronunciationAssessmentResult.prototype.completenessScore
         * @function
         * @public
         * @returns {number} Completeness score.
         */
        get: function () {
            return this.detailResult.PronunciationAssessment.CompletenessScore;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PronunciationAssessmentResult.prototype, "fluencyScore", {
        /**
         * The score indicating the fluency of the given speech.
         * @member PronunciationAssessmentResult.prototype.fluencyScore
         * @function
         * @public
         * @returns {number} Fluency score.
         */
        get: function () {
            return this.detailResult.PronunciationAssessment.FluencyScore;
        },
        enumerable: false,
        configurable: true
    });
    return PronunciationAssessmentResult;
}());
exports.PronunciationAssessmentResult = PronunciationAssessmentResult;



/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecognitionEndedEvent = exports.RecognitionCompletionStatus = exports.RecognitionStartedEvent = exports.ConnectingToServiceEvent = exports.ListeningStartedEvent = exports.RecognitionTriggeredEvent = exports.SpeechRecognitionEvent = void 0;
// tslint:disable:max-classes-per-file
var Exports_1 = __webpack_require__(4);
var SpeechRecognitionEvent = /** @class */ (function (_super) {
    __extends(SpeechRecognitionEvent, _super);
    function SpeechRecognitionEvent(eventName, requestId, sessionId, eventType) {
        if (eventType === void 0) { eventType = Exports_1.EventType.Info; }
        var _this = _super.call(this, eventName, eventType) || this;
        _this.privRequestId = requestId;
        _this.privSessionId = sessionId;
        return _this;
    }
    Object.defineProperty(SpeechRecognitionEvent.prototype, "requestId", {
        get: function () {
            return this.privRequestId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechRecognitionEvent.prototype, "sessionId", {
        get: function () {
            return this.privSessionId;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechRecognitionEvent;
}(Exports_1.PlatformEvent));
exports.SpeechRecognitionEvent = SpeechRecognitionEvent;
var RecognitionTriggeredEvent = /** @class */ (function (_super) {
    __extends(RecognitionTriggeredEvent, _super);
    function RecognitionTriggeredEvent(requestId, sessionId, audioSourceId, audioNodeId) {
        var _this = _super.call(this, "RecognitionTriggeredEvent", requestId, sessionId) || this;
        _this.privAudioSourceId = audioSourceId;
        _this.privAudioNodeId = audioNodeId;
        return _this;
    }
    Object.defineProperty(RecognitionTriggeredEvent.prototype, "audioSourceId", {
        get: function () {
            return this.privAudioSourceId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionTriggeredEvent.prototype, "audioNodeId", {
        get: function () {
            return this.privAudioNodeId;
        },
        enumerable: false,
        configurable: true
    });
    return RecognitionTriggeredEvent;
}(SpeechRecognitionEvent));
exports.RecognitionTriggeredEvent = RecognitionTriggeredEvent;
var ListeningStartedEvent = /** @class */ (function (_super) {
    __extends(ListeningStartedEvent, _super);
    function ListeningStartedEvent(requestId, sessionId, audioSourceId, audioNodeId) {
        var _this = _super.call(this, "ListeningStartedEvent", requestId, sessionId) || this;
        _this.privAudioSourceId = audioSourceId;
        _this.privAudioNodeId = audioNodeId;
        return _this;
    }
    Object.defineProperty(ListeningStartedEvent.prototype, "audioSourceId", {
        get: function () {
            return this.privAudioSourceId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ListeningStartedEvent.prototype, "audioNodeId", {
        get: function () {
            return this.privAudioNodeId;
        },
        enumerable: false,
        configurable: true
    });
    return ListeningStartedEvent;
}(SpeechRecognitionEvent));
exports.ListeningStartedEvent = ListeningStartedEvent;
var ConnectingToServiceEvent = /** @class */ (function (_super) {
    __extends(ConnectingToServiceEvent, _super);
    function ConnectingToServiceEvent(requestId, authFetchEventid, sessionId) {
        var _this = _super.call(this, "ConnectingToServiceEvent", requestId, sessionId) || this;
        _this.privAuthFetchEventid = authFetchEventid;
        return _this;
    }
    Object.defineProperty(ConnectingToServiceEvent.prototype, "authFetchEventid", {
        get: function () {
            return this.privAuthFetchEventid;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectingToServiceEvent;
}(SpeechRecognitionEvent));
exports.ConnectingToServiceEvent = ConnectingToServiceEvent;
var RecognitionStartedEvent = /** @class */ (function (_super) {
    __extends(RecognitionStartedEvent, _super);
    function RecognitionStartedEvent(requestId, audioSourceId, audioNodeId, authFetchEventId, sessionId) {
        var _this = _super.call(this, "RecognitionStartedEvent", requestId, sessionId) || this;
        _this.privAudioSourceId = audioSourceId;
        _this.privAudioNodeId = audioNodeId;
        _this.privAuthFetchEventId = authFetchEventId;
        return _this;
    }
    Object.defineProperty(RecognitionStartedEvent.prototype, "audioSourceId", {
        get: function () {
            return this.privAudioSourceId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionStartedEvent.prototype, "audioNodeId", {
        get: function () {
            return this.privAudioNodeId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionStartedEvent.prototype, "authFetchEventId", {
        get: function () {
            return this.privAuthFetchEventId;
        },
        enumerable: false,
        configurable: true
    });
    return RecognitionStartedEvent;
}(SpeechRecognitionEvent));
exports.RecognitionStartedEvent = RecognitionStartedEvent;
var RecognitionCompletionStatus;
(function (RecognitionCompletionStatus) {
    RecognitionCompletionStatus[RecognitionCompletionStatus["Success"] = 0] = "Success";
    RecognitionCompletionStatus[RecognitionCompletionStatus["AudioSourceError"] = 1] = "AudioSourceError";
    RecognitionCompletionStatus[RecognitionCompletionStatus["AudioSourceTimeout"] = 2] = "AudioSourceTimeout";
    RecognitionCompletionStatus[RecognitionCompletionStatus["AuthTokenFetchError"] = 3] = "AuthTokenFetchError";
    RecognitionCompletionStatus[RecognitionCompletionStatus["AuthTokenFetchTimeout"] = 4] = "AuthTokenFetchTimeout";
    RecognitionCompletionStatus[RecognitionCompletionStatus["UnAuthorized"] = 5] = "UnAuthorized";
    RecognitionCompletionStatus[RecognitionCompletionStatus["ConnectTimeout"] = 6] = "ConnectTimeout";
    RecognitionCompletionStatus[RecognitionCompletionStatus["ConnectError"] = 7] = "ConnectError";
    RecognitionCompletionStatus[RecognitionCompletionStatus["ClientRecognitionActivityTimeout"] = 8] = "ClientRecognitionActivityTimeout";
    RecognitionCompletionStatus[RecognitionCompletionStatus["UnknownError"] = 9] = "UnknownError";
})(RecognitionCompletionStatus = exports.RecognitionCompletionStatus || (exports.RecognitionCompletionStatus = {}));
var RecognitionEndedEvent = /** @class */ (function (_super) {
    __extends(RecognitionEndedEvent, _super);
    function RecognitionEndedEvent(requestId, audioSourceId, audioNodeId, authFetchEventId, sessionId, serviceTag, status, error) {
        var _this = _super.call(this, "RecognitionEndedEvent", requestId, sessionId, status === RecognitionCompletionStatus.Success ? Exports_1.EventType.Info : Exports_1.EventType.Error) || this;
        _this.privAudioSourceId = audioSourceId;
        _this.privAudioNodeId = audioNodeId;
        _this.privAuthFetchEventId = authFetchEventId;
        _this.privStatus = status;
        _this.privError = error;
        _this.privServiceTag = serviceTag;
        return _this;
    }
    Object.defineProperty(RecognitionEndedEvent.prototype, "audioSourceId", {
        get: function () {
            return this.privAudioSourceId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionEndedEvent.prototype, "audioNodeId", {
        get: function () {
            return this.privAudioNodeId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionEndedEvent.prototype, "authFetchEventId", {
        get: function () {
            return this.privAuthFetchEventId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionEndedEvent.prototype, "serviceTag", {
        get: function () {
            return this.privServiceTag;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionEndedEvent.prototype, "status", {
        get: function () {
            return this.privStatus;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognitionEndedEvent.prototype, "error", {
        get: function () {
            return this.privError;
        },
        enumerable: false,
        configurable: true
    });
    return RecognitionEndedEvent;
}(SpeechRecognitionEvent));
exports.RecognitionEndedEvent = RecognitionEndedEvent;



/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceRecognizerBase = void 0;
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(4);
var Exports_3 = __webpack_require__(61);
var Exports_4 = __webpack_require__(53);
var SpeechConnectionMessage_Internal_1 = __webpack_require__(173);
var ServiceRecognizerBase = /** @class */ (function () {
    function ServiceRecognizerBase(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) {
        var _this = this;
        this.privSetTimeout = setTimeout;
        this.privIsLiveAudio = false;
        this.recognizeOverride = undefined;
        this.disconnectOverride = undefined;
        this.receiveMessageOverride = undefined;
        this.sendSpeechContext = function (connection) {
            var speechContextJson = _this.speechContext.toJSON();
            _this.privRequestSession.onSpeechContext();
            if (speechContextJson) {
                return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "speech.context", _this.privRequestSession.requestId, "application/json", speechContextJson));
            }
            return;
        };
        this.sendPrePayloadJSONOverride = undefined;
        this.postConnectImplOverride = undefined;
        this.configConnectionOverride = undefined;
        this.sendSpeechServiceConfig = function (connection, requestSession, SpeechServiceConfigJson) {
            // filter out anything that is not required for the service to work.
            if (ServiceRecognizerBase.telemetryDataEnabled !== true) {
                var withTelemetry = JSON.parse(SpeechServiceConfigJson);
                var replacement = {
                    context: {
                        system: withTelemetry.context.system,
                    },
                };
                SpeechServiceConfigJson = JSON.stringify(replacement);
            }
            if (_this.privRecognizerConfig.parameters.getProperty("TranscriptionService_SingleChannel", "false").toLowerCase() === "true") {
                var json = JSON.parse(SpeechServiceConfigJson);
                json.context.DisableReferenceChannel = "True";
                json.context.MicSpec = "1_0_0";
                SpeechServiceConfigJson = JSON.stringify(json);
            }
            if (SpeechServiceConfigJson) {
                return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "speech.config", requestSession.requestId, "application/json", SpeechServiceConfigJson));
            }
            return;
        };
        if (!authentication) {
            throw new Exports_2.ArgumentNullError("authentication");
        }
        if (!connectionFactory) {
            throw new Exports_2.ArgumentNullError("connectionFactory");
        }
        if (!audioSource) {
            throw new Exports_2.ArgumentNullError("audioSource");
        }
        if (!recognizerConfig) {
            throw new Exports_2.ArgumentNullError("recognizerConfig");
        }
        this.privMustReportEndOfStream = false;
        this.privAuthentication = authentication;
        this.privConnectionFactory = connectionFactory;
        this.privAudioSource = audioSource;
        this.privRecognizerConfig = recognizerConfig;
        this.privIsDisposed = false;
        this.privRecognizer = recognizer;
        this.privRequestSession = new Exports_4.RequestSession(this.privAudioSource.id());
        this.privConnectionEvents = new Exports_2.EventSource();
        this.privServiceEvents = new Exports_2.EventSource();
        this.privDynamicGrammar = new Exports_4.DynamicGrammarBuilder();
        this.privSpeechContext = new Exports_4.SpeechContext(this.privDynamicGrammar);
        this.privAgentConfig = new Exports_4.AgentConfig();
        if (typeof (Blob) !== "undefined" && typeof (Worker) !== "undefined") {
            this.privSetTimeout = Exports_2.Timeout.setTimeout;
        }
        this.connectionEvents.attach(function (connectionEvent) { return __awaiter(_this, void 0, void 0, function () {
            var connectionClosedEvent;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(connectionEvent.name === "ConnectionClosedEvent")) return [3 /*break*/, 2];
                        connectionClosedEvent = connectionEvent;
                        if (!(connectionClosedEvent.statusCode === 1003 ||
                            connectionClosedEvent.statusCode === 1007 ||
                            connectionClosedEvent.statusCode === 1002 ||
                            connectionClosedEvent.statusCode === 4000 ||
                            this.privRequestSession.numConnectionAttempts > this.privRecognizerConfig.maxRetryCount)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.cancelRecognitionLocal(Exports_3.CancellationReason.Error, connectionClosedEvent.statusCode === 1007 ? Exports_3.CancellationErrorCode.BadRequestParameters : Exports_3.CancellationErrorCode.ConnectionFailure, connectionClosedEvent.reason + " websocket error code: " + connectionClosedEvent.statusCode)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        }); });
    }
    Object.defineProperty(ServiceRecognizerBase.prototype, "audioSource", {
        get: function () {
            return this.privAudioSource;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ServiceRecognizerBase.prototype, "speechContext", {
        get: function () {
            return this.privSpeechContext;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ServiceRecognizerBase.prototype, "dynamicGrammar", {
        get: function () {
            return this.privDynamicGrammar;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ServiceRecognizerBase.prototype, "agentConfig", {
        get: function () {
            return this.privAgentConfig;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ServiceRecognizerBase.prototype, "conversationTranslatorToken", {
        set: function (token) {
            this.privRecognizerConfig.parameters.setProperty(Exports_3.PropertyId.ConversationTranslator_Token, token);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ServiceRecognizerBase.prototype, "authentication", {
        set: function (auth) {
            this.privAuthentication = this.authentication;
        },
        enumerable: false,
        configurable: true
    });
    ServiceRecognizerBase.prototype.isDisposed = function () {
        return this.privIsDisposed;
    };
    ServiceRecognizerBase.prototype.dispose = function (reason) {
        return __awaiter(this, void 0, void 0, function () {
            var connection, error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.privIsDisposed = true;
                        if (!this.privConnectionConfigurationPromise) return [3 /*break*/, 5];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 4, , 5]);
                        return [4 /*yield*/, this.privConnectionConfigurationPromise];
                    case 2:
                        connection = _a.sent();
                        return [4 /*yield*/, connection.dispose(reason)];
                    case 3:
                        _a.sent();
                        return [3 /*break*/, 5];
                    case 4:
                        error_1 = _a.sent();
                        // The connection is in a bad state. But we're trying to kill it, so...
                        return [2 /*return*/];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    Object.defineProperty(ServiceRecognizerBase.prototype, "connectionEvents", {
        get: function () {
            return this.privConnectionEvents;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ServiceRecognizerBase.prototype, "serviceEvents", {
        get: function () {
            return this.privServiceEvents;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ServiceRecognizerBase.prototype, "recognitionMode", {
        get: function () {
            return this.privRecognizerConfig.recognitionMode;
        },
        enumerable: false,
        configurable: true
    });
    ServiceRecognizerBase.prototype.recognize = function (recoMode, successCallback, errorCallBack) {
        return __awaiter(this, void 0, void 0, function () {
            var conPromise, audioNode, audioStreamNode, format, deviceInfo, error_2, error_3, sessionStartEventArgs, messageRetrievalPromise, audioSendPromise;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.recognizeOverride !== undefined) {
                            return [2 /*return*/, this.recognizeOverride(recoMode, successCallback, errorCallBack)];
                        }
                        // Clear the existing configuration promise to force a re-transmission of config and context.
                        this.privConnectionConfigurationPromise = null;
                        this.privRecognizerConfig.recognitionMode = recoMode;
                        this.privSuccessCallback = successCallback;
                        this.privErrorCallback = errorCallBack;
                        this.privRequestSession.startNewRecognition();
                        this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events);
                        conPromise = this.connectImpl();
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 6, , 8]);
                        return [4 /*yield*/, this.audioSource.attach(this.privRequestSession.audioNodeId)];
                    case 2:
                        audioStreamNode = _a.sent();
                        return [4 /*yield*/, this.audioSource.format];
                    case 3:
                        format = _a.sent();
                        return [4 /*yield*/, this.audioSource.deviceInfo];
                    case 4:
                        deviceInfo = _a.sent();
                        this.privIsLiveAudio = deviceInfo.type && deviceInfo.type === Exports_4.type.Microphones;
                        audioNode = new Exports_1.ReplayableAudioNode(audioStreamNode, format.avgBytesPerSec);
                        return [4 /*yield*/, this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false)];
                    case 5:
                        _a.sent();
                        this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo };
                        return [3 /*break*/, 8];
                    case 6:
                        error_2 = _a.sent();
                        return [4 /*yield*/, this.privRequestSession.onStopRecognizing()];
                    case 7:
                        _a.sent();
                        throw error_2;
                    case 8:
                        _a.trys.push([8, 10, , 12]);
                        return [4 /*yield*/, conPromise];
                    case 9:
                        _a.sent();
                        return [3 /*break*/, 12];
                    case 10:
                        error_3 = _a.sent();
                        return [4 /*yield*/, this.cancelRecognitionLocal(Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.ConnectionFailure, error_3)];
                    case 11:
                        _a.sent();
                        return [2 /*return*/];
                    case 12:
                        sessionStartEventArgs = new Exports_3.SessionEventArgs(this.privRequestSession.sessionId);
                        if (!!this.privRecognizer.sessionStarted) {
                            this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs);
                        }
                        messageRetrievalPromise = this.receiveMessage();
                        audioSendPromise = this.sendAudio(audioNode);
                        audioSendPromise.catch(function (error) { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.cancelRecognitionLocal(Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.RuntimeError, error)];
                                    case 1:
                                        _a.sent();
                                        return [2 /*return*/];
                                }
                            });
                        }); });
                        return [2 /*return*/];
                }
            });
        });
    };
    ServiceRecognizerBase.prototype.stopRecognizing = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.privRequestSession.isRecognizing) return [3 /*break*/, 8];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, , 6, 8]);
                        return [4 /*yield*/, this.audioSource.turnOff()];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.sendFinalAudio()];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, this.privRequestSession.onStopRecognizing()];
                    case 4:
                        _a.sent();
                        return [4 /*yield*/, this.privRequestSession.turnCompletionPromise];
                    case 5:
                        _a.sent();
                        return [3 /*break*/, 8];
                    case 6: return [4 /*yield*/, this.privRequestSession.dispose()];
                    case 7:
                        _a.sent();
                        return [7 /*endfinally*/];
                    case 8: return [2 /*return*/];
                }
            });
        });
    };
    ServiceRecognizerBase.prototype.connect = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.connectImpl()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, Promise.resolve()];
                }
            });
        });
    };
    ServiceRecognizerBase.prototype.connectAsync = function (cb, err) {
        this.connectImpl().then(function (connection) {
            try {
                if (!!cb) {
                    cb();
                }
            }
            catch (e) {
                if (!!err) {
                    err(e);
                }
            }
        }, function (reason) {
            try {
                if (!!err) {
                    err(reason);
                }
                /* tslint:disable:no-empty */
            }
            catch (error) {
            }
        });
    };
    ServiceRecognizerBase.prototype.disconnect = function () {
        return __awaiter(this, void 0, void 0, function () {
            var error_4;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.cancelRecognitionLocal(Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.NoError, "Disconnecting")];
                    case 1:
                        _a.sent();
                        if (!(this.disconnectOverride !== undefined)) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.disconnectOverride()];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        _a.trys.push([3, 6, , 7]);
                        return [4 /*yield*/, this.privConnectionPromise];
                    case 4: return [4 /*yield*/, (_a.sent()).dispose()];
                    case 5:
                        _a.sent();
                        return [3 /*break*/, 7];
                    case 6:
                        error_4 = _a.sent();
                        return [3 /*break*/, 7];
                    case 7:
                        this.privConnectionPromise = null;
                        return [2 /*return*/];
                }
            });
        });
    };
    ServiceRecognizerBase.prototype.sendMessage = function (message) { };
    ServiceRecognizerBase.prototype.sendNetworkMessage = function (path, payload) {
        return __awaiter(this, void 0, void 0, function () {
            var type, contentType, connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        type = typeof payload === "string" ? Exports_2.MessageType.Text : Exports_2.MessageType.Binary;
                        contentType = typeof payload === "string" ? "application/json" : "";
                        return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _a.sent();
                        return [2 /*return*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(type, path, this.privRequestSession.requestId, contentType, payload))];
                }
            });
        });
    };
    Object.defineProperty(ServiceRecognizerBase.prototype, "activityTemplate", {
        get: function () { return this.privActivityTemplate; },
        set: function (messagePayload) { this.privActivityTemplate = messagePayload; },
        enumerable: false,
        configurable: true
    });
    ServiceRecognizerBase.prototype.sendTelemetryData = function () {
        return __awaiter(this, void 0, void 0, function () {
            var telemetryData, connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        telemetryData = this.privRequestSession.getTelemetry();
                        if (ServiceRecognizerBase.telemetryDataEnabled !== true ||
                            this.privIsDisposed ||
                            null === telemetryData) {
                            return [2 /*return*/];
                        }
                        if (!!ServiceRecognizerBase.telemetryData) {
                            try {
                                ServiceRecognizerBase.telemetryData(telemetryData);
                                /* tslint:disable:no-empty */
                            }
                            catch (_b) { }
                        }
                        return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _a.sent();
                        return [4 /*yield*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "telemetry", this.privRequestSession.requestId, "application/json", telemetryData))];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    // Cancels recognition.
    ServiceRecognizerBase.prototype.cancelRecognitionLocal = function (cancellationReason, errorCode, error) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!!this.privRequestSession.isRecognizing) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.privRequestSession.onStopRecognizing()];
                    case 1:
                        _a.sent();
                        this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, cancellationReason, errorCode, error);
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    ServiceRecognizerBase.prototype.receiveMessage = function () {
        return __awaiter(this, void 0, void 0, function () {
            var connection, message, connectionMessage, _a, speechStartDetected, speechStartEventArgs, json, speechStopDetected, speechStopEventArgs, sessionStopEventArgs, error_5;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 18, , 19]);
                        if (this.privIsDisposed) {
                            // We're done.
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _b.sent();
                        return [4 /*yield*/, connection.read()];
                    case 2:
                        message = _b.sent();
                        if (this.receiveMessageOverride !== undefined) {
                            return [2 /*return*/, this.receiveMessageOverride()];
                        }
                        // indicates we are draining the queue and it came with no message;
                        if (!message) {
                            if (!this.privRequestSession.isRecognizing) {
                                return [2 /*return*/];
                            }
                            else {
                                return [2 /*return*/, this.receiveMessage()];
                            }
                        }
                        this.privServiceHasSentMessage = true;
                        connectionMessage = SpeechConnectionMessage_Internal_1.SpeechConnectionMessage.fromConnectionMessage(message);
                        if (!(connectionMessage.requestId.toLowerCase() === this.privRequestSession.requestId.toLowerCase())) return [3 /*break*/, 17];
                        _a = connectionMessage.path.toLowerCase();
                        switch (_a) {
                            case "turn.start": return [3 /*break*/, 3];
                            case "speech.startdetected": return [3 /*break*/, 4];
                            case "speech.enddetected": return [3 /*break*/, 5];
                            case "turn.end": return [3 /*break*/, 6];
                        }
                        return [3 /*break*/, 15];
                    case 3:
                        this.privMustReportEndOfStream = true;
                        this.privRequestSession.onServiceTurnStartResponse();
                        return [3 /*break*/, 17];
                    case 4:
                        speechStartDetected = Exports_4.SpeechDetected.fromJSON(connectionMessage.textBody);
                        speechStartEventArgs = new Exports_3.RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId);
                        if (!!this.privRecognizer.speechStartDetected) {
                            this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs);
                        }
                        return [3 /*break*/, 17];
                    case 5:
                        json = void 0;
                        if (connectionMessage.textBody.length > 0) {
                            json = connectionMessage.textBody;
                        }
                        else {
                            // If the request was empty, the JSON returned is empty.
                            json = "{ Offset: 0 }";
                        }
                        speechStopDetected = Exports_4.SpeechDetected.fromJSON(json);
                        // Only shrink the buffers for continuous recognition.
                        // For single shot, the speech.phrase message will come after the speech.end and it should own buffer shrink.
                        if (this.privRecognizerConfig.isContinuousRecognition) {
                            this.privRequestSession.onServiceRecognized(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset);
                        }
                        speechStopEventArgs = new Exports_3.RecognitionEventArgs(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId);
                        if (!!this.privRecognizer.speechEndDetected) {
                            this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs);
                        }
                        return [3 /*break*/, 17];
                    case 6: return [4 /*yield*/, this.sendTelemetryData()];
                    case 7:
                        _b.sent();
                        if (!(this.privRequestSession.isSpeechEnded && this.privMustReportEndOfStream)) return [3 /*break*/, 9];
                        this.privMustReportEndOfStream = false;
                        return [4 /*yield*/, this.cancelRecognitionLocal(Exports_3.CancellationReason.EndOfStream, Exports_3.CancellationErrorCode.NoError, undefined)];
                    case 8:
                        _b.sent();
                        _b.label = 9;
                    case 9:
                        sessionStopEventArgs = new Exports_3.SessionEventArgs(this.privRequestSession.sessionId);
                        return [4 /*yield*/, this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition)];
                    case 10:
                        _b.sent();
                        if (!(!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing)) return [3 /*break*/, 11];
                        if (!!this.privRecognizer.sessionStopped) {
                            this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs);
                        }
                        return [2 /*return*/];
                    case 11: return [4 /*yield*/, this.fetchConnection()];
                    case 12:
                        connection = _b.sent();
                        return [4 /*yield*/, this.sendPrePayloadJSON(connection)];
                    case 13:
                        _b.sent();
                        _b.label = 14;
                    case 14: return [3 /*break*/, 17];
                    case 15: return [4 /*yield*/, this.processTypeSpecificMessages(connectionMessage)];
                    case 16:
                        if (!(_b.sent())) {
                            // here are some messages that the derived class has not processed, dispatch them to connect class
                            if (!!this.privServiceEvents) {
                                this.serviceEvents.onEvent(new Exports_2.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));
                            }
                        }
                        _b.label = 17;
                    case 17: return [2 /*return*/, this.receiveMessage()];
                    case 18:
                        error_5 = _b.sent();
                        return [2 /*return*/, null];
                    case 19: return [2 /*return*/];
                }
            });
        });
    };
    // Encapsulated for derived service recognizers that need to send additional JSON
    ServiceRecognizerBase.prototype.sendPrePayloadJSON = function (connection) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.sendPrePayloadJSONOverride !== undefined) {
                            return [2 /*return*/, this.sendPrePayloadJSONOverride(connection)];
                        }
                        return [4 /*yield*/, this.sendSpeechContext(connection)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.sendWaveHeader(connection)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    ServiceRecognizerBase.prototype.sendWaveHeader = function (connection) {
        return __awaiter(this, void 0, void 0, function () {
            var format;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.audioSource.format];
                    case 1:
                        format = _a.sent();
                        // this.writeBufferToConsole(format.header);
                        return [2 /*return*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Binary, "audio", this.privRequestSession.requestId, "audio/x-wav", format.header))];
                }
            });
        });
    };
    // Establishes a websocket connection to the end point.
    ServiceRecognizerBase.prototype.connectImpl = function () {
        var _this = this;
        if (this.privConnectionPromise) {
            return this.privConnectionPromise.then(function (connection) {
                if (connection.state() === Exports_2.ConnectionState.Disconnected) {
                    _this.privConnectionId = null;
                    _this.privConnectionPromise = null;
                    _this.privServiceHasSentMessage = false;
                    return _this.connectImpl();
                }
                return _this.privConnectionPromise;
            }, function (error) {
                _this.privConnectionId = null;
                _this.privConnectionPromise = null;
                _this.privServiceHasSentMessage = false;
                return _this.connectImpl();
            });
        }
        this.privConnectionPromise = this.retryableConnect();
        // Attach an empty handler to allow the promise to run in the background while
        // other startup events happen. It'll eventually be awaited on.
        this.privConnectionPromise.catch(function () { });
        if (this.postConnectImplOverride !== undefined) {
            return this.postConnectImplOverride(this.privConnectionPromise);
        }
        return this.privConnectionPromise;
    };
    ServiceRecognizerBase.prototype.fetchConnection = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privConnectionConfigurationPromise) {
                            return [2 /*return*/, this.privConnectionConfigurationPromise.then(function (connection) {
                                    if (connection.state() === Exports_2.ConnectionState.Disconnected) {
                                        _this.privConnectionId = null;
                                        _this.privConnectionConfigurationPromise = null;
                                        _this.privServiceHasSentMessage = false;
                                        return _this.fetchConnection();
                                    }
                                    return _this.privConnectionConfigurationPromise;
                                }, function (error) {
                                    _this.privConnectionId = null;
                                    _this.privConnectionConfigurationPromise = null;
                                    _this.privServiceHasSentMessage = false;
                                    return _this.fetchConnection();
                                })];
                        }
                        this.privConnectionConfigurationPromise = this.configureConnection();
                        return [4 /*yield*/, this.privConnectionConfigurationPromise];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    ServiceRecognizerBase.prototype.sendAudio = function (audioStreamNode) {
        return __awaiter(this, void 0, void 0, function () {
            var audioFormat, nextSendTime, fastLaneSizeMs, maxSendUnthrottledBytes, startRecogNumber, readAndUploadCycle;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.audioSource.format];
                    case 1:
                        audioFormat = _a.sent();
                        nextSendTime = Date.now();
                        fastLaneSizeMs = this.privRecognizerConfig.parameters.getProperty("SPEECH-TransmitLengthBeforThrottleMs", "5000");
                        maxSendUnthrottledBytes = audioFormat.avgBytesPerSec / 1000 * parseInt(fastLaneSizeMs, 10);
                        startRecogNumber = this.privRequestSession.recogNumber;
                        readAndUploadCycle = function () { return __awaiter(_this, void 0, void 0, function () {
                            var connection, audioStreamChunk, payload, sendDelay;
                            var _this = this;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        if (!(!this.privIsDisposed &&
                                            !this.privRequestSession.isSpeechEnded &&
                                            this.privRequestSession.isRecognizing &&
                                            this.privRequestSession.recogNumber === startRecogNumber)) return [3 /*break*/, 5];
                                        return [4 /*yield*/, this.fetchConnection()];
                                    case 1:
                                        connection = _a.sent();
                                        return [4 /*yield*/, audioStreamNode.read()];
                                    case 2:
                                        audioStreamChunk = _a.sent();
                                        // we have a new audio chunk to upload.
                                        if (this.privRequestSession.isSpeechEnded) {
                                            // If service already recognized audio end then don't send any more audio
                                            return [2 /*return*/];
                                        }
                                        payload = void 0;
                                        sendDelay = void 0;
                                        if (!audioStreamChunk || audioStreamChunk.isEnd) {
                                            payload = null;
                                            sendDelay = 0;
                                        }
                                        else {
                                            payload = audioStreamChunk.buffer;
                                            this.privRequestSession.onAudioSent(payload.byteLength);
                                            if (maxSendUnthrottledBytes >= this.privRequestSession.bytesSent) {
                                                sendDelay = 0;
                                            }
                                            else {
                                                sendDelay = Math.max(0, nextSendTime - Date.now());
                                            }
                                        }
                                        if (!(0 !== sendDelay)) return [3 /*break*/, 4];
                                        return [4 /*yield*/, this.delay(sendDelay)];
                                    case 3:
                                        _a.sent();
                                        _a.label = 4;
                                    case 4:
                                        if (payload !== null) {
                                            nextSendTime = Date.now() + (payload.byteLength * 1000 / (audioFormat.avgBytesPerSec * 2));
                                        }
                                        // Are we still alive?
                                        if (!this.privIsDisposed &&
                                            !this.privRequestSession.isSpeechEnded &&
                                            this.privRequestSession.isRecognizing &&
                                            this.privRequestSession.recogNumber === startRecogNumber) {
                                            connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Binary, "audio", this.privRequestSession.requestId, null, payload)).catch(function () {
                                                _this.privRequestSession.onServiceTurnEndResponse(_this.privRecognizerConfig.isContinuousRecognition).catch(function () { });
                                            });
                                            if (!(audioStreamChunk === null || audioStreamChunk === void 0 ? void 0 : audioStreamChunk.isEnd)) {
                                                // this.writeBufferToConsole(payload);
                                                // Regardless of success or failure, schedule the next upload.
                                                // If the underlying connection was broken, the next cycle will
                                                // get a new connection and re-transmit missing audio automatically.
                                                return [2 /*return*/, readAndUploadCycle()];
                                            }
                                            else {
                                                // the audio stream has been closed, no need to schedule next
                                                // read-upload cycle.
                                                if (!this.privIsLiveAudio) {
                                                    this.privRequestSession.onSpeechEnded();
                                                }
                                            }
                                        }
                                        _a.label = 5;
                                    case 5: return [2 /*return*/];
                                }
                            });
                        }); };
                        return [2 /*return*/, readAndUploadCycle()];
                }
            });
        });
    };
    ServiceRecognizerBase.prototype.retryableConnect = function () {
        return __awaiter(this, void 0, void 0, function () {
            var isUnAuthorized, sessionId, lastStatusCode, lastReason, authPromise, auth, connection, response;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        isUnAuthorized = false;
                        this.privAuthFetchEventId = Exports_2.createNoDashGuid();
                        sessionId = this.privRequestSession.sessionId;
                        this.privConnectionId = (sessionId !== undefined) ? sessionId : Exports_2.createNoDashGuid();
                        this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId, this.privConnectionId);
                        lastStatusCode = 0;
                        lastReason = "";
                        _a.label = 1;
                    case 1:
                        if (!(this.privRequestSession.numConnectionAttempts <= this.privRecognizerConfig.maxRetryCount)) return [3 /*break*/, 8];
                        authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId);
                        return [4 /*yield*/, authPromise];
                    case 2:
                        auth = _a.sent();
                        return [4 /*yield*/, this.privRequestSession.onAuthCompleted(false)];
                    case 3:
                        _a.sent();
                        connection = this.privConnectionFactory.create(this.privRecognizerConfig, auth, this.privConnectionId);
                        // Attach the telemetry handlers.
                        this.privRequestSession.listenForServiceTelemetry(connection.events);
                        // Attach to the underlying event. No need to hold onto the detach pointers as in the event the connection goes away,
                        // it'll stop sending events.
                        connection.events.attach(function (event) {
                            _this.connectionEvents.onEvent(event);
                        });
                        return [4 /*yield*/, connection.open()];
                    case 4:
                        response = _a.sent();
                        if (!(response.statusCode === 200)) return [3 /*break*/, 6];
                        return [4 /*yield*/, this.privRequestSession.onConnectionEstablishCompleted(response.statusCode)];
                    case 5:
                        _a.sent();
                        return [2 /*return*/, Promise.resolve(connection)];
                    case 6:
                        if (response.statusCode === 1006) {
                            isUnAuthorized = true;
                        }
                        _a.label = 7;
                    case 7:
                        lastStatusCode = response.statusCode;
                        lastReason = response.reason;
                        this.privRequestSession.onRetryConnection();
                        return [3 /*break*/, 1];
                    case 8: return [4 /*yield*/, this.privRequestSession.onConnectionEstablishCompleted(lastStatusCode, lastReason)];
                    case 9:
                        _a.sent();
                        return [2 /*return*/, Promise.reject("Unable to contact server. StatusCode: " + lastStatusCode + ", " + this.privRecognizerConfig.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Endpoint) + " Reason: " + lastReason)];
                }
            });
        });
    };
    ServiceRecognizerBase.prototype.delay = function (delayMs) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this.privSetTimeout(resolve, delayMs);
        });
    };
    ServiceRecognizerBase.prototype.writeBufferToConsole = function (buffer) {
        var out = "Buffer Size: ";
        if (null === buffer) {
            out += "null";
        }
        else {
            var readView = new Uint8Array(buffer);
            out += buffer.byteLength + "\r\n";
            for (var i = 0; i < buffer.byteLength; i++) {
                out += readView[i].toString(16).padStart(2, "0") + " ";
            }
        }
        // tslint:disable-next-line:no-console
        console.info(out);
    };
    ServiceRecognizerBase.prototype.sendFinalAudio = function () {
        return __awaiter(this, void 0, void 0, function () {
            var connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _a.sent();
                        return [4 /*yield*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Binary, "audio", this.privRequestSession.requestId, null, null))];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    // Takes an established websocket connection to the endpoint and sends speech configuration information.
    ServiceRecognizerBase.prototype.configureConnection = function () {
        return __awaiter(this, void 0, void 0, function () {
            var connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.connectImpl()];
                    case 1:
                        connection = _a.sent();
                        if (this.configConnectionOverride !== undefined) {
                            return [2 /*return*/, this.configConnectionOverride(connection)];
                        }
                        return [4 /*yield*/, this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize())];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.sendPrePayloadJSON(connection)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, connection];
                }
            });
        });
    };
    ServiceRecognizerBase.telemetryDataEnabled = true;
    return ServiceRecognizerBase;
}());
exports.ServiceRecognizerBase = ServiceRecognizerBase;



/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechConnectionMessage = void 0;
var Exports_1 = __webpack_require__(4);
var HeaderNames_1 = __webpack_require__(55);
var SpeechConnectionMessage = /** @class */ (function (_super) {
    __extends(SpeechConnectionMessage, _super);
    function SpeechConnectionMessage(messageType, path, requestId, contentType, body, streamId, additionalHeaders, id) {
        var _this = this;
        if (!path) {
            throw new Exports_1.ArgumentNullError("path");
        }
        if (!requestId) {
            throw new Exports_1.ArgumentNullError("requestId");
        }
        var headers = {};
        headers[HeaderNames_1.HeaderNames.Path] = path;
        headers[HeaderNames_1.HeaderNames.RequestId] = requestId;
        headers[HeaderNames_1.HeaderNames.RequestTimestamp] = new Date().toISOString();
        if (contentType) {
            headers[HeaderNames_1.HeaderNames.ContentType] = contentType;
        }
        if (streamId) {
            headers[HeaderNames_1.HeaderNames.RequestStreamId] = streamId;
        }
        if (additionalHeaders) {
            for (var headerName in additionalHeaders) {
                if (headerName) {
                    headers[headerName] = additionalHeaders[headerName];
                }
            }
        }
        if (id) {
            _this = _super.call(this, messageType, body, headers, id) || this;
        }
        else {
            _this = _super.call(this, messageType, body, headers) || this;
        }
        _this.privPath = path;
        _this.privRequestId = requestId;
        _this.privContentType = contentType;
        _this.privStreamId = streamId;
        _this.privAdditionalHeaders = additionalHeaders;
        return _this;
    }
    Object.defineProperty(SpeechConnectionMessage.prototype, "path", {
        get: function () {
            return this.privPath;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConnectionMessage.prototype, "requestId", {
        get: function () {
            return this.privRequestId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConnectionMessage.prototype, "contentType", {
        get: function () {
            return this.privContentType;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConnectionMessage.prototype, "streamId", {
        get: function () {
            return this.privStreamId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechConnectionMessage.prototype, "additionalHeaders", {
        get: function () {
            return this.privAdditionalHeaders;
        },
        enumerable: false,
        configurable: true
    });
    SpeechConnectionMessage.fromConnectionMessage = function (message) {
        var path = null;
        var requestId = null;
        var contentType = null;
        var requestTimestamp = null;
        var streamId = null;
        var additionalHeaders = {};
        if (message.headers) {
            for (var headerName in message.headers) {
                if (headerName) {
                    if (headerName.toLowerCase() === HeaderNames_1.HeaderNames.Path.toLowerCase()) {
                        path = message.headers[headerName];
                    }
                    else if (headerName.toLowerCase() === HeaderNames_1.HeaderNames.RequestId.toLowerCase()) {
                        requestId = message.headers[headerName];
                    }
                    else if (headerName.toLowerCase() === HeaderNames_1.HeaderNames.RequestTimestamp.toLowerCase()) {
                        requestTimestamp = message.headers[headerName];
                    }
                    else if (headerName.toLowerCase() === HeaderNames_1.HeaderNames.ContentType.toLowerCase()) {
                        contentType = message.headers[headerName];
                    }
                    else if (headerName.toLowerCase() === HeaderNames_1.HeaderNames.RequestStreamId.toLowerCase()) {
                        streamId = message.headers[headerName];
                    }
                    else {
                        additionalHeaders[headerName] = message.headers[headerName];
                    }
                }
            }
        }
        return new SpeechConnectionMessage(message.messageType, path, requestId, contentType, message.body, streamId, additionalHeaders, message.id);
    };
    return SpeechConnectionMessage;
}(Exports_1.ConnectionMessage));
exports.SpeechConnectionMessage = SpeechConnectionMessage;



/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.type = exports.connectivity = exports.Device = exports.OS = exports.System = exports.Context = exports.SpeechServiceConfig = exports.RecognizerConfig = exports.SpeechResultFormat = exports.RecognitionMode = void 0;
// tslint:disable:max-classes-per-file
var Exports_1 = __webpack_require__(61);
var RecognitionMode;
(function (RecognitionMode) {
    RecognitionMode[RecognitionMode["Interactive"] = 0] = "Interactive";
    RecognitionMode[RecognitionMode["Conversation"] = 1] = "Conversation";
    RecognitionMode[RecognitionMode["Dictation"] = 2] = "Dictation";
})(RecognitionMode = exports.RecognitionMode || (exports.RecognitionMode = {}));
var SpeechResultFormat;
(function (SpeechResultFormat) {
    SpeechResultFormat[SpeechResultFormat["Simple"] = 0] = "Simple";
    SpeechResultFormat[SpeechResultFormat["Detailed"] = 1] = "Detailed";
})(SpeechResultFormat = exports.SpeechResultFormat || (exports.SpeechResultFormat = {}));
var RecognizerConfig = /** @class */ (function () {
    function RecognizerConfig(speechServiceConfig, parameters) {
        this.privRecognitionMode = RecognitionMode.Interactive;
        this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new SpeechServiceConfig(new Context(null));
        this.privParameters = parameters;
        this.privMaxRetryCount = parseInt(parameters.getProperty("SPEECH-Error-MaxRetryCount", "4"), 10);
    }
    Object.defineProperty(RecognizerConfig.prototype, "parameters", {
        get: function () {
            return this.privParameters;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognizerConfig.prototype, "recognitionMode", {
        get: function () {
            return this.privRecognitionMode;
        },
        set: function (value) {
            this.privRecognitionMode = value;
            this.privRecognitionActivityTimeout = value === RecognitionMode.Interactive ? 8000 : 25000;
            this.privSpeechServiceConfig.Recognition = RecognitionMode[value];
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognizerConfig.prototype, "SpeechServiceConfig", {
        get: function () {
            return this.privSpeechServiceConfig;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognizerConfig.prototype, "recognitionActivityTimeout", {
        get: function () {
            return this.privRecognitionActivityTimeout;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognizerConfig.prototype, "isContinuousRecognition", {
        get: function () {
            return this.privRecognitionMode !== RecognitionMode.Interactive;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognizerConfig.prototype, "autoDetectSourceLanguages", {
        get: function () {
            return this.parameters.getProperty(Exports_1.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, undefined);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RecognizerConfig.prototype, "maxRetryCount", {
        get: function () {
            return this.privMaxRetryCount;
        },
        enumerable: false,
        configurable: true
    });
    return RecognizerConfig;
}());
exports.RecognizerConfig = RecognizerConfig;
// The config is serialized and sent as the Speech.Config
var SpeechServiceConfig = /** @class */ (function () {
    function SpeechServiceConfig(context) {
        var _this = this;
        this.serialize = function () {
            return JSON.stringify(_this, function (key, value) {
                if (value && typeof value === "object") {
                    var replacement = {};
                    for (var k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            replacement[k && k.charAt(0).toLowerCase() + k.substring(1)] = value[k];
                        }
                    }
                    return replacement;
                }
                return value;
            });
        };
        this.context = context;
    }
    Object.defineProperty(SpeechServiceConfig.prototype, "Context", {
        get: function () {
            return this.context;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechServiceConfig.prototype, "Recognition", {
        get: function () {
            return this.recognition;
        },
        set: function (value) {
            this.recognition = value.toLowerCase();
        },
        enumerable: false,
        configurable: true
    });
    return SpeechServiceConfig;
}());
exports.SpeechServiceConfig = SpeechServiceConfig;
var Context = /** @class */ (function () {
    function Context(os) {
        this.system = new System();
        this.os = os;
    }
    return Context;
}());
exports.Context = Context;
var System = /** @class */ (function () {
    function System() {
        // Note: below will be patched for official builds.
        var SPEECHSDK_CLIENTSDK_VERSION = "1.20.0";
        this.name = "SpeechSDK";
        this.version = SPEECHSDK_CLIENTSDK_VERSION;
        this.build = "JavaScript";
        this.lang = "JavaScript";
    }
    return System;
}());
exports.System = System;
var OS = /** @class */ (function () {
    function OS(platform, name, version) {
        this.platform = platform;
        this.name = name;
        this.version = version;
    }
    return OS;
}());
exports.OS = OS;
var Device = /** @class */ (function () {
    function Device(manufacturer, model, version) {
        this.manufacturer = manufacturer;
        this.model = model;
        this.version = version;
    }
    return Device;
}());
exports.Device = Device;
var connectivity;
(function (connectivity) {
    connectivity["Bluetooth"] = "Bluetooth";
    connectivity["Wired"] = "Wired";
    connectivity["WiFi"] = "WiFi";
    connectivity["Cellular"] = "Cellular";
    connectivity["InBuilt"] = "InBuilt";
    connectivity["Unknown"] = "Unknown";
})(connectivity = exports.connectivity || (exports.connectivity = {}));
var type;
(function (type) {
    type["Phone"] = "Phone";
    type["Speaker"] = "Speaker";
    type["Car"] = "Car";
    type["Headset"] = "Headset";
    type["Thermostat"] = "Thermostat";
    type["Microphones"] = "Microphones";
    type["Deskphone"] = "Deskphone";
    type["RemoteControl"] = "RemoteControl";
    type["Unknown"] = "Unknown";
    type["File"] = "File";
    type["Stream"] = "Stream";
})(type = exports.type || (exports.type = {}));



/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebsocketMessageFormatter = void 0;
var Exports_1 = __webpack_require__(4);
var CRLF = "\r\n";
var WebsocketMessageFormatter = /** @class */ (function () {
    function WebsocketMessageFormatter() {
        var _this = this;
        this.toConnectionMessage = function (message) {
            var deferral = new Exports_1.Deferred();
            try {
                if (message.messageType === Exports_1.MessageType.Text) {
                    var textMessage = message.textContent;
                    var headers = {};
                    var body = null;
                    if (textMessage) {
                        var headerBodySplit = textMessage.split("\r\n\r\n");
                        if (headerBodySplit && headerBodySplit.length > 0) {
                            headers = _this.parseHeaders(headerBodySplit[0]);
                            if (headerBodySplit.length > 1) {
                                body = headerBodySplit[1];
                            }
                        }
                    }
                    deferral.resolve(new Exports_1.ConnectionMessage(message.messageType, body, headers, message.id));
                }
                else if (message.messageType === Exports_1.MessageType.Binary) {
                    var binaryMessage = message.binaryContent;
                    var headers = {};
                    var body = null;
                    if (!binaryMessage || binaryMessage.byteLength < 2) {
                        throw new Error("Invalid binary message format. Header length missing.");
                    }
                    var dataView = new DataView(binaryMessage);
                    var headerLength = dataView.getInt16(0);
                    if (binaryMessage.byteLength < headerLength + 2) {
                        throw new Error("Invalid binary message format. Header content missing.");
                    }
                    var headersString = "";
                    for (var i = 0; i < headerLength; i++) {
                        headersString += String.fromCharCode((dataView).getInt8(i + 2));
                    }
                    headers = _this.parseHeaders(headersString);
                    if (binaryMessage.byteLength > headerLength + 2) {
                        body = binaryMessage.slice(2 + headerLength);
                    }
                    deferral.resolve(new Exports_1.ConnectionMessage(message.messageType, body, headers, message.id));
                }
            }
            catch (e) {
                deferral.reject("Error formatting the message. Error: " + e);
            }
            return deferral.promise;
        };
        this.fromConnectionMessage = function (message) {
            var deferral = new Exports_1.Deferred();
            try {
                if (message.messageType === Exports_1.MessageType.Text) {
                    var payload = "" + _this.makeHeaders(message) + CRLF + (message.textBody ? message.textBody : "");
                    deferral.resolve(new Exports_1.RawWebsocketMessage(Exports_1.MessageType.Text, payload, message.id));
                }
                else if (message.messageType === Exports_1.MessageType.Binary) {
                    var headersString = _this.makeHeaders(message);
                    var content = message.binaryBody;
                    var headerBuffer = _this.stringToArrayBuffer(headersString);
                    var headerInt8Array = new Int8Array(headerBuffer);
                    var headerLength = headerInt8Array.byteLength;
                    var payloadInt8Array = new Int8Array(2 + headerLength + (content ? content.byteLength : 0));
                    payloadInt8Array[0] = ((headerLength >> 8) & 0xff);
                    payloadInt8Array[1] = headerLength & 0xff;
                    payloadInt8Array.set(headerInt8Array, 2);
                    if (content) {
                        var bodyInt8Array = new Int8Array(content);
                        payloadInt8Array.set(bodyInt8Array, 2 + headerLength);
                    }
                    var payload = payloadInt8Array.buffer;
                    deferral.resolve(new Exports_1.RawWebsocketMessage(Exports_1.MessageType.Binary, payload, message.id));
                }
            }
            catch (e) {
                deferral.reject("Error formatting the message. " + e);
            }
            return deferral.promise;
        };
        this.makeHeaders = function (message) {
            var headersString = "";
            if (message.headers) {
                for (var header in message.headers) {
                    if (header) {
                        headersString += header + ": " + message.headers[header] + CRLF;
                    }
                }
            }
            return headersString;
        };
        this.parseHeaders = function (headersString) {
            var headers = {};
            if (headersString) {
                var headerMatches = headersString.match(/[^\r\n]+/g);
                if (headers) {
                    for (var _i = 0, headerMatches_1 = headerMatches; _i < headerMatches_1.length; _i++) {
                        var header = headerMatches_1[_i];
                        if (header) {
                            var separatorIndex = header.indexOf(":");
                            var headerName = separatorIndex > 0 ? header.substr(0, separatorIndex).trim().toLowerCase() : header;
                            var headerValue = separatorIndex > 0 && header.length > (separatorIndex + 1) ?
                                header.substr(separatorIndex + 1).trim() :
                                "";
                            headers[headerName] = headerValue;
                        }
                    }
                }
            }
            return headers;
        };
        this.stringToArrayBuffer = function (str) {
            var buffer = new ArrayBuffer(str.length);
            var view = new DataView(buffer);
            for (var i = 0; i < str.length; i++) {
                view.setUint8(i, str.charCodeAt(i));
            }
            return buffer;
        };
    }
    return WebsocketMessageFormatter;
}());
exports.WebsocketMessageFormatter = WebsocketMessageFormatter;



/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechConnectionFactory = void 0;
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(53);
var Exports_3 = __webpack_require__(61);
var ConnectionFactoryBase_1 = __webpack_require__(123);
var Exports_4 = __webpack_require__(53);
var HeaderNames_1 = __webpack_require__(55);
var QueryParameterNames_1 = __webpack_require__(124);
var SpeechConnectionFactory = /** @class */ (function (_super) {
    __extends(SpeechConnectionFactory, _super);
    function SpeechConnectionFactory() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.interactiveRelativeUri = "/speech/recognition/interactive/cognitiveservices/v1";
        _this.conversationRelativeUri = "/speech/recognition/conversation/cognitiveservices/v1";
        _this.dictationRelativeUri = "/speech/recognition/dictation/cognitiveservices/v1";
        _this.create = function (config, authInfo, connectionId) {
            var endpoint = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Endpoint, undefined);
            var region = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Region, undefined);
            var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region);
            var host = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".stt.speech" + hostSuffix);
            var queryParams = {};
            var endpointId = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_EndpointId, undefined);
            var language = config.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage, undefined);
            if (endpointId) {
                if (!endpoint || endpoint.search(QueryParameterNames_1.QueryParameterNames.CustomSpeechDeploymentId) === -1) {
                    queryParams[QueryParameterNames_1.QueryParameterNames.CustomSpeechDeploymentId] = endpointId;
                }
            }
            else if (language) {
                if (!endpoint || endpoint.search(QueryParameterNames_1.QueryParameterNames.Language) === -1) {
                    queryParams[QueryParameterNames_1.QueryParameterNames.Language] = language;
                }
            }
            if (!endpoint || endpoint.search(QueryParameterNames_1.QueryParameterNames.Format) === -1) {
                queryParams[QueryParameterNames_1.QueryParameterNames.Format] = config.parameters.getProperty(Exports_2.OutputFormatPropertyName, Exports_3.OutputFormat[Exports_3.OutputFormat.Simple]).toLowerCase();
            }
            if (config.autoDetectSourceLanguages !== undefined) {
                queryParams[QueryParameterNames_1.QueryParameterNames.EnableLanguageId] = "true";
            }
            _this.setCommonUrlParams(config, queryParams, endpoint);
            if (!endpoint) {
                switch (config.recognitionMode) {
                    case Exports_4.RecognitionMode.Conversation:
                        if (config.parameters.getProperty(Exports_2.ForceDictationPropertyName, "false") === "true") {
                            endpoint = host + _this.dictationRelativeUri;
                        }
                        else {
                            endpoint = host + _this.conversationRelativeUri;
                        }
                        break;
                    case Exports_4.RecognitionMode.Dictation:
                        endpoint = host + _this.dictationRelativeUri;
                        break;
                    default:
                        endpoint = host + _this.interactiveRelativeUri; // default is interactive
                        break;
                }
            }
            var headers = {};
            if (authInfo.token !== undefined && authInfo.token !== "") {
                headers[authInfo.headerName] = authInfo.token;
            }
            headers[HeaderNames_1.HeaderNames.ConnectionId] = connectionId;
            config.parameters.setProperty(Exports_3.PropertyId.SpeechServiceConnection_Url, endpoint);
            var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
            return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_4.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);
        };
        return _this;
    }
    return SpeechConnectionFactory;
}(ConnectionFactoryBase_1.ConnectionFactoryBase));
exports.SpeechConnectionFactory = SpeechConnectionFactory;



/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranscriberConnectionFactory = void 0;
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(61);
var ConnectionFactoryBase_1 = __webpack_require__(123);
var Exports_3 = __webpack_require__(53);
var HeaderNames_1 = __webpack_require__(55);
var QueryParameterNames_1 = __webpack_require__(124);
var TranscriberConnectionFactory = /** @class */ (function (_super) {
    __extends(TranscriberConnectionFactory, _super);
    function TranscriberConnectionFactory() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.multiaudioRelativeUri = "/speech/recognition/multiaudio";
        _this.create = function (config, authInfo, connectionId) {
            var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, undefined);
            var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, "centralus");
            var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region);
            var hostDefault = "wss://transcribe." + region + ".cts.speech" + hostSuffix + _this.multiaudioRelativeUri;
            var host = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, hostDefault);
            var queryParams = {};
            var endpointId = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId, undefined);
            var language = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage, undefined);
            if (endpointId) {
                if (!endpoint || endpoint.search(QueryParameterNames_1.QueryParameterNames.CustomSpeechDeploymentId) === -1) {
                    queryParams[QueryParameterNames_1.QueryParameterNames.CustomSpeechDeploymentId] = endpointId;
                }
            }
            else if (language) {
                if (!endpoint || endpoint.search(QueryParameterNames_1.QueryParameterNames.Language) === -1) {
                    queryParams[QueryParameterNames_1.QueryParameterNames.Language] = language;
                }
            }
            _this.setCommonUrlParams(config, queryParams, endpoint);
            if (!endpoint) {
                endpoint = host;
            }
            var headers = {};
            if (authInfo.token !== undefined && authInfo.token !== "") {
                headers[authInfo.headerName] = authInfo.token;
            }
            headers[HeaderNames_1.HeaderNames.ConnectionId] = connectionId;
            config.parameters.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Url, endpoint);
            var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
            return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_3.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);
        };
        return _this;
    }
    return TranscriberConnectionFactory;
}(ConnectionFactoryBase_1.ConnectionFactoryBase));
exports.TranscriberConnectionFactory = TranscriberConnectionFactory;



/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationConnectionFactory = void 0;
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(61);
var ConnectionFactoryBase_1 = __webpack_require__(123);
var Exports_3 = __webpack_require__(53);
var HeaderNames_1 = __webpack_require__(55);
var QueryParameterNames_1 = __webpack_require__(124);
var TranslationConnectionFactory = /** @class */ (function (_super) {
    __extends(TranslationConnectionFactory, _super);
    function TranslationConnectionFactory() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.create = function (config, authInfo, connectionId) {
            var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, undefined);
            if (!endpoint) {
                var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, undefined);
                var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region);
                var host = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".s2s.speech" + hostSuffix);
                endpoint = host + "/speech/translation/cognitiveservices/v1";
            }
            var queryParams = {
                from: config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage),
                to: config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationToLanguages),
            };
            _this.setCommonUrlParams(config, queryParams, endpoint);
            _this.setUrlParameter(Exports_2.PropertyId.SpeechServiceResponse_TranslationRequestStablePartialResult, QueryParameterNames_1.QueryParameterNames.StableTranslation, config, queryParams, endpoint);
            var voiceName = "voice";
            var featureName = "features";
            if (config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationVoice, undefined) !== undefined) {
                queryParams[voiceName] = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_TranslationVoice);
                queryParams[featureName] = "texttospeech";
            }
            var headers = {};
            if (authInfo.token !== undefined && authInfo.token !== "") {
                headers[authInfo.headerName] = authInfo.token;
            }
            headers[HeaderNames_1.HeaderNames.ConnectionId] = connectionId;
            config.parameters.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Url, endpoint);
            var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
            return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_3.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);
        };
        return _this;
    }
    return TranslationConnectionFactory;
}(ConnectionFactoryBase_1.ConnectionFactoryBase));
exports.TranslationConnectionFactory = TranslationConnectionFactory;



/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisConnectionFactory = void 0;
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(61);
var ConnectionFactoryBase_1 = __webpack_require__(123);
var Exports_3 = __webpack_require__(53);
var HeaderNames_1 = __webpack_require__(55);
var QueryParameterNames_1 = __webpack_require__(124);
var SpeechSynthesisConnectionFactory = /** @class */ (function () {
    function SpeechSynthesisConnectionFactory() {
        var _this = this;
        this.synthesisUri = "/cognitiveservices/websocket/v1";
        this.create = function (config, authInfo, connectionId) {
            var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, undefined);
            var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, undefined);
            var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region);
            var endpointId = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_EndpointId, undefined);
            var hostPrefix = (endpointId === undefined) ? "tts" : "voice";
            var host = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + "." + hostPrefix + ".speech" + hostSuffix);
            var queryParams = {};
            if (!endpoint) {
                endpoint = host + _this.synthesisUri;
            }
            var headers = {};
            if (authInfo.token !== undefined && authInfo.token !== "") {
                headers[authInfo.headerName] = authInfo.token;
            }
            headers[HeaderNames_1.HeaderNames.ConnectionId] = connectionId;
            if (endpointId !== undefined) {
                headers[QueryParameterNames_1.QueryParameterNames.CustomVoiceDeploymentId] = endpointId;
            }
            config.parameters.setProperty(Exports_2.PropertyId.SpeechServiceConnection_Url, endpoint);
            var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
            return new Exports_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_3.WebsocketMessageFormatter(), Exports_1.ProxyInfo.fromParameters(config.parameters), enableCompression, connectionId);
        };
    }
    return SpeechSynthesisConnectionFactory;
}());
exports.SpeechSynthesisConnectionFactory = SpeechSynthesisConnectionFactory;



/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnumTranslation = void 0;
var Exports_1 = __webpack_require__(61);
var Exports_2 = __webpack_require__(53);
var EnumTranslation = /** @class */ (function () {
    function EnumTranslation() {
    }
    EnumTranslation.implTranslateRecognitionResult = function (recognitionStatus) {
        var reason = Exports_1.ResultReason.Canceled;
        switch (recognitionStatus) {
            case Exports_2.RecognitionStatus.Success:
                reason = Exports_1.ResultReason.RecognizedSpeech;
                break;
            case Exports_2.RecognitionStatus.NoMatch:
            case Exports_2.RecognitionStatus.InitialSilenceTimeout:
            case Exports_2.RecognitionStatus.BabbleTimeout:
            case Exports_2.RecognitionStatus.EndOfDictation:
                reason = Exports_1.ResultReason.NoMatch;
                break;
            case Exports_2.RecognitionStatus.Error:
            case Exports_2.RecognitionStatus.BadRequest:
            case Exports_2.RecognitionStatus.Forbidden:
            default:
                reason = Exports_1.ResultReason.Canceled;
                break;
        }
        return reason;
    };
    EnumTranslation.implTranslateCancelResult = function (recognitionStatus) {
        var reason = Exports_1.CancellationReason.EndOfStream;
        switch (recognitionStatus) {
            case Exports_2.RecognitionStatus.Success:
            case Exports_2.RecognitionStatus.EndOfDictation:
            case Exports_2.RecognitionStatus.NoMatch:
                reason = Exports_1.CancellationReason.EndOfStream;
                break;
            case Exports_2.RecognitionStatus.InitialSilenceTimeout:
            case Exports_2.RecognitionStatus.BabbleTimeout:
            case Exports_2.RecognitionStatus.Error:
            case Exports_2.RecognitionStatus.BadRequest:
            case Exports_2.RecognitionStatus.Forbidden:
            default:
                reason = Exports_1.CancellationReason.Error;
                break;
        }
        return reason;
    };
    EnumTranslation.implTranslateCancelErrorCode = function (recognitionStatus) {
        var reason = Exports_1.CancellationErrorCode.NoError;
        switch (recognitionStatus) {
            case Exports_2.RecognitionStatus.Error:
                reason = Exports_1.CancellationErrorCode.ServiceError;
                break;
            case Exports_2.RecognitionStatus.TooManyRequests:
                reason = Exports_1.CancellationErrorCode.TooManyRequests;
                break;
            case Exports_2.RecognitionStatus.BadRequest:
                reason = Exports_1.CancellationErrorCode.BadRequestParameters;
                break;
            case Exports_2.RecognitionStatus.Forbidden:
                reason = Exports_1.CancellationErrorCode.Forbidden;
                break;
            default:
                reason = Exports_1.CancellationErrorCode.NoError;
                break;
        }
        return reason;
    };
    EnumTranslation.implTranslateErrorDetails = function (cancellationErrorCode) {
        var errorDetails = "The speech service encountered an internal error and could not continue.";
        switch (cancellationErrorCode) {
            case Exports_1.CancellationErrorCode.Forbidden:
                errorDetails = "The recognizer is using a free subscription that ran out of quota.";
                break;
            case Exports_1.CancellationErrorCode.BadRequestParameters:
                errorDetails = "Invalid parameter or unsupported audio format in the request.";
                break;
            case Exports_1.CancellationErrorCode.TooManyRequests:
                errorDetails = "The number of parallel requests exceeded the number of allowed concurrent transcriptions.";
                break;
            default:
                break;
        }
        return errorDetails;
    };
    return EnumTranslation;
}());
exports.EnumTranslation = EnumTranslation;



/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecognitionStatus = exports.SynthesisStatus = void 0;
/**
 * @class SynthesisStatus
 * @private
 */
var SynthesisStatus;
(function (SynthesisStatus) {
    /**
     * The response contains valid audio data.
     * @member SynthesisStatus.Success
     */
    SynthesisStatus[SynthesisStatus["Success"] = 0] = "Success";
    /**
     * Indicates the end of audio data. No valid audio data is included in the message.
     * @member SynthesisStatus.SynthesisEnd
     */
    SynthesisStatus[SynthesisStatus["SynthesisEnd"] = 1] = "SynthesisEnd";
    /**
     * Indicates an error occurred during synthesis data processing.
     * @member SynthesisStatus.Error
     */
    SynthesisStatus[SynthesisStatus["Error"] = 2] = "Error";
})(SynthesisStatus = exports.SynthesisStatus || (exports.SynthesisStatus = {}));
var RecognitionStatus;
(function (RecognitionStatus) {
    RecognitionStatus[RecognitionStatus["Success"] = 0] = "Success";
    RecognitionStatus[RecognitionStatus["NoMatch"] = 1] = "NoMatch";
    RecognitionStatus[RecognitionStatus["InitialSilenceTimeout"] = 2] = "InitialSilenceTimeout";
    RecognitionStatus[RecognitionStatus["BabbleTimeout"] = 3] = "BabbleTimeout";
    RecognitionStatus[RecognitionStatus["Error"] = 4] = "Error";
    RecognitionStatus[RecognitionStatus["EndOfDictation"] = 5] = "EndOfDictation";
    RecognitionStatus[RecognitionStatus["TooManyRequests"] = 6] = "TooManyRequests";
    RecognitionStatus[RecognitionStatus["BadRequest"] = 7] = "BadRequest";
    RecognitionStatus[RecognitionStatus["Forbidden"] = 8] = "Forbidden";
})(RecognitionStatus = exports.RecognitionStatus || (exports.RecognitionStatus = {}));



/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationSynthesisEnd = void 0;
var Exports_1 = __webpack_require__(53);
var TranslationSynthesisEnd = /** @class */ (function () {
    function TranslationSynthesisEnd(json) {
        this.privSynthesisEnd = JSON.parse(json);
        this.privSynthesisEnd.SynthesisStatus = Exports_1.SynthesisStatus[this.privSynthesisEnd.SynthesisStatus];
    }
    TranslationSynthesisEnd.fromJSON = function (json) {
        return new TranslationSynthesisEnd(json);
    };
    Object.defineProperty(TranslationSynthesisEnd.prototype, "SynthesisStatus", {
        get: function () {
            return this.privSynthesisEnd.SynthesisStatus;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationSynthesisEnd.prototype, "FailureReason", {
        get: function () {
            return this.privSynthesisEnd.FailureReason;
        },
        enumerable: false,
        configurable: true
    });
    return TranslationSynthesisEnd;
}());
exports.TranslationSynthesisEnd = TranslationSynthesisEnd;



/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationHypothesis = void 0;
var TranslationStatus_1 = __webpack_require__(45);
var TranslationHypothesis = /** @class */ (function () {
    function TranslationHypothesis(json) {
        this.privTranslationHypothesis = JSON.parse(json);
        this.privTranslationHypothesis.Translation.TranslationStatus = TranslationStatus_1.TranslationStatus[this.privTranslationHypothesis.Translation.TranslationStatus];
    }
    TranslationHypothesis.fromJSON = function (json) {
        return new TranslationHypothesis(json);
    };
    Object.defineProperty(TranslationHypothesis.prototype, "Duration", {
        get: function () {
            return this.privTranslationHypothesis.Duration;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationHypothesis.prototype, "Offset", {
        get: function () {
            return this.privTranslationHypothesis.Offset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationHypothesis.prototype, "Text", {
        get: function () {
            return this.privTranslationHypothesis.Text;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationHypothesis.prototype, "Translation", {
        get: function () {
            return this.privTranslationHypothesis.Translation;
        },
        enumerable: false,
        configurable: true
    });
    return TranslationHypothesis;
}());
exports.TranslationHypothesis = TranslationHypothesis;



/***/ }),
/* 185 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationPhrase = void 0;
var Contracts_1 = __webpack_require__(63);
var Exports_1 = __webpack_require__(53);
var TranslationStatus_1 = __webpack_require__(45);
var TranslationPhrase = /** @class */ (function () {
    function TranslationPhrase(phrase) {
        this.privTranslationPhrase = phrase;
        this.privTranslationPhrase.RecognitionStatus = Exports_1.RecognitionStatus[this.privTranslationPhrase.RecognitionStatus];
        if (this.privTranslationPhrase.Translation !== undefined) {
            this.privTranslationPhrase.Translation.TranslationStatus = TranslationStatus_1.TranslationStatus[this.privTranslationPhrase.Translation.TranslationStatus];
        }
    }
    TranslationPhrase.fromJSON = function (json) {
        return new TranslationPhrase(JSON.parse(json));
    };
    TranslationPhrase.fromTranslationResponse = function (translationResponse) {
        Contracts_1.Contracts.throwIfNullOrUndefined(translationResponse, "translationResponse");
        var phrase = translationResponse.SpeechPhrase;
        translationResponse.SpeechPhrase = undefined;
        phrase.Translation = translationResponse;
        phrase.Text = phrase.DisplayText;
        return new TranslationPhrase(phrase);
    };
    Object.defineProperty(TranslationPhrase.prototype, "RecognitionStatus", {
        get: function () {
            return this.privTranslationPhrase.RecognitionStatus;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationPhrase.prototype, "Offset", {
        get: function () {
            return this.privTranslationPhrase.Offset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationPhrase.prototype, "Duration", {
        get: function () {
            return this.privTranslationPhrase.Duration;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationPhrase.prototype, "Text", {
        get: function () {
            return this.privTranslationPhrase.Text;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranslationPhrase.prototype, "Translation", {
        get: function () {
            return this.privTranslationPhrase.Translation;
        },
        enumerable: false,
        configurable: true
    });
    return TranslationPhrase;
}());
exports.TranslationPhrase = TranslationPhrase;



/***/ }),
/* 186 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationServiceRecognizer = void 0;
var Exports_1 = __webpack_require__(4);
var Exports_2 = __webpack_require__(61);
var Exports_3 = __webpack_require__(53);
// tslint:disable-next-line:max-classes-per-file
var TranslationServiceRecognizer = /** @class */ (function (_super) {
    __extends(TranslationServiceRecognizer, _super);
    function TranslationServiceRecognizer(authentication, connectionFactory, audioSource, recognizerConfig, translationRecognizer) {
        var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, translationRecognizer) || this;
        _this.privTranslationRecognizer = translationRecognizer;
        _this.connectionEvents.attach(function (connectionEvent) { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(connectionEvent.name === "ConnectionEstablishedEvent")) return [3 /*break*/, 1];
                        this.privTranslationRecognizer.onConnection();
                        return [3 /*break*/, 3];
                    case 1:
                        if (!(connectionEvent.name === "ConnectionClosedEvent")) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.privTranslationRecognizer.onDisconnection()];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        }); });
        return _this;
    }
    TranslationServiceRecognizer.prototype.processTypeSpecificMessages = function (connectionMessage) {
        return __awaiter(this, void 0, void 0, function () {
            var resultProps, processed, handleTranslationPhrase, _a, result, phrase, synthEnd, result_1, retEvent, canceledResult;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        resultProps = new Exports_2.PropertyCollection();
                        processed = false;
                        handleTranslationPhrase = function (translatedPhrase) { return __awaiter(_this, void 0, void 0, function () {
                            var result, reason, result, cancelReason, cancellationErrorCode, ev;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + translatedPhrase.Offset + translatedPhrase.Duration);
                                        if (!(translatedPhrase.RecognitionStatus === Exports_3.RecognitionStatus.Success)) return [3 /*break*/, 1];
                                        result = this.fireEventForResult(translatedPhrase, resultProps);
                                        if (!!this.privTranslationRecognizer.recognized) {
                                            try {
                                                this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, result);
                                                /* tslint:disable:no-empty */
                                            }
                                            catch (error) {
                                                // Not going to let errors in the event handler
                                                // trip things up.
                                            }
                                        }
                                        // report result to promise.
                                        if (!!this.privSuccessCallback) {
                                            try {
                                                this.privSuccessCallback(result.result);
                                            }
                                            catch (e) {
                                                if (!!this.privErrorCallback) {
                                                    this.privErrorCallback(e);
                                                }
                                            }
                                            // Only invoke the call back once.
                                            // and if it's successful don't invoke the
                                            // error after that.
                                            this.privSuccessCallback = undefined;
                                            this.privErrorCallback = undefined;
                                        }
                                        return [3 /*break*/, 5];
                                    case 1:
                                        reason = Exports_3.EnumTranslation.implTranslateRecognitionResult(translatedPhrase.RecognitionStatus);
                                        result = new Exports_2.TranslationRecognitionResult(undefined, this.privRequestSession.requestId, reason, translatedPhrase.Text, translatedPhrase.Duration, this.privRequestSession.currentTurnAudioOffset + translatedPhrase.Offset, undefined, connectionMessage.textBody, resultProps);
                                        if (!(reason === Exports_2.ResultReason.Canceled)) return [3 /*break*/, 3];
                                        cancelReason = Exports_3.EnumTranslation.implTranslateCancelResult(translatedPhrase.RecognitionStatus);
                                        cancellationErrorCode = Exports_3.EnumTranslation.implTranslateCancelErrorCode(translatedPhrase.RecognitionStatus);
                                        return [4 /*yield*/, this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_3.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode))];
                                    case 2:
                                        _a.sent();
                                        return [3 /*break*/, 4];
                                    case 3:
                                        if (!(this.privRequestSession.isSpeechEnded && reason === Exports_2.ResultReason.NoMatch && translatedPhrase.RecognitionStatus !== Exports_3.RecognitionStatus.InitialSilenceTimeout)) {
                                            ev = new Exports_2.TranslationRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);
                                            if (!!this.privTranslationRecognizer.recognized) {
                                                try {
                                                    this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, ev);
                                                    /* tslint:disable:no-empty */
                                                }
                                                catch (error) {
                                                    // Not going to let errors in the event handler
                                                    // trip things up.
                                                }
                                            }
                                        }
                                        // report result to promise.
                                        if (!!this.privSuccessCallback) {
                                            try {
                                                this.privSuccessCallback(result);
                                            }
                                            catch (e) {
                                                if (!!this.privErrorCallback) {
                                                    this.privErrorCallback(e);
                                                }
                                            }
                                            // Only invoke the call back once.
                                            // and if it's successful don't invoke the
                                            // error after that.
                                            this.privSuccessCallback = undefined;
                                            this.privErrorCallback = undefined;
                                        }
                                        _a.label = 4;
                                    case 4:
                                        processed = true;
                                        _a.label = 5;
                                    case 5: return [2 /*return*/];
                                }
                            });
                        }); };
                        if (connectionMessage.messageType === Exports_1.MessageType.Text) {
                            resultProps.setProperty(Exports_2.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
                        }
                        _a = connectionMessage.path.toLowerCase();
                        switch (_a) {
                            case "translation.hypothesis": return [3 /*break*/, 1];
                            case "translation.response": return [3 /*break*/, 2];
                            case "translation.phrase": return [3 /*break*/, 5];
                            case "translation.synthesis": return [3 /*break*/, 7];
                            case "translation.synthesis.end": return [3 /*break*/, 8];
                        }
                        return [3 /*break*/, 9];
                    case 1:
                        result = this.fireEventForResult(Exports_3.TranslationHypothesis.fromJSON(connectionMessage.textBody), resultProps);
                        this.privRequestSession.onHypothesis(this.privRequestSession.currentTurnAudioOffset + result.offset);
                        if (!!this.privTranslationRecognizer.recognizing) {
                            try {
                                this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer, result);
                                /* tslint:disable:no-empty */
                            }
                            catch (error) {
                                // Not going to let errors in the event handler
                                // trip things up.
                            }
                        }
                        processed = true;
                        return [3 /*break*/, 10];
                    case 2:
                        phrase = JSON.parse(connectionMessage.textBody);
                        if (!!!phrase.SpeechPhrase) return [3 /*break*/, 4];
                        return [4 /*yield*/, handleTranslationPhrase(Exports_3.TranslationPhrase.fromTranslationResponse(phrase))];
                    case 3:
                        _b.sent();
                        _b.label = 4;
                    case 4: return [3 /*break*/, 10];
                    case 5: return [4 /*yield*/, handleTranslationPhrase(Exports_3.TranslationPhrase.fromJSON(connectionMessage.textBody))];
                    case 6:
                        _b.sent();
                        return [3 /*break*/, 10];
                    case 7:
                        this.sendSynthesisAudio(connectionMessage.binaryBody, this.privRequestSession.sessionId);
                        processed = true;
                        return [3 /*break*/, 10];
                    case 8:
                        synthEnd = Exports_3.TranslationSynthesisEnd.fromJSON(connectionMessage.textBody);
                        switch (synthEnd.SynthesisStatus) {
                            case Exports_3.SynthesisStatus.Error:
                                if (!!this.privTranslationRecognizer.synthesizing) {
                                    result_1 = new Exports_2.TranslationSynthesisResult(Exports_2.ResultReason.Canceled, undefined);
                                    retEvent = new Exports_2.TranslationSynthesisEventArgs(result_1, this.privRequestSession.sessionId);
                                    try {
                                        this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent);
                                        /* tslint:disable:no-empty */
                                    }
                                    catch (error) {
                                        // Not going to let errors in the event handler
                                        // trip things up.
                                    }
                                }
                                if (!!this.privTranslationRecognizer.canceled) {
                                    canceledResult = new Exports_2.TranslationRecognitionCanceledEventArgs(this.privRequestSession.sessionId, Exports_2.CancellationReason.Error, synthEnd.FailureReason, Exports_2.CancellationErrorCode.ServiceError, null);
                                    try {
                                        this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, canceledResult);
                                        /* tslint:disable:no-empty */
                                    }
                                    catch (error) {
                                        // Not going to let errors in the event handler
                                        // trip things up.
                                    }
                                }
                                break;
                            case Exports_3.SynthesisStatus.Success:
                                this.sendSynthesisAudio(undefined, this.privRequestSession.sessionId);
                                break;
                            default:
                                break;
                        }
                        processed = true;
                        return [3 /*break*/, 10];
                    case 9: return [3 /*break*/, 10];
                    case 10: return [2 /*return*/, processed];
                }
            });
        });
    };
    // Cancels recognition.
    TranslationServiceRecognizer.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) {
        var properties = new Exports_2.PropertyCollection();
        properties.setProperty(Exports_3.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[errorCode]);
        if (!!this.privTranslationRecognizer.canceled) {
            var cancelEvent = new Exports_2.TranslationRecognitionCanceledEventArgs(sessionId, cancellationReason, error, errorCode, undefined);
            try {
                this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, cancelEvent);
                /* tslint:disable:no-empty */
            }
            catch (_a) { }
        }
        if (!!this.privSuccessCallback) {
            var result = new Exports_2.TranslationRecognitionResult(undefined, // Translations
            requestId, Exports_2.ResultReason.Canceled, undefined, // Text
            undefined, // Druation
            undefined, // Offset
            error, undefined, // Json
            properties);
            try {
                this.privSuccessCallback(result);
                /* tslint:disable:no-empty */
                this.privSuccessCallback = undefined;
            }
            catch (_b) { }
        }
    };
    TranslationServiceRecognizer.prototype.fireEventForResult = function (serviceResult, properties) {
        var translations;
        if (undefined !== serviceResult.Translation.Translations) {
            translations = new Exports_2.Translations();
            for (var _i = 0, _a = serviceResult.Translation.Translations; _i < _a.length; _i++) {
                var translation = _a[_i];
                translations.set(translation.Language, translation.Text || translation.DisplayText);
            }
        }
        var resultReason;
        if (serviceResult instanceof Exports_3.TranslationPhrase) {
            if (serviceResult.Translation.TranslationStatus === Exports_1.TranslationStatus.Success) {
                resultReason = Exports_2.ResultReason.TranslatedSpeech;
            }
            else {
                resultReason = Exports_2.ResultReason.RecognizedSpeech;
            }
        }
        else {
            resultReason = Exports_2.ResultReason.TranslatingSpeech;
        }
        var offset = serviceResult.Offset + this.privRequestSession.currentTurnAudioOffset;
        var result = new Exports_2.TranslationRecognitionResult(translations, this.privRequestSession.requestId, resultReason, serviceResult.Text, serviceResult.Duration, offset, serviceResult.Translation.FailureReason, JSON.stringify(serviceResult), properties);
        var ev = new Exports_2.TranslationRecognitionEventArgs(result, offset, this.privRequestSession.sessionId);
        return ev;
    };
    TranslationServiceRecognizer.prototype.sendSynthesisAudio = function (audio, sessionId) {
        var reason = (undefined === audio) ? Exports_2.ResultReason.SynthesizingAudioCompleted : Exports_2.ResultReason.SynthesizingAudio;
        var result = new Exports_2.TranslationSynthesisResult(reason, audio);
        var retEvent = new Exports_2.TranslationSynthesisEventArgs(result, sessionId);
        if (!!this.privTranslationRecognizer.synthesizing) {
            try {
                this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent);
                /* tslint:disable:no-empty */
            }
            catch (error) {
                // Not going to let errors in the event handler
                // trip things up.
            }
        }
    };
    return TranslationServiceRecognizer;
}(Exports_3.ServiceRecognizerBase));
exports.TranslationServiceRecognizer = TranslationServiceRecognizer;



/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechDetected = void 0;
var SpeechDetected = /** @class */ (function () {
    function SpeechDetected(json) {
        this.privSpeechStartDetected = JSON.parse(json);
    }
    SpeechDetected.fromJSON = function (json) {
        return new SpeechDetected(json);
    };
    Object.defineProperty(SpeechDetected.prototype, "Offset", {
        get: function () {
            return this.privSpeechStartDetected.Offset;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechDetected;
}());
exports.SpeechDetected = SpeechDetected;



/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechHypothesis = void 0;
var SpeechHypothesis = /** @class */ (function () {
    function SpeechHypothesis(json) {
        this.privSpeechHypothesis = JSON.parse(json);
    }
    SpeechHypothesis.fromJSON = function (json) {
        return new SpeechHypothesis(json);
    };
    Object.defineProperty(SpeechHypothesis.prototype, "Text", {
        get: function () {
            return this.privSpeechHypothesis.Text;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechHypothesis.prototype, "Offset", {
        get: function () {
            return this.privSpeechHypothesis.Offset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechHypothesis.prototype, "Duration", {
        get: function () {
            return this.privSpeechHypothesis.Duration;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechHypothesis.prototype, "Language", {
        get: function () {
            return this.privSpeechHypothesis.PrimaryLanguage === undefined ? undefined : this.privSpeechHypothesis.PrimaryLanguage.Language;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechHypothesis.prototype, "LanguageDetectionConfidence", {
        get: function () {
            return this.privSpeechHypothesis.PrimaryLanguage === undefined ? undefined : this.privSpeechHypothesis.PrimaryLanguage.Confidence;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechHypothesis.prototype, "SpeakerId", {
        get: function () {
            return this.privSpeechHypothesis.SpeakerId;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechHypothesis;
}());
exports.SpeechHypothesis = SpeechHypothesis;



/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechKeyword = void 0;
var SpeechKeyword = /** @class */ (function () {
    function SpeechKeyword(json) {
        this.privSpeechKeyword = JSON.parse(json);
    }
    SpeechKeyword.fromJSON = function (json) {
        return new SpeechKeyword(json);
    };
    Object.defineProperty(SpeechKeyword.prototype, "Status", {
        get: function () {
            return this.privSpeechKeyword.Status;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechKeyword.prototype, "Text", {
        get: function () {
            return this.privSpeechKeyword.Text;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechKeyword.prototype, "Offset", {
        get: function () {
            return this.privSpeechKeyword.Offset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechKeyword.prototype, "Duration", {
        get: function () {
            return this.privSpeechKeyword.Duration;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechKeyword;
}());
exports.SpeechKeyword = SpeechKeyword;



/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechServiceRecognizer = void 0;
var Exports_1 = __webpack_require__(61);
var Exports_2 = __webpack_require__(53);
// tslint:disable-next-line:max-classes-per-file
var SpeechServiceRecognizer = /** @class */ (function (_super) {
    __extends(SpeechServiceRecognizer, _super);
    function SpeechServiceRecognizer(authentication, connectionFactory, audioSource, recognizerConfig, speechRecognizer) {
        var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, speechRecognizer) || this;
        _this.privSpeechRecognizer = speechRecognizer;
        if (recognizerConfig.autoDetectSourceLanguages !== undefined) {
            var sourceLanguages = recognizerConfig.autoDetectSourceLanguages.split(",");
            _this.privSpeechContext.setSection("languageId", {
                languages: sourceLanguages,
                onSuccess: { action: "Recognize" },
                onUnknown: { action: "None" }
            });
            _this.privSpeechContext.setSection("phraseOutput", {
                interimResults: {
                    resultType: "Auto"
                },
                phraseResults: {
                    resultType: "Always"
                }
            });
        }
        return _this;
    }
    SpeechServiceRecognizer.prototype.processTypeSpecificMessages = function (connectionMessage) {
        return __awaiter(this, void 0, void 0, function () {
            var result, resultProps, processed, _a, hypothesis, offset, ev, simple, resultReason, cancelReason, cancellationErrorCode, detailed, totalOffset, offsetCorrectedJson, event_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        resultProps = new Exports_1.PropertyCollection();
                        resultProps.setProperty(Exports_1.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
                        processed = false;
                        _a = connectionMessage.path.toLowerCase();
                        switch (_a) {
                            case "speech.hypothesis": return [3 /*break*/, 1];
                            case "speech.fragment": return [3 /*break*/, 1];
                            case "speech.phrase": return [3 /*break*/, 2];
                        }
                        return [3 /*break*/, 6];
                    case 1:
                        hypothesis = Exports_2.SpeechHypothesis.fromJSON(connectionMessage.textBody);
                        offset = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset;
                        result = new Exports_1.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_1.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, undefined, // Speaker Id
                        undefined, connectionMessage.textBody, resultProps);
                        this.privRequestSession.onHypothesis(offset);
                        ev = new Exports_1.SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId);
                        if (!!this.privSpeechRecognizer.recognizing) {
                            try {
                                this.privSpeechRecognizer.recognizing(this.privSpeechRecognizer, ev);
                                /* tslint:disable:no-empty */
                            }
                            catch (error) {
                                // Not going to let errors in the event handler
                                // trip things up.
                            }
                        }
                        processed = true;
                        return [3 /*break*/, 7];
                    case 2:
                        simple = Exports_2.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);
                        resultReason = Exports_2.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus);
                        this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + simple.Offset + simple.Duration);
                        if (!(Exports_1.ResultReason.Canceled === resultReason)) return [3 /*break*/, 4];
                        cancelReason = Exports_2.EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus);
                        cancellationErrorCode = Exports_2.EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus);
                        return [4 /*yield*/, this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_2.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode))];
                    case 3:
                        _b.sent();
                        return [3 /*break*/, 5];
                    case 4:
                        if (!(this.privRequestSession.isSpeechEnded && resultReason === Exports_1.ResultReason.NoMatch && simple.RecognitionStatus !== Exports_2.RecognitionStatus.InitialSilenceTimeout)) {
                            if (this.privRecognizerConfig.parameters.getProperty(Exports_2.OutputFormatPropertyName) === Exports_1.OutputFormat[Exports_1.OutputFormat.Simple]) {
                                result = new Exports_1.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, simple.DisplayText, simple.Duration, simple.Offset + this.privRequestSession.currentTurnAudioOffset, simple.Language, simple.LanguageDetectionConfidence, undefined, // Speaker Id
                                undefined, connectionMessage.textBody, resultProps);
                            }
                            else {
                                detailed = Exports_2.DetailedSpeechPhrase.fromJSON(connectionMessage.textBody);
                                totalOffset = detailed.Offset + this.privRequestSession.currentTurnAudioOffset;
                                offsetCorrectedJson = detailed.getJsonWithCorrectedOffsets(totalOffset);
                                result = new Exports_1.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, detailed.RecognitionStatus === Exports_2.RecognitionStatus.Success ? detailed.NBest[0].Display : undefined, detailed.Duration, totalOffset, detailed.Language, detailed.LanguageDetectionConfidence, undefined, // Speaker Id
                                undefined, offsetCorrectedJson, resultProps);
                            }
                            event_1 = new Exports_1.SpeechRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);
                            if (!!this.privSpeechRecognizer.recognized) {
                                try {
                                    this.privSpeechRecognizer.recognized(this.privSpeechRecognizer, event_1);
                                    /* tslint:disable:no-empty */
                                }
                                catch (error) {
                                    // Not going to let errors in the event handler
                                    // trip things up.
                                }
                            }
                        }
                        if (!!this.privSuccessCallback) {
                            try {
                                this.privSuccessCallback(result);
                            }
                            catch (e) {
                                if (!!this.privErrorCallback) {
                                    this.privErrorCallback(e);
                                }
                            }
                            // Only invoke the call back once.
                            // and if it's successful don't invoke the
                            // error after that.
                            this.privSuccessCallback = undefined;
                            this.privErrorCallback = undefined;
                        }
                        _b.label = 5;
                    case 5:
                        processed = true;
                        return [3 /*break*/, 7];
                    case 6: return [3 /*break*/, 7];
                    case 7: return [2 /*return*/, processed];
                }
            });
        });
    };
    // Cancels recognition.
    SpeechServiceRecognizer.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) {
        var properties = new Exports_1.PropertyCollection();
        properties.setProperty(Exports_2.CancellationErrorCodePropertyName, Exports_1.CancellationErrorCode[errorCode]);
        if (!!this.privSpeechRecognizer.canceled) {
            var cancelEvent = new Exports_1.SpeechRecognitionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId);
            try {
                this.privSpeechRecognizer.canceled(this.privSpeechRecognizer, cancelEvent);
                /* tslint:disable:no-empty */
            }
            catch (_a) { }
        }
        if (!!this.privSuccessCallback) {
            var result = new Exports_1.SpeechRecognitionResult(requestId, Exports_1.ResultReason.Canceled, undefined, // Text
            undefined, // Duration
            undefined, // Offset
            undefined, // Language
            undefined, // Language Detection Confidence
            undefined, // Speaker Id
            error, undefined, // Json
            properties);
            try {
                this.privSuccessCallback(result);
                this.privSuccessCallback = undefined;
                /* tslint:disable:no-empty */
            }
            catch (_b) { }
        }
    };
    return SpeechServiceRecognizer;
}(Exports_2.ServiceRecognizerBase));
exports.SpeechServiceRecognizer = SpeechServiceRecognizer;



/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranscriptionServiceRecognizer = void 0;
var Exports_1 = __webpack_require__(4);
var Exports_2 = __webpack_require__(61);
var Exports_3 = __webpack_require__(53);
var SpeechConnectionMessage_Internal_1 = __webpack_require__(173);
// tslint:disable-next-line:max-classes-per-file
var TranscriptionServiceRecognizer = /** @class */ (function (_super) {
    __extends(TranscriptionServiceRecognizer, _super);
    function TranscriptionServiceRecognizer(authentication, connectionFactory, audioSource, recognizerConfig, transcriber) {
        var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, transcriber) || this;
        _this.sendSpeechEvent = function (connection, payload) {
            var speechEventJson = JSON.stringify(payload);
            if (speechEventJson) {
                return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_1.MessageType.Text, "speech.event", _this.privRequestSession.requestId, "application/json", speechEventJson));
            }
            return;
        };
        _this.privTranscriberRecognizer = transcriber;
        _this.sendPrePayloadJSONOverride = _this.sendTranscriptionStartJSON;
        return _this;
    }
    TranscriptionServiceRecognizer.prototype.sendSpeechEventAsync = function (info, command) {
        return __awaiter(this, void 0, void 0, function () {
            var connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!!this.privRequestSession.isRecognizing) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _a.sent();
                        return [4 /*yield*/, this.sendSpeechEvent(connection, this.createSpeechEventPayload(info, command))];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    TranscriptionServiceRecognizer.prototype.processTypeSpecificMessages = function (connectionMessage) {
        return __awaiter(this, void 0, void 0, function () {
            var result, resultProps, processed, _a, hypothesis, offset, ev, simple, resultReason, cancelReason, cancellationErrorCode, detailed, totalOffset, offsetCorrectedJson, event_1;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        resultProps = new Exports_2.PropertyCollection();
                        resultProps.setProperty(Exports_2.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
                        processed = false;
                        _a = connectionMessage.path.toLowerCase();
                        switch (_a) {
                            case "speech.hypothesis": return [3 /*break*/, 1];
                            case "speech.fragment": return [3 /*break*/, 1];
                            case "speech.phrase": return [3 /*break*/, 2];
                        }
                        return [3 /*break*/, 6];
                    case 1:
                        hypothesis = Exports_3.SpeechHypothesis.fromJSON(connectionMessage.textBody);
                        offset = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset;
                        result = new Exports_2.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_2.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, hypothesis.SpeakerId, undefined, connectionMessage.textBody, resultProps);
                        this.privRequestSession.onHypothesis(offset);
                        ev = new Exports_2.SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId);
                        if (!!this.privTranscriberRecognizer.recognizing) {
                            try {
                                this.privTranscriberRecognizer.recognizing(this.privTranscriberRecognizer, ev);
                                /* tslint:disable:no-empty */
                            }
                            catch (error) {
                                // Not going to let errors in the event handler
                                // trip things up.
                            }
                        }
                        processed = true;
                        return [3 /*break*/, 7];
                    case 2:
                        simple = Exports_3.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);
                        resultReason = Exports_3.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus);
                        this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + simple.Offset + simple.Duration);
                        if (!(Exports_2.ResultReason.Canceled === resultReason)) return [3 /*break*/, 4];
                        cancelReason = Exports_3.EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus);
                        cancellationErrorCode = Exports_3.EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus);
                        return [4 /*yield*/, this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_3.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode))];
                    case 3:
                        _b.sent();
                        return [3 /*break*/, 5];
                    case 4:
                        if (!(this.privRequestSession.isSpeechEnded && resultReason === Exports_2.ResultReason.NoMatch && simple.RecognitionStatus !== Exports_3.RecognitionStatus.InitialSilenceTimeout)) {
                            if (this.privRecognizerConfig.parameters.getProperty(Exports_3.OutputFormatPropertyName) === Exports_2.OutputFormat[Exports_2.OutputFormat.Simple]) {
                                result = new Exports_2.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, simple.DisplayText, simple.Duration, simple.Offset + this.privRequestSession.currentTurnAudioOffset, simple.Language, simple.LanguageDetectionConfidence, simple.SpeakerId, undefined, connectionMessage.textBody, resultProps);
                            }
                            else {
                                detailed = Exports_3.DetailedSpeechPhrase.fromJSON(connectionMessage.textBody);
                                totalOffset = detailed.Offset + this.privRequestSession.currentTurnAudioOffset;
                                offsetCorrectedJson = detailed.getJsonWithCorrectedOffsets(totalOffset);
                                result = new Exports_2.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, detailed.Text, detailed.Duration, totalOffset, detailed.Language, detailed.LanguageDetectionConfidence, detailed.SpeakerId, undefined, offsetCorrectedJson, resultProps);
                            }
                            event_1 = new Exports_2.SpeechRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);
                            if (!!this.privTranscriberRecognizer.recognized) {
                                try {
                                    this.privTranscriberRecognizer.recognized(this.privTranscriberRecognizer, event_1);
                                    /* tslint:disable:no-empty */
                                }
                                catch (error) {
                                    // Not going to let errors in the event handler
                                    // trip things up.
                                }
                            }
                        }
                        if (!!this.privSuccessCallback) {
                            try {
                                this.privSuccessCallback(result);
                            }
                            catch (e) {
                                if (!!this.privErrorCallback) {
                                    this.privErrorCallback(e);
                                }
                            }
                            // Only invoke the call back once.
                            // and if it's successful don't invoke the
                            // error after that.
                            this.privSuccessCallback = undefined;
                            this.privErrorCallback = undefined;
                        }
                        _b.label = 5;
                    case 5:
                        processed = true;
                        return [3 /*break*/, 7];
                    case 6: return [3 /*break*/, 7];
                    case 7: return [2 /*return*/, processed];
                }
            });
        });
    };
    // Cancels recognition.
    TranscriptionServiceRecognizer.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) {
        var properties = new Exports_2.PropertyCollection();
        properties.setProperty(Exports_3.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[errorCode]);
        if (!!this.privTranscriberRecognizer.canceled) {
            var cancelEvent = new Exports_2.ConversationTranscriptionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId);
            try {
                this.privTranscriberRecognizer.canceled(this.privTranscriberRecognizer, cancelEvent);
                /* tslint:disable:no-empty */
            }
            catch (_a) { }
        }
        if (!!this.privSuccessCallback) {
            var result = new Exports_2.SpeechRecognitionResult(requestId, Exports_2.ResultReason.Canceled, undefined, // Text
            undefined, // Duration
            undefined, // Offset
            undefined, // Language
            undefined, // Language Detection Confidence
            undefined, // Speaker Id
            error, undefined, // Json
            properties);
            try {
                this.privSuccessCallback(result);
                this.privSuccessCallback = undefined;
                /* tslint:disable:no-empty */
            }
            catch (_b) { }
        }
    };
    // Encapsulated for derived service recognizers that need to send additional JSON
    TranscriptionServiceRecognizer.prototype.sendTranscriptionStartJSON = function (connection) {
        return __awaiter(this, void 0, void 0, function () {
            var info, payload;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.sendSpeechContext(connection)];
                    case 1:
                        _a.sent();
                        info = this.privTranscriberRecognizer.getConversationInfo();
                        payload = this.createSpeechEventPayload(info, "start");
                        return [4 /*yield*/, this.sendSpeechEvent(connection, payload)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.sendWaveHeader(connection)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    TranscriptionServiceRecognizer.prototype.createSpeechEventPayload = function (info, command) {
        var meeting = "meeting";
        var eventDict = { id: meeting, name: command, meeting: info.conversationProperties };
        var idString = "id";
        var attendees = "attendees";
        var record = "record";
        eventDict[meeting][idString] = info.id;
        eventDict[meeting][attendees] = info.participants;
        eventDict[meeting][record] = info.conversationProperties.audiorecording === "on" ? "true" : "false";
        return eventDict;
    };
    return TranscriptionServiceRecognizer;
}(Exports_3.ServiceRecognizerBase));
exports.TranscriptionServiceRecognizer = TranscriptionServiceRecognizer;



/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.DetailedSpeechPhrase = void 0;
var Exports_1 = __webpack_require__(53);
var DetailedSpeechPhrase = /** @class */ (function () {
    function DetailedSpeechPhrase(json) {
        this.privDetailedSpeechPhrase = JSON.parse(json);
        this.privDetailedSpeechPhrase.RecognitionStatus = Exports_1.RecognitionStatus[this.privDetailedSpeechPhrase.RecognitionStatus];
    }
    DetailedSpeechPhrase.fromJSON = function (json) {
        return new DetailedSpeechPhrase(json);
    };
    DetailedSpeechPhrase.prototype.getJsonWithCorrectedOffsets = function (baseOffset) {
        if (!!this.privDetailedSpeechPhrase.NBest) {
            var firstWordOffset = void 0;
            for (var _i = 0, _a = this.privDetailedSpeechPhrase.NBest; _i < _a.length; _i++) {
                var phrase = _a[_i];
                if (!!phrase.Words && !!phrase.Words[0]) {
                    firstWordOffset = phrase.Words[0].Offset;
                    break;
                }
            }
            if (!!firstWordOffset && firstWordOffset < baseOffset) {
                var offset = baseOffset - firstWordOffset;
                for (var _b = 0, _c = this.privDetailedSpeechPhrase.NBest; _b < _c.length; _b++) {
                    var details = _c[_b];
                    if (!!details.Words) {
                        for (var _d = 0, _e = details.Words; _d < _e.length; _d++) {
                            var word = _e[_d];
                            word.Offset += offset;
                        }
                    }
                }
            }
        }
        return JSON.stringify(this.privDetailedSpeechPhrase);
    };
    Object.defineProperty(DetailedSpeechPhrase.prototype, "RecognitionStatus", {
        get: function () {
            return this.privDetailedSpeechPhrase.RecognitionStatus;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DetailedSpeechPhrase.prototype, "NBest", {
        get: function () {
            return this.privDetailedSpeechPhrase.NBest;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DetailedSpeechPhrase.prototype, "Duration", {
        get: function () {
            return this.privDetailedSpeechPhrase.Duration;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DetailedSpeechPhrase.prototype, "Offset", {
        get: function () {
            return this.privDetailedSpeechPhrase.Offset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DetailedSpeechPhrase.prototype, "Language", {
        get: function () {
            return this.privDetailedSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privDetailedSpeechPhrase.PrimaryLanguage.Language;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DetailedSpeechPhrase.prototype, "LanguageDetectionConfidence", {
        get: function () {
            return this.privDetailedSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privDetailedSpeechPhrase.PrimaryLanguage.Confidence;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DetailedSpeechPhrase.prototype, "Text", {
        get: function () {
            return !!this.privDetailedSpeechPhrase.NBest && this.privDetailedSpeechPhrase.NBest[0] ? this.privDetailedSpeechPhrase.NBest[0].Display : this.privDetailedSpeechPhrase.DisplayText;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DetailedSpeechPhrase.prototype, "SpeakerId", {
        get: function () {
            return this.privDetailedSpeechPhrase.SpeakerId;
        },
        enumerable: false,
        configurable: true
    });
    return DetailedSpeechPhrase;
}());
exports.DetailedSpeechPhrase = DetailedSpeechPhrase;



/***/ }),
/* 193 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleSpeechPhrase = void 0;
var Exports_1 = __webpack_require__(53);
var SimpleSpeechPhrase = /** @class */ (function () {
    function SimpleSpeechPhrase(json) {
        this.privSimpleSpeechPhrase = JSON.parse(json);
        this.privSimpleSpeechPhrase.RecognitionStatus = Exports_1.RecognitionStatus[this.privSimpleSpeechPhrase.RecognitionStatus];
    }
    SimpleSpeechPhrase.fromJSON = function (json) {
        return new SimpleSpeechPhrase(json);
    };
    Object.defineProperty(SimpleSpeechPhrase.prototype, "RecognitionStatus", {
        get: function () {
            return this.privSimpleSpeechPhrase.RecognitionStatus;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SimpleSpeechPhrase.prototype, "DisplayText", {
        get: function () {
            return this.privSimpleSpeechPhrase.DisplayText;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SimpleSpeechPhrase.prototype, "Offset", {
        get: function () {
            return this.privSimpleSpeechPhrase.Offset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SimpleSpeechPhrase.prototype, "Duration", {
        get: function () {
            return this.privSimpleSpeechPhrase.Duration;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SimpleSpeechPhrase.prototype, "Language", {
        get: function () {
            return this.privSimpleSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privSimpleSpeechPhrase.PrimaryLanguage.Language;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SimpleSpeechPhrase.prototype, "LanguageDetectionConfidence", {
        get: function () {
            return this.privSimpleSpeechPhrase.PrimaryLanguage === undefined ? undefined : this.privSimpleSpeechPhrase.PrimaryLanguage.Confidence;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SimpleSpeechPhrase.prototype, "SpeakerId", {
        get: function () {
            return this.privSimpleSpeechPhrase.SpeakerId;
        },
        enumerable: false,
        configurable: true
    });
    return SimpleSpeechPhrase;
}());
exports.SimpleSpeechPhrase = SimpleSpeechPhrase;



/***/ }),
/* 194 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AddedLmIntent = void 0;
/**
 * @class AddedLmIntent
 */
// tslint:disable-next-line:max-classes-per-file
var AddedLmIntent = /** @class */ (function () {
    /**
     * Creates and initializes an instance of this class.
     * @constructor
     * @param modelImpl - The model.
     * @param intentName - The intent name.
     */
    function AddedLmIntent(modelImpl, intentName) {
        this.modelImpl = modelImpl;
        this.intentName = intentName;
    }
    return AddedLmIntent;
}());
exports.AddedLmIntent = AddedLmIntent;



/***/ }),
/* 195 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentServiceRecognizer = void 0;
var Exports_1 = __webpack_require__(4);
var Exports_2 = __webpack_require__(61);
var Exports_3 = __webpack_require__(53);
// tslint:disable-next-line:max-classes-per-file
var IntentServiceRecognizer = /** @class */ (function (_super) {
    __extends(IntentServiceRecognizer, _super);
    function IntentServiceRecognizer(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) {
        var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, recognizer) || this;
        _this.privIntentRecognizer = recognizer;
        _this.privIntentDataSent = false;
        return _this;
    }
    IntentServiceRecognizer.prototype.setIntents = function (addedIntents, umbrellaIntent) {
        this.privAddedLmIntents = addedIntents;
        this.privUmbrellaIntent = umbrellaIntent;
        this.privIntentDataSent = true;
    };
    IntentServiceRecognizer.prototype.processTypeSpecificMessages = function (connectionMessage) {
        return __awaiter(this, void 0, void 0, function () {
            var result, ev, processed, resultProps, speechHypothesis, simple, sendEvent, intentResponse, addedIntent, intentId, reason, properties;
            var _this = this;
            return __generator(this, function (_a) {
                processed = false;
                resultProps = new Exports_2.PropertyCollection();
                if (connectionMessage.messageType === Exports_1.MessageType.Text) {
                    resultProps.setProperty(Exports_2.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
                }
                switch (connectionMessage.path.toLowerCase()) {
                    case "speech.hypothesis":
                        speechHypothesis = Exports_3.SpeechHypothesis.fromJSON(connectionMessage.textBody);
                        result = new Exports_2.IntentRecognitionResult(undefined, this.privRequestSession.requestId, Exports_2.ResultReason.RecognizingIntent, speechHypothesis.Text, speechHypothesis.Duration, speechHypothesis.Offset + this.privRequestSession.currentTurnAudioOffset, speechHypothesis.Language, speechHypothesis.LanguageDetectionConfidence, undefined, connectionMessage.textBody, resultProps);
                        this.privRequestSession.onHypothesis(result.offset);
                        ev = new Exports_2.IntentRecognitionEventArgs(result, speechHypothesis.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId);
                        if (!!this.privIntentRecognizer.recognizing) {
                            try {
                                this.privIntentRecognizer.recognizing(this.privIntentRecognizer, ev);
                                /* tslint:disable:no-empty */
                            }
                            catch (error) {
                                // Not going to let errors in the event handler
                                // trip things up.
                            }
                        }
                        processed = true;
                        break;
                    case "speech.phrase":
                        simple = Exports_3.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);
                        result = new Exports_2.IntentRecognitionResult(undefined, this.privRequestSession.requestId, Exports_3.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus), simple.DisplayText, simple.Duration, simple.Offset + this.privRequestSession.currentTurnAudioOffset, simple.Language, simple.LanguageDetectionConfidence, undefined, connectionMessage.textBody, resultProps);
                        ev = new Exports_2.IntentRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);
                        sendEvent = function () {
                            if (!!_this.privIntentRecognizer.recognized) {
                                try {
                                    _this.privIntentRecognizer.recognized(_this.privIntentRecognizer, ev);
                                    /* tslint:disable:no-empty */
                                }
                                catch (error) {
                                    // Not going to let errors in the event handler
                                    // trip things up.
                                }
                            }
                            // report result to promise.
                            if (!!_this.privSuccessCallback) {
                                try {
                                    _this.privSuccessCallback(result);
                                }
                                catch (e) {
                                    if (!!_this.privErrorCallback) {
                                        _this.privErrorCallback(e);
                                    }
                                }
                                // Only invoke the call back once.
                                // and if it's successful don't invoke the
                                // error after that.
                                _this.privSuccessCallback = undefined;
                                _this.privErrorCallback = undefined;
                            }
                        };
                        // If intent data was sent, the terminal result for this recognizer is an intent being found.
                        // If no intent data was sent, the terminal event is speech recognition being successful.
                        if (false === this.privIntentDataSent || Exports_2.ResultReason.NoMatch === ev.result.reason) {
                            // Advance the buffers.
                            this.privRequestSession.onPhraseRecognized(ev.offset + ev.result.duration);
                            sendEvent();
                        }
                        else {
                            // Squirrel away the args, when the response event arrives it will build upon them
                            // and then return
                            this.privPendingIntentArgs = ev;
                        }
                        processed = true;
                        break;
                    case "response":
                        // Response from LUIS
                        ev = this.privPendingIntentArgs;
                        this.privPendingIntentArgs = undefined;
                        if (undefined === ev) {
                            if ("" === connectionMessage.textBody) {
                                // This condition happens if there is nothing but silence in the
                                // audio sent to the service.
                                return [2 /*return*/];
                            }
                            // Odd... Not sure this can happen
                            ev = new Exports_2.IntentRecognitionEventArgs(new Exports_2.IntentRecognitionResult(), 0 /*TODO*/, this.privRequestSession.sessionId);
                        }
                        intentResponse = Exports_3.IntentResponse.fromJSON(connectionMessage.textBody);
                        addedIntent = this.privAddedLmIntents[intentResponse.topScoringIntent.intent];
                        if (this.privUmbrellaIntent !== undefined) {
                            addedIntent = this.privUmbrellaIntent;
                        }
                        if (null !== intentResponse && addedIntent !== undefined) {
                            intentId = addedIntent.intentName === undefined ? intentResponse.topScoringIntent.intent : addedIntent.intentName;
                            reason = ev.result.reason;
                            if (undefined !== intentId) {
                                reason = Exports_2.ResultReason.RecognizedIntent;
                            }
                            properties = (undefined !== ev.result.properties) ?
                                ev.result.properties : new Exports_2.PropertyCollection();
                            properties.setProperty(Exports_2.PropertyId.LanguageUnderstandingServiceResponse_JsonResult, connectionMessage.textBody);
                            ev = new Exports_2.IntentRecognitionEventArgs(new Exports_2.IntentRecognitionResult(intentId, ev.result.resultId, reason, ev.result.text, ev.result.duration, ev.result.offset, undefined, undefined, ev.result.errorDetails, ev.result.json, properties), ev.offset, ev.sessionId);
                        }
                        this.privRequestSession.onPhraseRecognized(ev.offset + ev.result.duration);
                        if (!!this.privIntentRecognizer.recognized) {
                            try {
                                this.privIntentRecognizer.recognized(this.privIntentRecognizer, ev);
                                /* tslint:disable:no-empty */
                            }
                            catch (error) {
                                // Not going to let errors in the event handler
                                // trip things up.
                            }
                        }
                        // report result to promise.
                        if (!!this.privSuccessCallback) {
                            try {
                                this.privSuccessCallback(ev.result);
                            }
                            catch (e) {
                                if (!!this.privErrorCallback) {
                                    this.privErrorCallback(e);
                                }
                            }
                            // Only invoke the call back once.
                            // and if it's successful don't invoke the
                            // error after that.
                            this.privSuccessCallback = undefined;
                            this.privErrorCallback = undefined;
                        }
                        processed = true;
                        break;
                    default:
                        break;
                }
                return [2 /*return*/, processed];
            });
        });
    };
    // Cancels recognition.
    IntentServiceRecognizer.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) {
        var properties = new Exports_2.PropertyCollection();
        properties.setProperty(Exports_3.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[errorCode]);
        if (!!this.privIntentRecognizer.canceled) {
            var cancelEvent = new Exports_2.IntentRecognitionCanceledEventArgs(cancellationReason, error, errorCode, undefined, undefined, sessionId);
            try {
                this.privIntentRecognizer.canceled(this.privIntentRecognizer, cancelEvent);
                /* tslint:disable:no-empty */
            }
            catch (_a) { }
        }
        if (!!this.privSuccessCallback) {
            var result = new Exports_2.IntentRecognitionResult(undefined, // Intent Id
            requestId, Exports_2.ResultReason.Canceled, undefined, // Text
            undefined, // Duration
            undefined, // Offset
            undefined, // Language
            undefined, // LanguageDetectionConfidence
            error, undefined, // Json
            properties);
            try {
                this.privSuccessCallback(result);
                this.privSuccessCallback = undefined;
                /* tslint:disable:no-empty */
            }
            catch (_b) { }
        }
    };
    return IntentServiceRecognizer;
}(Exports_3.ServiceRecognizerBase));
exports.IntentServiceRecognizer = IntentServiceRecognizer;



/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// response
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentResponse = void 0;
var IntentResponse = /** @class */ (function () {
    function IntentResponse(json) {
        this.privIntentResponse = JSON.parse(json);
    }
    IntentResponse.fromJSON = function (json) {
        return new IntentResponse(json);
    };
    Object.defineProperty(IntentResponse.prototype, "query", {
        get: function () {
            return this.privIntentResponse.query;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(IntentResponse.prototype, "topScoringIntent", {
        get: function () {
            return this.privIntentResponse.topScoringIntent;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(IntentResponse.prototype, "entities", {
        get: function () {
            return this.privIntentResponse.entities;
        },
        enumerable: false,
        configurable: true
    });
    return IntentResponse;
}());
exports.IntentResponse = IntentResponse;



/***/ }),
/* 197 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestSession = void 0;
var Exports_1 = __webpack_require__(4);
var RecognitionEvents_1 = __webpack_require__(171);
var ServiceTelemetryListener_Internal_1 = __webpack_require__(198);
var RequestSession = /** @class */ (function () {
    function RequestSession(audioSourceId) {
        var _this = this;
        this.privIsDisposed = false;
        this.privDetachables = new Array();
        this.privIsAudioNodeDetached = false;
        this.privIsRecognizing = false;
        this.privIsSpeechEnded = false;
        this.privTurnStartAudioOffset = 0;
        this.privLastRecoOffset = 0;
        this.privHypothesisReceived = false;
        this.privBytesSent = 0;
        this.privRecogNumber = 0;
        this.privInTurn = false;
        this.privConnectionAttempts = 0;
        this.onPreConnectionStart = function (authFetchEventId, connectionId) {
            _this.privAuthFetchEventId = authFetchEventId;
            _this.privSessionId = connectionId;
            _this.onEvent(new RecognitionEvents_1.ConnectingToServiceEvent(_this.privRequestId, _this.privAuthFetchEventId, _this.privSessionId));
        };
        this.onSpeechContext = function () {
            _this.privRequestId = Exports_1.createNoDashGuid();
        };
        this.onServiceTurnStartResponse = function () {
            if (!!_this.privTurnDeferral && !!_this.privInTurn) {
                // What? How are we starting a turn with another not done?
                _this.privTurnDeferral.reject("Another turn started before current completed.");
                // Avoid UnhandledPromiseRejection if privTurnDeferral is not being awaited
                /* tslint:disable:no-empty */
                _this.privTurnDeferral.promise.then().catch(function () { });
            }
            _this.privInTurn = true;
            _this.privTurnDeferral = new Exports_1.Deferred();
        };
        this.getTelemetry = function () {
            if (_this.privServiceTelemetryListener.hasTelemetry) {
                return _this.privServiceTelemetryListener.getTelemetry();
            }
            else {
                return null;
            }
        };
        this.onEvent = function (event) {
            if (!!_this.privServiceTelemetryListener) {
                _this.privServiceTelemetryListener.onEvent(event);
            }
            Exports_1.Events.instance.onEvent(event);
        };
        this.privAudioSourceId = audioSourceId;
        this.privRequestId = Exports_1.createNoDashGuid();
        this.privAudioNodeId = Exports_1.createNoDashGuid();
        this.privTurnDeferral = new Exports_1.Deferred();
        // We're not in a turn, so resolve.
        this.privTurnDeferral.resolve();
    }
    Object.defineProperty(RequestSession.prototype, "sessionId", {
        get: function () {
            return this.privSessionId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RequestSession.prototype, "requestId", {
        get: function () {
            return this.privRequestId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RequestSession.prototype, "audioNodeId", {
        get: function () {
            return this.privAudioNodeId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RequestSession.prototype, "turnCompletionPromise", {
        get: function () {
            return this.privTurnDeferral.promise;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RequestSession.prototype, "isSpeechEnded", {
        get: function () {
            return this.privIsSpeechEnded;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RequestSession.prototype, "isRecognizing", {
        get: function () {
            return this.privIsRecognizing;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RequestSession.prototype, "currentTurnAudioOffset", {
        get: function () {
            return this.privTurnStartAudioOffset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RequestSession.prototype, "recogNumber", {
        get: function () {
            return this.privRecogNumber;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RequestSession.prototype, "numConnectionAttempts", {
        get: function () {
            return this.privConnectionAttempts;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RequestSession.prototype, "bytesSent", {
        // The number of bytes sent for the current connection.
        // Counter is reset to 0 each time a connection is established.
        get: function () {
            return this.privBytesSent;
        },
        enumerable: false,
        configurable: true
    });
    RequestSession.prototype.listenForServiceTelemetry = function (eventSource) {
        if (!!this.privServiceTelemetryListener) {
            this.privDetachables.push(eventSource.attachListener(this.privServiceTelemetryListener));
        }
    };
    RequestSession.prototype.startNewRecognition = function () {
        this.privIsSpeechEnded = false;
        this.privIsRecognizing = true;
        this.privTurnStartAudioOffset = 0;
        this.privLastRecoOffset = 0;
        this.privRecogNumber++;
        this.privServiceTelemetryListener = new ServiceTelemetryListener_Internal_1.ServiceTelemetryListener(this.privRequestId, this.privAudioSourceId, this.privAudioNodeId);
        this.onEvent(new RecognitionEvents_1.RecognitionTriggeredEvent(this.requestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId));
    };
    RequestSession.prototype.onAudioSourceAttachCompleted = function (audioNode, isError, error) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.privAudioNode = audioNode;
                        this.privIsAudioNodeDetached = false;
                        if (!isError) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.onComplete()];
                    case 1:
                        _a.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        this.onEvent(new RecognitionEvents_1.ListeningStartedEvent(this.privRequestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId));
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    RequestSession.prototype.onAuthCompleted = function (isError, error) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!isError) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.onComplete()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    RequestSession.prototype.onConnectionEstablishCompleted = function (statusCode, reason) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(statusCode === 200)) return [3 /*break*/, 1];
                        this.onEvent(new RecognitionEvents_1.RecognitionStartedEvent(this.requestId, this.privAudioSourceId, this.privAudioNodeId, this.privAuthFetchEventId, this.privSessionId));
                        if (!!this.privAudioNode) {
                            this.privAudioNode.replay();
                        }
                        this.privTurnStartAudioOffset = this.privLastRecoOffset;
                        this.privBytesSent = 0;
                        return [2 /*return*/];
                    case 1:
                        if (!(statusCode === 403)) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.onComplete()];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    RequestSession.prototype.onServiceTurnEndResponse = function (continuousRecognition) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.privTurnDeferral.resolve();
                        if (!(!continuousRecognition || this.isSpeechEnded)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.onComplete()];
                    case 1:
                        _a.sent();
                        this.privInTurn = false;
                        return [3 /*break*/, 3];
                    case 2:
                        // Start a new request set.
                        this.privTurnStartAudioOffset = this.privLastRecoOffset;
                        this.privAudioNode.replay();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    RequestSession.prototype.onHypothesis = function (offset) {
        if (!this.privHypothesisReceived) {
            this.privHypothesisReceived = true;
            this.privServiceTelemetryListener.hypothesisReceived(this.privAudioNode.findTimeAtOffset(offset));
        }
    };
    RequestSession.prototype.onPhraseRecognized = function (offset) {
        this.privServiceTelemetryListener.phraseReceived(this.privAudioNode.findTimeAtOffset(offset));
        this.onServiceRecognized(offset);
    };
    RequestSession.prototype.onServiceRecognized = function (offset) {
        this.privLastRecoOffset = offset;
        this.privHypothesisReceived = false;
        this.privAudioNode.shrinkBuffers(offset);
        this.privConnectionAttempts = 0;
    };
    RequestSession.prototype.onAudioSent = function (bytesSent) {
        this.privBytesSent += bytesSent;
    };
    RequestSession.prototype.onRetryConnection = function () {
        this.privConnectionAttempts++;
    };
    RequestSession.prototype.dispose = function (error) {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var _i, _b, detachable;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (!!this.privIsDisposed) return [3 /*break*/, 5];
                        // we should have completed by now. If we did not its an unknown error.
                        this.privIsDisposed = true;
                        _i = 0, _b = this.privDetachables;
                        _c.label = 1;
                    case 1:
                        if (!(_i < _b.length)) return [3 /*break*/, 4];
                        detachable = _b[_i];
                        return [4 /*yield*/, detachable.detach()];
                    case 2:
                        _c.sent();
                        _c.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4:
                        (_a = this.privServiceTelemetryListener) === null || _a === void 0 ? void 0 : _a.dispose();
                        this.privIsRecognizing = false;
                        _c.label = 5;
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    RequestSession.prototype.onStopRecognizing = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.onComplete()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    // Should be called with the audioNode for this session has indicated that it is out of speech.
    RequestSession.prototype.onSpeechEnded = function () {
        this.privIsSpeechEnded = true;
    };
    RequestSession.prototype.onComplete = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!!this.privIsRecognizing) return [3 /*break*/, 2];
                        this.privIsRecognizing = false;
                        return [4 /*yield*/, this.detachAudioNode()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    RequestSession.prototype.detachAudioNode = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!this.privIsAudioNodeDetached) return [3 /*break*/, 2];
                        this.privIsAudioNodeDetached = true;
                        if (!this.privAudioNode) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.privAudioNode.detach()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    return RequestSession;
}());
exports.RequestSession = RequestSession;



/***/ }),
/* 198 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceTelemetryListener = void 0;
// tslint:disable:max-classes-per-file
var Exports_1 = __webpack_require__(4);
var RecognitionEvents_1 = __webpack_require__(171);
var ServiceTelemetryListener = /** @class */ (function () {
    function ServiceTelemetryListener(requestId, audioSourceId, audioNodeId) {
        var _this = this;
        this.privIsDisposed = false;
        this.privListeningTriggerMetric = null;
        this.privMicMetric = null;
        this.privConnectionEstablishMetric = null;
        this.onEvent = function (e) {
            if (_this.privIsDisposed) {
                return;
            }
            if (e instanceof RecognitionEvents_1.RecognitionTriggeredEvent && e.requestId === _this.privRequestId) {
                _this.privListeningTriggerMetric = {
                    End: e.eventTime,
                    Name: "ListeningTrigger",
                    Start: e.eventTime,
                };
            }
            if (e instanceof Exports_1.AudioStreamNodeAttachingEvent && e.audioSourceId === _this.privAudioSourceId && e.audioNodeId === _this.privAudioNodeId) {
                _this.privMicStartTime = e.eventTime;
            }
            if (e instanceof Exports_1.AudioStreamNodeAttachedEvent && e.audioSourceId === _this.privAudioSourceId && e.audioNodeId === _this.privAudioNodeId) {
                _this.privMicStartTime = e.eventTime;
            }
            if (e instanceof Exports_1.AudioSourceErrorEvent && e.audioSourceId === _this.privAudioSourceId) {
                if (!_this.privMicMetric) {
                    _this.privMicMetric = {
                        End: e.eventTime,
                        Error: e.error,
                        Name: "Microphone",
                        Start: _this.privMicStartTime,
                    };
                }
            }
            if (e instanceof Exports_1.AudioStreamNodeErrorEvent && e.audioSourceId === _this.privAudioSourceId && e.audioNodeId === _this.privAudioNodeId) {
                if (!_this.privMicMetric) {
                    _this.privMicMetric = {
                        End: e.eventTime,
                        Error: e.error,
                        Name: "Microphone",
                        Start: _this.privMicStartTime,
                    };
                }
            }
            if (e instanceof Exports_1.AudioStreamNodeDetachedEvent && e.audioSourceId === _this.privAudioSourceId && e.audioNodeId === _this.privAudioNodeId) {
                if (!_this.privMicMetric) {
                    _this.privMicMetric = {
                        End: e.eventTime,
                        Name: "Microphone",
                        Start: _this.privMicStartTime,
                    };
                }
            }
            if (e instanceof RecognitionEvents_1.ConnectingToServiceEvent && e.requestId === _this.privRequestId) {
                _this.privConnectionId = e.sessionId;
            }
            if (e instanceof Exports_1.ConnectionStartEvent && e.connectionId === _this.privConnectionId) {
                _this.privConnectionStartTime = e.eventTime;
            }
            if (e instanceof Exports_1.ConnectionEstablishedEvent && e.connectionId === _this.privConnectionId) {
                if (!_this.privConnectionEstablishMetric) {
                    _this.privConnectionEstablishMetric = {
                        End: e.eventTime,
                        Id: _this.privConnectionId,
                        Name: "Connection",
                        Start: _this.privConnectionStartTime,
                    };
                }
            }
            if (e instanceof Exports_1.ConnectionEstablishErrorEvent && e.connectionId === _this.privConnectionId) {
                if (!_this.privConnectionEstablishMetric) {
                    _this.privConnectionEstablishMetric = {
                        End: e.eventTime,
                        Error: _this.getConnectionError(e.statusCode),
                        Id: _this.privConnectionId,
                        Name: "Connection",
                        Start: _this.privConnectionStartTime,
                    };
                }
            }
            if (e instanceof Exports_1.ConnectionMessageReceivedEvent && e.connectionId === _this.privConnectionId) {
                if (e.message && e.message.headers && e.message.headers.path) {
                    if (!_this.privReceivedMessages[e.message.headers.path]) {
                        _this.privReceivedMessages[e.message.headers.path] = new Array();
                    }
                    var maxMessagesToSend = 50;
                    if (_this.privReceivedMessages[e.message.headers.path].length < maxMessagesToSend) {
                        _this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime);
                    }
                }
            }
        };
        this.getTelemetry = function () {
            var metrics = new Array();
            if (_this.privListeningTriggerMetric) {
                metrics.push(_this.privListeningTriggerMetric);
            }
            if (_this.privMicMetric) {
                metrics.push(_this.privMicMetric);
            }
            if (_this.privConnectionEstablishMetric) {
                metrics.push(_this.privConnectionEstablishMetric);
            }
            if (_this.privPhraseLatencies.length > 0) {
                metrics.push({
                    PhraseLatencyMs: _this.privPhraseLatencies,
                });
            }
            if (_this.privHypothesisLatencies.length > 0) {
                metrics.push({
                    FirstHypothesisLatencyMs: _this.privHypothesisLatencies,
                });
            }
            var telemetry = {
                Metrics: metrics,
                ReceivedMessages: _this.privReceivedMessages,
            };
            var json = JSON.stringify(telemetry);
            // We dont want to send the same telemetry again. So clean those out.
            _this.privReceivedMessages = {};
            _this.privListeningTriggerMetric = null;
            _this.privMicMetric = null;
            _this.privConnectionEstablishMetric = null;
            _this.privPhraseLatencies = [];
            _this.privHypothesisLatencies = [];
            return json;
        };
        this.dispose = function () {
            _this.privIsDisposed = true;
        };
        this.getConnectionError = function (statusCode) {
            /*
            -- Websocket status codes --
            NormalClosure = 1000,
            EndpointUnavailable = 1001,
            ProtocolError = 1002,
            InvalidMessageType = 1003,
            Empty = 1005,
            InvalidPayloadData = 1007,
            PolicyViolation = 1008,
            MessageTooBig = 1009,
            MandatoryExtension = 1010,
            InternalServerError = 1011
            */
            switch (statusCode) {
                case 400:
                case 1002:
                case 1003:
                case 1005:
                case 1007:
                case 1008:
                case 1009: return "BadRequest";
                case 401: return "Unauthorized";
                case 403: return "Forbidden";
                case 503:
                case 1001: return "ServerUnavailable";
                case 500:
                case 1011: return "ServerError";
                case 408:
                case 504: return "Timeout";
                default: return "statuscode:" + statusCode.toString();
            }
        };
        this.privRequestId = requestId;
        this.privAudioSourceId = audioSourceId;
        this.privAudioNodeId = audioNodeId;
        this.privReceivedMessages = {};
        this.privPhraseLatencies = [];
        this.privHypothesisLatencies = [];
    }
    ServiceTelemetryListener.prototype.phraseReceived = function (audioReceivedTime) {
        if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it.
            this.privPhraseLatencies.push(Date.now() - audioReceivedTime);
        }
    };
    ServiceTelemetryListener.prototype.hypothesisReceived = function (audioReceivedTime) {
        if (audioReceivedTime > 0) { // 0 indicates the time is unknown. Drop it.
            this.privHypothesisLatencies.push(Date.now() - audioReceivedTime);
        }
    };
    Object.defineProperty(ServiceTelemetryListener.prototype, "hasTelemetry", {
        // Determines if there are any telemetry events to send to the service.
        get: function () {
            return (Object.keys(this.privReceivedMessages).length !== 0 ||
                this.privListeningTriggerMetric !== null ||
                this.privMicMetric !== null ||
                this.privConnectionEstablishMetric !== null ||
                this.privPhraseLatencies.length !== 0 ||
                this.privHypothesisLatencies.length !== 0);
        },
        enumerable: false,
        configurable: true
    });
    return ServiceTelemetryListener;
}());
exports.ServiceTelemetryListener = ServiceTelemetryListener;



/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechContext = void 0;
/**
 * Represents the JSON used in the speech.context message sent to the speech service.
 * The dynamic grammar is always refreshed from the encapsulated dynamic grammar object.
 */
var SpeechContext = /** @class */ (function () {
    function SpeechContext(dynamicGrammar) {
        this.privContext = {};
        this.privDynamicGrammar = dynamicGrammar;
    }
    /**
     * Adds a section to the speech.context object.
     * @param sectionName Name of the section to add.
     * @param value JSON serializable object that represents the value.
     */
    SpeechContext.prototype.setSection = function (sectionName, value) {
        this.privContext[sectionName] = value;
    };
    /**
     * @Internal
     * This is only used by pronunciation assessment config.
     * Do not use externally, object returned will change without warning or notice.
     */
    SpeechContext.prototype.setPronunciationAssessmentParams = function (params) {
        if (this.privContext.phraseDetection === undefined) {
            this.privContext.phraseDetection = {
                enrichment: {
                    pronunciationAssessment: {}
                }
            };
        }
        this.privContext.phraseDetection.enrichment.pronunciationAssessment = JSON.parse(params);
        if (this.privContext.phraseOutput === undefined) {
            this.privContext.phraseOutput = {
                detailed: {
                    options: []
                },
                format: {}
            };
        }
        this.privContext.phraseOutput.format = "Detailed";
        this.privContext.phraseOutput.detailed.options.push("PronunciationAssessment");
        if (this.privContext.phraseOutput.detailed.options.indexOf("WordTimings") === -1) {
            this.privContext.phraseOutput.detailed.options.push("WordTimings");
        }
        if (this.privContext.phraseOutput.detailed.options.indexOf("SNR") === -1) {
            this.privContext.phraseOutput.detailed.options.push("SNR");
        }
    };
    SpeechContext.prototype.toJSON = function () {
        var dgi = this.privDynamicGrammar.generateGrammarObject();
        this.setSection("dgi", dgi);
        var ret = JSON.stringify(this.privContext);
        return ret;
    };
    return SpeechContext;
}());
exports.SpeechContext = SpeechContext;



/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.DynamicGrammarBuilder = void 0;
/**
 * Responsible for building the object to be sent to the speech service to support dynamic grammars.
 * @class DynamicGrammarBuilder
 */
var DynamicGrammarBuilder = /** @class */ (function () {
    function DynamicGrammarBuilder() {
    }
    // Adds one more reference phrases to the dynamic grammar to send.
    // All added phrases are generic phrases.
    DynamicGrammarBuilder.prototype.addPhrase = function (phrase) {
        if (!this.privPhrases) {
            this.privPhrases = [];
        }
        if (phrase instanceof Array) {
            this.privPhrases = this.privPhrases.concat(phrase);
        }
        else {
            this.privPhrases.push(phrase);
        }
    };
    // Clears all phrases stored in the current object.
    DynamicGrammarBuilder.prototype.clearPhrases = function () {
        this.privPhrases = undefined;
    };
    // Adds one or more reference grammars to the current grammar.
    DynamicGrammarBuilder.prototype.addReferenceGrammar = function (grammar) {
        if (!this.privGrammars) {
            this.privGrammars = [];
        }
        if (grammar instanceof Array) {
            this.privGrammars = this.privGrammars.concat(grammar);
        }
        else {
            this.privGrammars.push(grammar);
        }
    };
    // clears all grammars stored on the recognizer.
    DynamicGrammarBuilder.prototype.clearGrammars = function () {
        this.privGrammars = undefined;
    };
    // Generates an object that represents the dynamic grammar used by the Speech Service.
    // This is done by building an object with the correct layout based on the phrases and reference grammars added to this instance
    // of a DynamicGrammarBuilder
    DynamicGrammarBuilder.prototype.generateGrammarObject = function () {
        if (this.privGrammars === undefined && this.privPhrases === undefined) {
            return undefined;
        }
        var retObj = {};
        retObj.ReferenceGrammars = this.privGrammars;
        if (undefined !== this.privPhrases && 0 !== this.privPhrases.length) {
            var retPhrases_1 = [];
            this.privPhrases.forEach(function (value, index, array) {
                retPhrases_1.push({
                    Text: value,
                });
            });
            retObj.Groups = [{ Type: "Generic", Items: retPhrases_1 }];
        }
        return retObj;
    };
    return DynamicGrammarBuilder;
}());
exports.DynamicGrammarBuilder = DynamicGrammarBuilder;



/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });



/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogServiceAdapter = void 0;
var Exports_1 = __webpack_require__(2);
var DialogEvents_1 = __webpack_require__(27);
var Exports_2 = __webpack_require__(4);
var AudioOutputFormat_1 = __webpack_require__(74);
var Exports_3 = __webpack_require__(61);
var DialogServiceTurnStateManager_1 = __webpack_require__(203);
var Exports_4 = __webpack_require__(53);
var ActivityResponsePayload_1 = __webpack_require__(205);
var SpeechConnectionMessage_Internal_1 = __webpack_require__(173);
var DialogServiceAdapter = /** @class */ (function (_super) {
    __extends(DialogServiceAdapter, _super);
    function DialogServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, dialogServiceConnector) {
        var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, dialogServiceConnector) || this;
        _this.sendAgentConfig = function (connection) {
            if (_this.agentConfig && !_this.agentConfigSent) {
                if (_this.privRecognizerConfig
                    .parameters
                    .getProperty(Exports_3.PropertyId.Conversation_DialogType) === Exports_3.DialogServiceConfig.DialogTypes.CustomCommands) {
                    var config = _this.agentConfig.get();
                    config.botInfo.commandsCulture = _this.privRecognizerConfig.parameters.getProperty(Exports_3.PropertyId.SpeechServiceConnection_RecoLanguage, "en-us");
                    _this.agentConfig.set(config);
                }
                _this.onEvent(new DialogEvents_1.SendingAgentContextMessageEvent(_this.agentConfig));
                var agentConfigJson = _this.agentConfig.toJsonString();
                // guard against sending this multiple times on one connection
                _this.agentConfigSent = true;
                return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "agent.config", _this.privRequestSession.requestId, "application/json", agentConfigJson));
            }
            return;
        };
        _this.sendAgentContext = function (connection) {
            var guid = Exports_2.createGuid();
            var speechActivityTemplate = _this.privDialogServiceConnector.properties.getProperty(Exports_3.PropertyId.Conversation_Speech_Activity_Template);
            var agentContext = {
                channelData: "",
                context: {
                    interactionId: guid
                },
                messagePayload: typeof speechActivityTemplate === undefined ? undefined : speechActivityTemplate,
                version: 0.5
            };
            var agentContextJson = JSON.stringify(agentContext);
            return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "speech.agent.context", _this.privRequestSession.requestId, "application/json", agentContextJson));
        };
        _this.handleResponseMessage = function (responseMessage) {
            // "response" messages can contain either "message" (activity) or "MessageStatus" data. Fire the appropriate
            // event according to the message type that's specified.
            var responsePayload = JSON.parse(responseMessage.textBody);
            switch (responsePayload.messageType.toLowerCase()) {
                case "message":
                    var responseRequestId = responseMessage.requestId.toUpperCase();
                    var activityPayload = ActivityResponsePayload_1.ActivityPayloadResponse.fromJSON(responseMessage.textBody);
                    var turn = _this.privTurnStateManager.GetTurn(responseRequestId);
                    // update the conversation Id
                    if (activityPayload.conversationId) {
                        var updateAgentConfig = _this.agentConfig.get();
                        updateAgentConfig.botInfo.conversationId = activityPayload.conversationId;
                        _this.agentConfig.set(updateAgentConfig);
                    }
                    var pullAudioOutputStream = turn.processActivityPayload(activityPayload, AudioOutputFormat_1.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(_this.privDialogServiceConnector.properties.getProperty(Exports_3.PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined)));
                    var activity = new Exports_3.ActivityReceivedEventArgs(activityPayload.messagePayload, pullAudioOutputStream);
                    if (!!_this.privDialogServiceConnector.activityReceived) {
                        try {
                            _this.privDialogServiceConnector.activityReceived(_this.privDialogServiceConnector, activity);
                            /* tslint:disable:no-empty */
                        }
                        catch (error) {
                            // Not going to let errors in the event handler
                            // trip things up.
                        }
                    }
                    break;
                case "messagestatus":
                    if (!!_this.privDialogServiceConnector.turnStatusReceived) {
                        try {
                            _this.privDialogServiceConnector.turnStatusReceived(_this.privDialogServiceConnector, new Exports_3.TurnStatusReceivedEventArgs(responseMessage.textBody));
                            /* tslint:disable:no-empty */
                        }
                        catch (error) {
                            // Not going to let errors in the event handler
                            // trip things up.
                        }
                    }
                    break;
                default:
                    Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent("Unexpected response of type " + responsePayload.messageType + ". Ignoring."));
                    break;
            }
        };
        _this.privEvents = new Exports_2.EventSource();
        _this.privDialogServiceConnector = dialogServiceConnector;
        _this.receiveMessageOverride = _this.receiveDialogMessageOverride;
        _this.privTurnStateManager = new DialogServiceTurnStateManager_1.DialogServiceTurnStateManager();
        _this.recognizeOverride = _this.listenOnce;
        _this.postConnectImplOverride = _this.dialogConnectImpl;
        _this.configConnectionOverride = _this.configConnection;
        _this.disconnectOverride = _this.privDisconnect;
        _this.privDialogAudioSource = audioSource;
        _this.agentConfigSent = false;
        _this.privLastResult = null;
        _this.connectionEvents.attach(function (connectionEvent) { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (connectionEvent.name === "ConnectionClosedEvent") {
                    this.terminateMessageLoop = true;
                }
                return [2 /*return*/];
            });
        }); });
        return _this;
    }
    DialogServiceAdapter.prototype.sendMessage = function (message) {
        return __awaiter(this, void 0, void 0, function () {
            var interactionGuid, requestId, agentMessage, agentMessageJson, connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        interactionGuid = Exports_2.createGuid();
                        requestId = Exports_2.createNoDashGuid();
                        agentMessage = {
                            context: {
                                interactionId: interactionGuid
                            },
                            messagePayload: JSON.parse(message),
                            version: 0.5
                        };
                        agentMessageJson = JSON.stringify(agentMessage);
                        return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _a.sent();
                        return [4 /*yield*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_2.MessageType.Text, "agent", requestId, "application/json", agentMessageJson))];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    DialogServiceAdapter.prototype.privDisconnect = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.NoError, "Disconnecting")];
                    case 1:
                        _a.sent();
                        this.terminateMessageLoop = true;
                        this.agentConfigSent = false;
                        return [2 /*return*/];
                }
            });
        });
    };
    DialogServiceAdapter.prototype.processTypeSpecificMessages = function (connectionMessage) {
        return __awaiter(this, void 0, void 0, function () {
            var resultProps, result, processed, speechPhrase, args, hypothesis, offset, ev, keyword, event_1, audioRequestId, turn;
            return __generator(this, function (_a) {
                resultProps = new Exports_3.PropertyCollection();
                if (connectionMessage.messageType === Exports_2.MessageType.Text) {
                    resultProps.setProperty(Exports_3.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
                }
                switch (connectionMessage.path.toLowerCase()) {
                    case "speech.phrase":
                        speechPhrase = Exports_4.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody);
                        this.privRequestSession.onPhraseRecognized(this.privRequestSession.currentTurnAudioOffset + speechPhrase.Offset + speechPhrase.Duration);
                        if (speechPhrase.RecognitionStatus !== Exports_4.RecognitionStatus.TooManyRequests && speechPhrase.RecognitionStatus !== Exports_4.RecognitionStatus.Error) {
                            args = this.fireEventForResult(speechPhrase, resultProps);
                            this.privLastResult = args.result;
                            if (!!this.privDialogServiceConnector.recognized) {
                                try {
                                    this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, args);
                                    /* tslint:disable:no-empty */
                                }
                                catch (error) {
                                    // Not going to let errors in the event handler
                                    // trip things up.
                                }
                            }
                        }
                        processed = true;
                        break;
                    case "speech.hypothesis":
                        hypothesis = Exports_4.SpeechHypothesis.fromJSON(connectionMessage.textBody);
                        offset = hypothesis.Offset + this.privRequestSession.currentTurnAudioOffset;
                        result = new Exports_3.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_3.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, undefined, undefined, connectionMessage.textBody, resultProps);
                        this.privRequestSession.onHypothesis(offset);
                        ev = new Exports_3.SpeechRecognitionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId);
                        if (!!this.privDialogServiceConnector.recognizing) {
                            try {
                                this.privDialogServiceConnector.recognizing(this.privDialogServiceConnector, ev);
                                /* tslint:disable:no-empty */
                            }
                            catch (error) {
                                // Not going to let errors in the event handler
                                // trip things up.
                            }
                        }
                        processed = true;
                        break;
                    case "speech.keyword":
                        keyword = Exports_4.SpeechKeyword.fromJSON(connectionMessage.textBody);
                        result = new Exports_3.SpeechRecognitionResult(this.privRequestSession.requestId, keyword.Status === "Accepted" ? Exports_3.ResultReason.RecognizedKeyword : Exports_3.ResultReason.NoMatch, keyword.Text, keyword.Duration, keyword.Offset, undefined, undefined, undefined, undefined, connectionMessage.textBody, resultProps);
                        if (keyword.Status !== "Accepted") {
                            this.privLastResult = result;
                        }
                        event_1 = new Exports_3.SpeechRecognitionEventArgs(result, result.duration, result.resultId);
                        if (!!this.privDialogServiceConnector.recognized) {
                            try {
                                this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, event_1);
                                /* tslint:disable:no-empty */
                            }
                            catch (error) {
                                // Not going to let errors in the event handler
                                // trip things up.
                            }
                        }
                        processed = true;
                        break;
                    case "audio":
                        {
                            audioRequestId = connectionMessage.requestId.toUpperCase();
                            turn = this.privTurnStateManager.GetTurn(audioRequestId);
                            try {
                                // Empty binary message signals end of stream.
                                if (!connectionMessage.binaryBody) {
                                    turn.endAudioStream();
                                }
                                else {
                                    turn.audioStream.write(connectionMessage.binaryBody);
                                }
                            }
                            catch (error) {
                                // Not going to let errors in the event handler
                                // trip things up.
                            }
                        }
                        processed = true;
                        break;
                    case "response":
                        {
                            this.handleResponseMessage(connectionMessage);
                        }
                        processed = true;
                        break;
                    default:
                        break;
                }
                return [2 /*return*/, processed];
            });
        });
    };
    // Cancels recognition.
    DialogServiceAdapter.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) {
        return __awaiter(this, void 0, void 0, function () {
            var properties, cancelEvent, result;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.terminateMessageLoop = true;
                        if (!!!this.privRequestSession.isRecognizing) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.privRequestSession.onStopRecognizing()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        if (!!this.privDialogServiceConnector.canceled) {
                            properties = new Exports_3.PropertyCollection();
                            properties.setProperty(Exports_4.CancellationErrorCodePropertyName, Exports_3.CancellationErrorCode[errorCode]);
                            cancelEvent = new Exports_3.SpeechRecognitionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId);
                            try {
                                this.privDialogServiceConnector.canceled(this.privDialogServiceConnector, cancelEvent);
                                /* tslint:disable:no-empty */
                            }
                            catch (_b) { }
                            if (!!this.privSuccessCallback) {
                                result = new Exports_3.SpeechRecognitionResult(undefined, // ResultId
                                Exports_3.ResultReason.Canceled, undefined, // Text
                                undefined, // Duration
                                undefined, // Offset
                                undefined, // Language
                                undefined, // Language Detection Confidence
                                undefined, // Speaker Id
                                error, undefined, // Json
                                properties);
                                try {
                                    this.privSuccessCallback(result);
                                    this.privSuccessCallback = undefined;
                                    /* tslint:disable:no-empty */
                                }
                                catch (_c) { }
                            }
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    DialogServiceAdapter.prototype.listenOnce = function (recoMode, successCallback, errorCallback) {
        return __awaiter(this, void 0, void 0, function () {
            var conPromise, preAudioPromise, node, format, deviceInfo, audioNode, error_1, sessionStartEventArgs, audioSendPromise;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.privRecognizerConfig.recognitionMode = recoMode;
                        this.privSuccessCallback = successCallback;
                        this.privErrorCallback = errorCallback;
                        this.privRequestSession.startNewRecognition();
                        this.privRequestSession.listenForServiceTelemetry(this.privDialogAudioSource.events);
                        this.privRecognizerConfig.parameters.setProperty(Exports_3.PropertyId.Speech_SessionId, this.privRequestSession.sessionId);
                        conPromise = this.connectImpl();
                        preAudioPromise = this.sendPreAudioMessages();
                        return [4 /*yield*/, this.privDialogAudioSource.attach(this.privRequestSession.audioNodeId)];
                    case 1:
                        node = _a.sent();
                        return [4 /*yield*/, this.privDialogAudioSource.format];
                    case 2:
                        format = _a.sent();
                        return [4 /*yield*/, this.privDialogAudioSource.deviceInfo];
                    case 3:
                        deviceInfo = _a.sent();
                        audioNode = new Exports_1.ReplayableAudioNode(node, format.avgBytesPerSec);
                        return [4 /*yield*/, this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false)];
                    case 4:
                        _a.sent();
                        this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo };
                        _a.label = 5;
                    case 5:
                        _a.trys.push([5, 8, , 10]);
                        return [4 /*yield*/, conPromise];
                    case 6:
                        _a.sent();
                        return [4 /*yield*/, preAudioPromise];
                    case 7:
                        _a.sent();
                        return [3 /*break*/, 10];
                    case 8:
                        error_1 = _a.sent();
                        return [4 /*yield*/, this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.ConnectionFailure, error_1)];
                    case 9:
                        _a.sent();
                        return [2 /*return*/, Promise.resolve()];
                    case 10:
                        sessionStartEventArgs = new Exports_3.SessionEventArgs(this.privRequestSession.sessionId);
                        if (!!this.privRecognizer.sessionStarted) {
                            this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs);
                        }
                        audioSendPromise = this.sendAudio(audioNode);
                        // /* tslint:disable:no-empty */
                        audioSendPromise.then(function () { }, function (error) { return __awaiter(_this, void 0, void 0, function () {
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0: return [4 /*yield*/, this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.RuntimeError, error)];
                                    case 1:
                                        _a.sent();
                                        return [2 /*return*/];
                                }
                            });
                        }); });
                        return [2 /*return*/];
                }
            });
        });
    };
    // Establishes a websocket connection to the end point.
    DialogServiceAdapter.prototype.dialogConnectImpl = function (connection) {
        this.privConnectionLoop = this.startMessageLoop();
        return connection;
    };
    DialogServiceAdapter.prototype.receiveDialogMessageOverride = function () {
        var _this = this;
        // we won't rely on the cascading promises of the connection since we want to continually be available to receive messages
        var communicationCustodian = new Exports_2.Deferred();
        var loop = function () { return __awaiter(_this, void 0, void 0, function () {
            var isDisposed, terminateMessageLoop, connection, message, connectionMessage, _a, turnRequestId, audioSessionReqId, speechStartDetected, speechStartEventArgs, json, speechStopDetected, speechStopEventArgs, turnEndRequestId, audioSessionReqId, sessionStopEventArgs, ret, error_2;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 12, , 13]);
                        isDisposed = this.isDisposed();
                        terminateMessageLoop = (!this.isDisposed() && this.terminateMessageLoop);
                        if (isDisposed || terminateMessageLoop) {
                            // We're done.
                            communicationCustodian.resolve(undefined);
                            return [2 /*return*/];
                        }
                        return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _b.sent();
                        return [4 /*yield*/, connection.read()];
                    case 2:
                        message = _b.sent();
                        if (!message) {
                            return [2 /*return*/, loop()];
                        }
                        connectionMessage = SpeechConnectionMessage_Internal_1.SpeechConnectionMessage.fromConnectionMessage(message);
                        _a = connectionMessage.path.toLowerCase();
                        switch (_a) {
                            case "turn.start": return [3 /*break*/, 3];
                            case "speech.startdetected": return [3 /*break*/, 4];
                            case "speech.enddetected": return [3 /*break*/, 5];
                            case "turn.end": return [3 /*break*/, 6];
                        }
                        return [3 /*break*/, 10];
                    case 3:
                        {
                            turnRequestId = connectionMessage.requestId.toUpperCase();
                            audioSessionReqId = this.privRequestSession.requestId.toUpperCase();
                            // turn started by the service
                            if (turnRequestId !== audioSessionReqId) {
                                this.privTurnStateManager.StartTurn(turnRequestId);
                            }
                            else {
                                this.privRequestSession.onServiceTurnStartResponse();
                            }
                        }
                        return [3 /*break*/, 11];
                    case 4:
                        speechStartDetected = Exports_4.SpeechDetected.fromJSON(connectionMessage.textBody);
                        speechStartEventArgs = new Exports_3.RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId);
                        if (!!this.privRecognizer.speechStartDetected) {
                            this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs);
                        }
                        return [3 /*break*/, 11];
                    case 5:
                        json = void 0;
                        if (connectionMessage.textBody.length > 0) {
                            json = connectionMessage.textBody;
                        }
                        else {
                            // If the request was empty, the JSON returned is empty.
                            json = "{ Offset: 0 }";
                        }
                        speechStopDetected = Exports_4.SpeechDetected.fromJSON(json);
                        this.privRequestSession.onServiceRecognized(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset);
                        speechStopEventArgs = new Exports_3.RecognitionEventArgs(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId);
                        if (!!this.privRecognizer.speechEndDetected) {
                            this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs);
                        }
                        return [3 /*break*/, 11];
                    case 6:
                        turnEndRequestId = connectionMessage.requestId.toUpperCase();
                        audioSessionReqId = this.privRequestSession.requestId.toUpperCase();
                        if (!(turnEndRequestId !== audioSessionReqId)) return [3 /*break*/, 7];
                        this.privTurnStateManager.CompleteTurn(turnEndRequestId);
                        return [3 /*break*/, 9];
                    case 7:
                        sessionStopEventArgs = new Exports_3.SessionEventArgs(this.privRequestSession.sessionId);
                        return [4 /*yield*/, this.privRequestSession.onServiceTurnEndResponse(false)];
                    case 8:
                        _b.sent();
                        if (!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing) {
                            if (!!this.privRecognizer.sessionStopped) {
                                this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs);
                            }
                        }
                        // report result to promise.
                        if (!!this.privSuccessCallback && this.privLastResult) {
                            try {
                                this.privSuccessCallback(this.privLastResult);
                                this.privLastResult = null;
                            }
                            catch (e) {
                                if (!!this.privErrorCallback) {
                                    this.privErrorCallback(e);
                                }
                            }
                            // Only invoke the call back once.
                            // and if it's successful don't invoke the
                            // error after that.
                            this.privSuccessCallback = undefined;
                            this.privErrorCallback = undefined;
                        }
                        _b.label = 9;
                    case 9: return [3 /*break*/, 11];
                    case 10:
                        if (!this.processTypeSpecificMessages(connectionMessage)) {
                            if (!!this.serviceEvents) {
                                this.serviceEvents.onEvent(new Exports_2.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));
                            }
                        }
                        _b.label = 11;
                    case 11:
                        ret = loop();
                        return [2 /*return*/, ret];
                    case 12:
                        error_2 = _b.sent();
                        this.terminateMessageLoop = true;
                        communicationCustodian.resolve();
                        return [3 /*break*/, 13];
                    case 13: return [2 /*return*/];
                }
            });
        }); };
        loop().catch(function (reason) {
            Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason));
        });
        return communicationCustodian.promise;
    };
    DialogServiceAdapter.prototype.startMessageLoop = function () {
        return __awaiter(this, void 0, void 0, function () {
            var error_3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.terminateMessageLoop = false;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 5]);
                        return [4 /*yield*/, this.receiveDialogMessageOverride()];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 5];
                    case 3:
                        error_3 = _a.sent();
                        return [4 /*yield*/, this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_3.CancellationReason.Error, Exports_3.CancellationErrorCode.RuntimeError, error_3)];
                    case 4:
                        _a.sent();
                        return [3 /*break*/, 5];
                    case 5: return [2 /*return*/, Promise.resolve()];
                }
            });
        });
    };
    // Takes an established websocket connection to the endpoint and sends speech configuration information.
    DialogServiceAdapter.prototype.configConnection = function (connection) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.terminateMessageLoop) {
                            this.terminateMessageLoop = false;
                            return [2 /*return*/, Promise.reject("Connection to service terminated.")];
                        }
                        return [4 /*yield*/, this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize())];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.sendAgentConfig(connection)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, connection];
                }
            });
        });
    };
    DialogServiceAdapter.prototype.sendPreAudioMessages = function () {
        return __awaiter(this, void 0, void 0, function () {
            var connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _a.sent();
                        this.addKeywordContextData();
                        return [4 /*yield*/, this.sendSpeechContext(connection)];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.sendAgentContext(connection)];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, this.sendWaveHeader(connection)];
                    case 4:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    DialogServiceAdapter.prototype.fireEventForResult = function (serviceResult, properties) {
        var resultReason = Exports_4.EnumTranslation.implTranslateRecognitionResult(serviceResult.RecognitionStatus);
        var offset = serviceResult.Offset + this.privRequestSession.currentTurnAudioOffset;
        var result = new Exports_3.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, serviceResult.DisplayText, serviceResult.Duration, offset, serviceResult.Language, serviceResult.LanguageDetectionConfidence, undefined, undefined, JSON.stringify(serviceResult), properties);
        var ev = new Exports_3.SpeechRecognitionEventArgs(result, offset, this.privRequestSession.sessionId);
        return ev;
    };
    DialogServiceAdapter.prototype.onEvent = function (event) {
        this.privEvents.onEvent(event);
        Exports_2.Events.instance.onEvent(event);
    };
    DialogServiceAdapter.prototype.addKeywordContextData = function () {
        var keywordPropertyValue = this.privRecognizerConfig.parameters.getProperty("SPEECH-KeywordsToDetect");
        if (keywordPropertyValue === undefined) {
            return;
        }
        var keywordOffsetPropertyValue = this.privRecognizerConfig.parameters
            .getProperty("SPEECH-KeywordsToDetect-Offsets");
        var keywordDurationPropertyValue = this.privRecognizerConfig.parameters
            .getProperty("SPEECH-KeywordsToDetect-Durations");
        var keywords = keywordPropertyValue.split(";");
        var keywordOffsets = keywordOffsetPropertyValue === undefined ? [] : keywordOffsetPropertyValue.split(";");
        var keywordDurations = keywordDurationPropertyValue === undefined ? [] : keywordDurationPropertyValue.split(";");
        var keywordDefinitionArray = [];
        for (var i = 0; i < keywords.length; i++) {
            var definition = {};
            definition.text = keywords[i];
            if (i < keywordOffsets.length) {
                definition.offset = Number(keywordOffsets[i]);
            }
            if (i < keywordDurations.length) {
                definition.duration = Number(keywordDurations[i]);
            }
            keywordDefinitionArray.push(definition);
        }
        this.speechContext.setSection("invocationSource", "VoiceActivationWithKeyword");
        this.speechContext.setSection("keywordDetection", [{
                clientDetectedKeywords: keywordDefinitionArray,
                onReject: { action: "EndOfTurn" },
                type: "startTrigger"
            }]);
    };
    return DialogServiceAdapter;
}(Exports_4.ServiceRecognizerBase));
exports.DialogServiceAdapter = DialogServiceAdapter;



/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogServiceTurnStateManager = void 0;
var Error_1 = __webpack_require__(25);
var DialogServiceTurnState_1 = __webpack_require__(204);
var DialogServiceTurnStateManager = /** @class */ (function () {
    function DialogServiceTurnStateManager() {
        this.privTurnMap = new Map();
        return;
    }
    DialogServiceTurnStateManager.prototype.StartTurn = function (id) {
        if (this.privTurnMap.has(id)) {
            throw new Error_1.InvalidOperationError("Service error: There is already a turn with id:" + id);
        }
        var turnState = new DialogServiceTurnState_1.DialogServiceTurnState(this, id);
        this.privTurnMap.set(id, turnState);
        return this.privTurnMap.get(id);
    };
    DialogServiceTurnStateManager.prototype.GetTurn = function (id) {
        return this.privTurnMap.get(id);
    };
    DialogServiceTurnStateManager.prototype.CompleteTurn = function (id) {
        if (!this.privTurnMap.has(id)) {
            throw new Error_1.InvalidOperationError("Service error: Received turn end for an unknown turn id:" + id);
        }
        var turnState = this.privTurnMap.get(id);
        turnState.complete();
        this.privTurnMap.delete(id);
        return turnState;
    };
    return DialogServiceTurnStateManager;
}());
exports.DialogServiceTurnStateManager = DialogServiceTurnStateManager;



/***/ }),
/* 204 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogServiceTurnState = void 0;
var AudioOutputFormat_1 = __webpack_require__(74);
var AudioOutputStream_1 = __webpack_require__(73);
var ActivityResponsePayload_1 = __webpack_require__(205);
var DialogServiceTurnState = /** @class */ (function () {
    function DialogServiceTurnState(manager, requestId) {
        this.privRequestId = requestId;
        this.privIsCompleted = false;
        this.privAudioStream = null;
        this.privTurnManager = manager;
        this.resetTurnEndTimeout();
        // tslint:disable-next-line:no-console
        // console.info("DialogServiceTurnState debugturn start:" + this.privRequestId);
    }
    Object.defineProperty(DialogServiceTurnState.prototype, "audioStream", {
        get: function () {
            // Called when is needed to stream.
            this.resetTurnEndTimeout();
            return this.privAudioStream;
        },
        enumerable: false,
        configurable: true
    });
    DialogServiceTurnState.prototype.processActivityPayload = function (payload, audioFormat) {
        if (payload.messageDataStreamType === ActivityResponsePayload_1.MessageDataStreamType.TextToSpeechAudio) {
            this.privAudioStream = AudioOutputStream_1.AudioOutputStream.createPullStream();
            this.privAudioStream.format = (audioFormat !== undefined) ? audioFormat : AudioOutputFormat_1.AudioOutputFormatImpl.getDefaultOutputFormat();
            // tslint:disable-next-line:no-console
            // console.info("Audio start debugturn:" + this.privRequestId);
        }
        return this.privAudioStream;
    };
    DialogServiceTurnState.prototype.endAudioStream = function () {
        if (this.privAudioStream !== null && !this.privAudioStream.isClosed) {
            this.privAudioStream.close();
        }
    };
    DialogServiceTurnState.prototype.complete = function () {
        if (this.privTimeoutToken !== undefined) {
            clearTimeout(this.privTimeoutToken);
        }
        this.endAudioStream();
    };
    DialogServiceTurnState.prototype.resetTurnEndTimeout = function () {
        var _this = this;
        if (this.privTimeoutToken !== undefined) {
            clearTimeout(this.privTimeoutToken);
        }
        // tslint:disable-next-line:no-console
        // console.info("Timeout reset debugturn:" + this.privRequestId);
        this.privTimeoutToken = setTimeout(function () {
            // tslint:disable-next-line:no-console
            // console.info("Timeout complete debugturn:" + this.privRequestId);
            _this.privTurnManager.CompleteTurn(_this.privRequestId);
            return;
        }, 2000);
    };
    return DialogServiceTurnState;
}());
exports.DialogServiceTurnState = DialogServiceTurnState;



/***/ }),
/* 205 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// response
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageDataStreamType = exports.ActivityPayloadResponse = void 0;
var ActivityPayloadResponse = /** @class */ (function () {
    function ActivityPayloadResponse(json) {
        this.privActivityResponse = JSON.parse(json);
    }
    ActivityPayloadResponse.fromJSON = function (json) {
        return new ActivityPayloadResponse(json);
    };
    Object.defineProperty(ActivityPayloadResponse.prototype, "conversationId", {
        get: function () {
            return this.privActivityResponse.conversationId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ActivityPayloadResponse.prototype, "messageDataStreamType", {
        get: function () {
            return this.privActivityResponse.messageDataStreamType;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ActivityPayloadResponse.prototype, "messagePayload", {
        get: function () {
            return this.privActivityResponse.messagePayload;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ActivityPayloadResponse.prototype, "version", {
        get: function () {
            return this.privActivityResponse.version;
        },
        enumerable: false,
        configurable: true
    });
    return ActivityPayloadResponse;
}());
exports.ActivityPayloadResponse = ActivityPayloadResponse;
var MessageDataStreamType;
(function (MessageDataStreamType) {
    MessageDataStreamType[MessageDataStreamType["None"] = 0] = "None";
    MessageDataStreamType[MessageDataStreamType["TextToSpeechAudio"] = 1] = "TextToSpeechAudio";
})(MessageDataStreamType = exports.MessageDataStreamType || (exports.MessageDataStreamType = {}));



/***/ }),
/* 206 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentConfig = void 0;
/**
 * Represents the JSON used in the agent.config message sent to the speech service.
 */
var AgentConfig = /** @class */ (function () {
    function AgentConfig() {
    }
    AgentConfig.prototype.toJsonString = function () {
        return JSON.stringify(this.iPrivConfig);
    };
    AgentConfig.prototype.get = function () {
        return this.iPrivConfig;
    };
    /**
     * Setter for the agent.config object.
     * @param value a JSON serializable object.
     */
    AgentConfig.prototype.set = function (value) {
        this.iPrivConfig = value;
    };
    return AgentConfig;
}());
exports.AgentConfig = AgentConfig;



/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
var ConversationManager_1 = __webpack_require__(208);
Object.defineProperty(exports, "ConversationManager", { enumerable: true, get: function () { return ConversationManager_1.ConversationManager; } });
var ConversationConnectionConfig_1 = __webpack_require__(209);
Object.defineProperty(exports, "ConversationConnectionConfig", { enumerable: true, get: function () { return ConversationConnectionConfig_1.ConversationConnectionConfig; } });
var ConversationTranslatorRecognizer_1 = __webpack_require__(211);
Object.defineProperty(exports, "ConversationRecognizerFactory", { enumerable: true, get: function () { return ConversationTranslatorRecognizer_1.ConversationRecognizerFactory; } });
var TranscriberRecognizer_1 = __webpack_require__(223);
Object.defineProperty(exports, "TranscriberRecognizer", { enumerable: true, get: function () { return TranscriberRecognizer_1.TranscriberRecognizer; } });
var ConversationTranslatorEventArgs_1 = __webpack_require__(217);
Object.defineProperty(exports, "ConversationReceivedTranslationEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.ConversationReceivedTranslationEventArgs; } });
Object.defineProperty(exports, "LockRoomEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.LockRoomEventArgs; } });
Object.defineProperty(exports, "MuteAllEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.MuteAllEventArgs; } });
Object.defineProperty(exports, "ParticipantAttributeEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs; } });
Object.defineProperty(exports, "ParticipantEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.ParticipantEventArgs; } });
Object.defineProperty(exports, "ParticipantsListEventArgs", { enumerable: true, get: function () { return ConversationTranslatorEventArgs_1.ParticipantsListEventArgs; } });
var ConversationTranslatorInterfaces_1 = __webpack_require__(218);
Object.defineProperty(exports, "ConversationTranslatorCommandTypes", { enumerable: true, get: function () { return ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes; } });
Object.defineProperty(exports, "ConversationTranslatorMessageTypes", { enumerable: true, get: function () { return ConversationTranslatorInterfaces_1.ConversationTranslatorMessageTypes; } });
Object.defineProperty(exports, "InternalParticipants", { enumerable: true, get: function () { return ConversationTranslatorInterfaces_1.InternalParticipants; } });



/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationManager = void 0;
var Exports_1 = __webpack_require__(2);
var Contracts_1 = __webpack_require__(63);
var Exports_2 = __webpack_require__(61);
var ConversationConnectionConfig_1 = __webpack_require__(209);
var ConversationManager = /** @class */ (function () {
    function ConversationManager() {
        //
        this.privRequestParams = ConversationConnectionConfig_1.ConversationConnectionConfig.configParams;
        this.privErrors = ConversationConnectionConfig_1.ConversationConnectionConfig.restErrors;
        this.privHost = ConversationConnectionConfig_1.ConversationConnectionConfig.host;
        this.privApiVersion = ConversationConnectionConfig_1.ConversationConnectionConfig.apiVersion;
        this.privRestPath = ConversationConnectionConfig_1.ConversationConnectionConfig.restPath;
        this.privRestAdapter = new Exports_1.RestMessageAdapter({});
    }
    /**
     * Make a POST request to the Conversation Manager service endpoint to create or join a conversation.
     * @param args
     * @param conversationCode
     * @param callback
     * @param errorCallback
     */
    ConversationManager.prototype.createOrJoin = function (args, conversationCode, cb, err) {
        var _this = this;
        try {
            Contracts_1.Contracts.throwIfNullOrUndefined(args, "args");
            var languageCode = args.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage, ConversationConnectionConfig_1.ConversationConnectionConfig.defaultLanguageCode);
            var nickname = args.getProperty(Exports_2.PropertyId.ConversationTranslator_Name, "conversation_host");
            var endpointHost = args.getProperty(Exports_2.PropertyId.ConversationTranslator_Host, this.privHost);
            var correlationId = args.getProperty(Exports_2.PropertyId.ConversationTranslator_CorrelationId);
            var subscriptionKey = args.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Key);
            var subscriptionRegion = args.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region);
            var authToken = args.getProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token);
            Contracts_1.Contracts.throwIfNullOrWhitespace(languageCode, "languageCode");
            Contracts_1.Contracts.throwIfNullOrWhitespace(nickname, "nickname");
            Contracts_1.Contracts.throwIfNullOrWhitespace(endpointHost, "endpointHost");
            var queryParams = {};
            queryParams[this.privRequestParams.apiVersion] = this.privApiVersion;
            queryParams[this.privRequestParams.languageCode] = languageCode;
            queryParams[this.privRequestParams.nickname] = nickname;
            var headers = {};
            if (correlationId) {
                headers[this.privRequestParams.correlationId] = correlationId;
            }
            headers[this.privRequestParams.clientAppId] = ConversationConnectionConfig_1.ConversationConnectionConfig.clientAppId;
            if (conversationCode !== undefined) {
                queryParams[this.privRequestParams.roomId] = conversationCode;
            }
            else {
                Contracts_1.Contracts.throwIfNullOrUndefined(subscriptionRegion, this.privErrors.authInvalidSubscriptionRegion);
                headers[this.privRequestParams.subscriptionRegion] = subscriptionRegion;
                if (subscriptionKey) {
                    headers[this.privRequestParams.subscriptionKey] = subscriptionKey;
                }
                else if (authToken) {
                    headers[this.privRequestParams.authorization] = "Bearer " + authToken;
                }
                else {
                    Contracts_1.Contracts.throwIfNullOrUndefined(subscriptionKey, this.privErrors.authInvalidSubscriptionKey);
                }
            }
            var config = {};
            config.headers = headers;
            this.privRestAdapter.options = config;
            var endpoint = "https://" + endpointHost + this.privRestPath;
            // TODO: support a proxy and certificate validation
            this.privRestAdapter.request(Exports_1.RestRequestType.Post, endpoint, queryParams, null).then(function (response) {
                var requestId = Exports_1.RestMessageAdapter.extractHeaderValue(_this.privRequestParams.requestId, response.headers);
                if (!response.ok) {
                    if (!!err) {
                        // get the error
                        var errorMessage = _this.privErrors.invalidCreateJoinConversationResponse.replace("{status}", response.status.toString());
                        var errMessageRaw = void 0;
                        try {
                            errMessageRaw = JSON.parse(response.data);
                            errorMessage += " [" + errMessageRaw.error.code + ": " + errMessageRaw.error.message + "]";
                        }
                        catch (e) {
                            errorMessage += " [" + response.data + "]";
                        }
                        if (requestId) {
                            errorMessage += " " + requestId;
                        }
                        err(errorMessage);
                    }
                    return;
                }
                var conversation = JSON.parse(response.data);
                if (conversation) {
                    conversation.requestId = requestId;
                }
                if (!!cb) {
                    try {
                        cb(conversation);
                    }
                    catch (e) {
                        if (!!err) {
                            err(e);
                        }
                    }
                    cb = undefined;
                }
                /* tslint:disable:no-empty */
            }).catch(function (e) { });
        }
        catch (error) {
            if (!!err) {
                if (error instanceof Error) {
                    var typedError = error;
                    err(typedError.name + ": " + typedError.message);
                }
                else {
                    err(error);
                }
            }
        }
    };
    /**
     * Make a DELETE request to the Conversation Manager service endpoint to leave the conversation.
     * @param args
     * @param sessionToken
     * @param callback
     */
    ConversationManager.prototype.leave = function (args, sessionToken) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            try {
                Contracts_1.Contracts.throwIfNullOrUndefined(args, _this.privErrors.invalidArgs.replace("{arg}", "config"));
                Contracts_1.Contracts.throwIfNullOrWhitespace(sessionToken, _this.privErrors.invalidArgs.replace("{arg}", "token"));
                var endpointHost = args.getProperty(Exports_2.PropertyId.ConversationTranslator_Host, _this.privHost);
                var correlationId = args.getProperty(Exports_2.PropertyId.ConversationTranslator_CorrelationId);
                var queryParams = {};
                queryParams[_this.privRequestParams.apiVersion] = _this.privApiVersion;
                queryParams[_this.privRequestParams.sessionToken] = sessionToken;
                var headers = {};
                if (correlationId) {
                    headers[_this.privRequestParams.correlationId] = correlationId;
                }
                var config = {};
                config.headers = headers;
                _this.privRestAdapter.options = config;
                var endpoint = "https://" + endpointHost + _this.privRestPath;
                // TODO: support a proxy and certificate validation
                _this.privRestAdapter.request(Exports_1.RestRequestType.Delete, endpoint, queryParams, null).then(function (response) {
                    if (!response.ok) {
                        // ignore errors on delete
                    }
                    resolve();
                    /* tslint:disable:no-empty */
                }).catch(function (e) { });
            }
            catch (error) {
                if (error instanceof Error) {
                    var typedError = error;
                    reject(typedError.name + ": " + typedError.message);
                }
                else {
                    reject(error);
                }
            }
        });
    };
    return ConversationManager;
}());
exports.ConversationManager = ConversationManager;



/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationConnectionConfig = void 0;
var RestConfigBase_1 = __webpack_require__(210);
var ConversationConnectionConfig = /** @class */ (function (_super) {
    __extends(ConversationConnectionConfig, _super);
    function ConversationConnectionConfig() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(ConversationConnectionConfig, "host", {
        get: function () {
            return ConversationConnectionConfig.privHost;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationConnectionConfig, "apiVersion", {
        get: function () {
            return ConversationConnectionConfig.privApiVersion;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationConnectionConfig, "clientAppId", {
        get: function () {
            return ConversationConnectionConfig.privClientAppId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationConnectionConfig, "defaultLanguageCode", {
        get: function () {
            return ConversationConnectionConfig.privDefaultLanguageCode;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationConnectionConfig, "restPath", {
        get: function () {
            return ConversationConnectionConfig.privRestPath;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationConnectionConfig, "webSocketPath", {
        get: function () {
            return ConversationConnectionConfig.privWebSocketPath;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationConnectionConfig, "speechHost", {
        get: function () {
            return ConversationConnectionConfig.privSpeechHost;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationConnectionConfig, "speechPath", {
        get: function () {
            return ConversationConnectionConfig.privSpeechPath;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationConnectionConfig, "transcriptionEventKeys", {
        get: function () {
            return ConversationConnectionConfig.privTranscriptionEventKeys;
        },
        enumerable: false,
        configurable: true
    });
    ConversationConnectionConfig.privHost = "dev.microsofttranslator.com";
    ConversationConnectionConfig.privRestPath = "/capito/room";
    ConversationConnectionConfig.privApiVersion = "2.0";
    ConversationConnectionConfig.privDefaultLanguageCode = "en-US";
    ConversationConnectionConfig.privClientAppId = "FC539C22-1767-4F1F-84BC-B4D811114F15";
    ConversationConnectionConfig.privWebSocketPath = "/capito/translate";
    ConversationConnectionConfig.privSpeechHost = "{region}.s2s.speech.microsoft.com";
    ConversationConnectionConfig.privSpeechPath = "/speech/translation/cognitiveservices/v1";
    ConversationConnectionConfig.privTranscriptionEventKeys = ["iCalUid", "callId", "organizer", "FLAC", "MTUri", "DifferentiateGuestSpeakers", "audiorecording", "Threadid", "OrganizerMri", "OrganizerTenantId", "UserToken"];
    return ConversationConnectionConfig;
}(RestConfigBase_1.RestConfigBase));
exports.ConversationConnectionConfig = ConversationConnectionConfig;



/***/ }),
/* 210 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.RestConfigBase = void 0;
var RestConfigBase = /** @class */ (function () {
    function RestConfigBase() {
    }
    Object.defineProperty(RestConfigBase, "requestOptions", {
        get: function () {
            return RestConfigBase.privDefaultRequestOptions;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RestConfigBase, "configParams", {
        get: function () {
            return RestConfigBase.privDefaultParams;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RestConfigBase, "restErrors", {
        get: function () {
            return RestConfigBase.privRestErrors;
        },
        enumerable: false,
        configurable: true
    });
    RestConfigBase.privDefaultRequestOptions = {
        headers: {
            Accept: "application/json",
        },
        ignoreCache: false,
        timeout: 10000,
    };
    RestConfigBase.privRestErrors = {
        authInvalidSubscriptionKey: "You must specify either an authentication token to use, or a Cognitive Speech subscription key.",
        authInvalidSubscriptionRegion: "You must specify the Cognitive Speech region to use.",
        invalidArgs: "Required input not found: {arg}.",
        invalidCreateJoinConversationResponse: "Creating/Joining conversation failed with HTTP {status}.",
        invalidParticipantRequest: "The requested participant was not found.",
        permissionDeniedConnect: "Required credentials not found.",
        permissionDeniedConversation: "Invalid operation: only the host can {command} the conversation.",
        permissionDeniedParticipant: "Invalid operation: only the host can {command} a participant.",
        permissionDeniedSend: "Invalid operation: the conversation is not in a connected state.",
        permissionDeniedStart: "Invalid operation: there is already an active conversation.",
    };
    RestConfigBase.privDefaultParams = {
        apiVersion: "api-version",
        authorization: "Authorization",
        clientAppId: "X-ClientAppId",
        contentTypeKey: "Content-Type",
        correlationId: "X-CorrelationId",
        languageCode: "language",
        nickname: "nickname",
        profanity: "profanity",
        requestId: "X-RequestId",
        roomId: "roomid",
        sessionToken: "token",
        subscriptionKey: "Ocp-Apim-Subscription-Key",
        subscriptionRegion: "Ocp-Apim-Subscription-Region",
        token: "X-CapitoToken",
    };
    return RestConfigBase;
}());
exports.RestConfigBase = RestConfigBase;



/***/ }),
/* 211 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslatorRecognizer = exports.ConversationRecognizerFactory = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
var ConversationConnectionFactory_1 = __webpack_require__(212);
var ConversationServiceAdapter_1 = __webpack_require__(215);
var ConversationRecognizerFactory = /** @class */ (function () {
    function ConversationRecognizerFactory() {
    }
    ConversationRecognizerFactory.fromConfig = function (conversation, speechConfig, audioConfig) {
        return new ConversationTranslatorRecognizer(conversation, speechConfig, audioConfig);
    };
    return ConversationRecognizerFactory;
}());
exports.ConversationRecognizerFactory = ConversationRecognizerFactory;
/**
 * Sends messages to the Conversation Translator websocket and listens for incoming events containing websocket messages.
 * Based off the recognizers in the SDK folder.
 */
// tslint:disable-next-line:max-classes-per-file
var ConversationTranslatorRecognizer = /** @class */ (function (_super) {
    __extends(ConversationTranslatorRecognizer, _super);
    function ConversationTranslatorRecognizer(conversation, speechConfig, audioConfig) {
        var _this = this;
        var serviceConfigImpl = speechConfig;
        Contracts_1.Contracts.throwIfNull(serviceConfigImpl, "speechConfig");
        var conversationImpl = conversation;
        Contracts_1.Contracts.throwIfNull(conversationImpl, "conversationImpl");
        _this = _super.call(this, audioConfig, serviceConfigImpl.properties, new ConversationConnectionFactory_1.ConversationConnectionFactory()) || this;
        _this.privConversation = conversationImpl;
        _this.privIsDisposed = false;
        _this.privProperties = serviceConfigImpl.properties.clone();
        _this.privConnection = Exports_3.Connection.fromRecognizer(_this);
        _this.privSetTimeout = (typeof (Blob) !== "undefined" && typeof (Worker) !== "undefined") ? Exports_2.Timeout.setTimeout : setTimeout;
        _this.privClearTimeout = (typeof (Blob) !== "undefined" && typeof (Worker) !== "undefined") ? Exports_2.Timeout.clearTimeout : clearTimeout;
        return _this;
    }
    Object.defineProperty(ConversationTranslatorRecognizer.prototype, "connected", {
        set: function (cb) {
            this.privConnection.connected = cb;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationTranslatorRecognizer.prototype, "disconnected", {
        set: function (cb) {
            this.privConnection.disconnected = cb;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationTranslatorRecognizer.prototype, "speechRecognitionLanguage", {
        /**
         * Return the speech language used by the recognizer
         */
        get: function () {
            return this.privSpeechRecognitionLanguage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationTranslatorRecognizer.prototype, "properties", {
        /**
         * Return the properties for the recognizer
         */
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    ConversationTranslatorRecognizer.prototype.isDisposed = function () {
        return this.privIsDisposed;
    };
    /**
     * Connect to the recognizer
     * @param token
     */
    ConversationTranslatorRecognizer.prototype.connect = function (token, cb, err) {
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token");
            this.privReco.conversationTranslatorToken = token;
            this.resetConversationTimeout();
            this.privReco.connectAsync(cb, err);
        }
        catch (error) {
            if (!!err) {
                if (error instanceof Error) {
                    var typedError = error;
                    err(typedError.name + ": " + typedError.message);
                }
                else {
                    err(error);
                }
            }
        }
    };
    /**
     * Disconnect from the recognizer
     */
    ConversationTranslatorRecognizer.prototype.disconnect = function (cb, err) {
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            if (this.privTimeoutToken !== undefined) {
                this.privClearTimeout(this.privTimeoutToken);
            }
            this.privReco.disconnect().then(function () {
                if (!!cb) {
                    cb();
                }
            }, function (error) {
                if (!!err) {
                    err(error);
                }
            });
        }
        catch (error) {
            if (!!err) {
                if (error instanceof Error) {
                    var typedError = error;
                    err(typedError.name + ": " + typedError.message);
                }
                else {
                    err(error);
                }
            }
            // Destroy the recognizer.
            this.dispose(true).catch(function (reason) {
                Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason));
            });
        }
    };
    /**
     * Send the mute all participants command to the websocket
     * @param conversationId
     * @param participantId
     * @param isMuted
     */
    ConversationTranslatorRecognizer.prototype.sendRequest = function (command, cb, err) {
        try {
            Contracts_1.Contracts.throwIfDisposed(this.privIsDisposed);
            this.sendMessage(command, cb, err);
        }
        catch (error) {
            if (!!err) {
                if (error instanceof Error) {
                    var typedError = error;
                    err(typedError.name + ": " + typedError.message);
                }
                else {
                    err(error);
                }
            }
            // Destroy the recognizer.
            this.dispose(true).catch(function (reason) {
                Exports_2.Events.instance.onEvent(new Exports_2.BackgroundEvent(reason));
            });
        }
    };
    /**
     * Close and dispose the recognizer
     */
    ConversationTranslatorRecognizer.prototype.close = function () {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (!!this.privIsDisposed) return [3 /*break*/, 2];
                        (_a = this.privConnection) === null || _a === void 0 ? void 0 : _a.closeConnection();
                        (_b = this.privConnection) === null || _b === void 0 ? void 0 : _b.close();
                        this.privConnection = undefined;
                        return [4 /*yield*/, this.dispose(true)];
                    case 1:
                        _c.sent();
                        _c.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Dispose the recognizer
     * @param disposing
     */
    ConversationTranslatorRecognizer.prototype.dispose = function (disposing) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privIsDisposed) {
                            return [2 /*return*/];
                        }
                        if (!disposing) return [3 /*break*/, 2];
                        if (this.privTimeoutToken !== undefined) {
                            this.privClearTimeout(this.privTimeoutToken);
                        }
                        this.privIsDisposed = true;
                        if (!!this.privConnection) {
                            this.privConnection.closeConnection();
                            this.privConnection.close();
                            this.privConnection = undefined;
                        }
                        return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Create the config for the recognizer
     * @param speechConfig
     */
    ConversationTranslatorRecognizer.prototype.createRecognizerConfig = function (speechConfig) {
        return new Exports_1.RecognizerConfig(speechConfig, this.privProperties);
    };
    /**
     * Create the service recognizer.
     * The audio source is redundnant here but is required by the implementation.
     * @param authentication
     * @param connectionFactory
     * @param audioConfig
     * @param recognizerConfig
     */
    ConversationTranslatorRecognizer.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) {
        var audioSource = audioConfig;
        return new ConversationServiceAdapter_1.ConversationServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this);
    };
    ConversationTranslatorRecognizer.prototype.sendMessage = function (msg, cb, err) {
        var withAsync = this.privReco;
        function PromiseToEmptyCallback(promise, cb, err) {
            if (!!promise) {
                promise.then(function (result) {
                    try {
                        if (!!cb) {
                            cb();
                        }
                    }
                    catch (e) {
                        if (!!err) {
                            err("'Unhandled error on promise callback: " + e + "'");
                        }
                    }
                }, function (reason) {
                    try {
                        if (!!err) {
                            err(reason);
                        }
                        /* tslint:disable:no-empty */
                    }
                    catch (error) {
                    }
                });
            }
            else {
                if (!!err) {
                    err("Null promise");
                }
            }
        }
        PromiseToEmptyCallback(withAsync.sendMessageAsync(msg), cb, err);
        this.resetConversationTimeout();
    };
    ConversationTranslatorRecognizer.prototype.resetConversationTimeout = function () {
        var _this = this;
        if (this.privTimeoutToken !== undefined) {
            this.privClearTimeout(this.privTimeoutToken);
        }
        this.privTimeoutToken = this.privSetTimeout(function () {
            _this.sendRequest(_this.privConversation.getKeepAlive());
        }, 60000);
    };
    return ConversationTranslatorRecognizer;
}(Exports_3.Recognizer));
exports.ConversationTranslatorRecognizer = ConversationTranslatorRecognizer;



/***/ }),
/* 212 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationConnectionFactory = void 0;
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var Exports_3 = __webpack_require__(61);
var ConnectionFactoryBase_1 = __webpack_require__(123);
var ConversationConnectionConfig_1 = __webpack_require__(209);
var ConversationWebsocketMessageFormatter_1 = __webpack_require__(213);
/**
 * Create a connection to the Conversation Translator websocket for sending instant messages and commands, and for receiving translated messages.
 * The conversation must already have been started or joined.
 */
var ConversationConnectionFactory = /** @class */ (function (_super) {
    __extends(ConversationConnectionFactory, _super);
    function ConversationConnectionFactory() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ConversationConnectionFactory.prototype.create = function (config, authInfo, connectionId) {
        var endpointHost = config.parameters.getProperty(Exports_3.PropertyId.ConversationTranslator_Host, ConversationConnectionConfig_1.ConversationConnectionConfig.host);
        var correlationId = config.parameters.getProperty(Exports_3.PropertyId.ConversationTranslator_CorrelationId, Exports_2.createGuid());
        var endpoint = "wss://" + endpointHost + ConversationConnectionConfig_1.ConversationConnectionConfig.webSocketPath;
        var token = config.parameters.getProperty(Exports_3.PropertyId.ConversationTranslator_Token, undefined);
        Contracts_1.Contracts.throwIfNullOrUndefined(token, "token");
        var queryParams = {};
        queryParams[ConversationConnectionConfig_1.ConversationConnectionConfig.configParams.apiVersion] = ConversationConnectionConfig_1.ConversationConnectionConfig.apiVersion;
        queryParams[ConversationConnectionConfig_1.ConversationConnectionConfig.configParams.token] = token;
        queryParams[ConversationConnectionConfig_1.ConversationConnectionConfig.configParams.correlationId] = correlationId;
        var enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
        return new Exports_1.WebsocketConnection(endpoint, queryParams, {}, new ConversationWebsocketMessageFormatter_1.ConversationWebsocketMessageFormatter(), Exports_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);
    };
    return ConversationConnectionFactory;
}(ConnectionFactoryBase_1.ConnectionFactoryBase));
exports.ConversationConnectionFactory = ConversationConnectionFactory;



/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationWebsocketMessageFormatter = void 0;
var Exports_1 = __webpack_require__(4);
var ConversationConnectionMessage_1 = __webpack_require__(214);
/**
 * Based off WebsocketMessageFormatter. The messages for Conversation Translator have some variations from the Speech messages.
 */
var ConversationWebsocketMessageFormatter = /** @class */ (function () {
    function ConversationWebsocketMessageFormatter() {
        /**
         * Format incoming messages: text (speech partial/final, IM) or binary (tts)
         */
        this.toConnectionMessage = function (message) {
            var deferral = new Exports_1.Deferred();
            try {
                if (message.messageType === Exports_1.MessageType.Text) {
                    var incomingMessage = new ConversationConnectionMessage_1.ConversationConnectionMessage(message.messageType, message.textContent, {}, message.id);
                    deferral.resolve(incomingMessage);
                }
                else if (message.messageType === Exports_1.MessageType.Binary) {
                    deferral.resolve(new ConversationConnectionMessage_1.ConversationConnectionMessage(message.messageType, message.binaryContent, undefined, message.id));
                }
            }
            catch (e) {
                deferral.reject("Error formatting the message. Error: " + e);
            }
            return deferral.promise;
        };
        /**
         * Format outgoing messages: text (commands or IM)
         */
        this.fromConnectionMessage = function (message) {
            var deferral = new Exports_1.Deferred();
            try {
                if (message.messageType === Exports_1.MessageType.Text) {
                    var payload = "" + (message.textBody ? message.textBody : "");
                    deferral.resolve(new Exports_1.RawWebsocketMessage(Exports_1.MessageType.Text, payload, message.id));
                }
            }
            catch (e) {
                deferral.reject("Error formatting the message. " + e);
            }
            return deferral.promise;
        };
    }
    return ConversationWebsocketMessageFormatter;
}());
exports.ConversationWebsocketMessageFormatter = ConversationWebsocketMessageFormatter;



/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationConnectionMessage = void 0;
var Exports_1 = __webpack_require__(4);
var ConversationConnectionMessage = /** @class */ (function (_super) {
    __extends(ConversationConnectionMessage, _super);
    function ConversationConnectionMessage(messageType, body, headers, id) {
        var _this = _super.call(this, messageType, body, headers, id) || this;
        var json = JSON.parse(_this.textBody);
        if (json.type !== undefined) {
            _this.privConversationMessageType = json.type;
        }
        return _this;
    }
    Object.defineProperty(ConversationConnectionMessage.prototype, "conversationMessageType", {
        get: function () {
            return this.privConversationMessageType;
        },
        enumerable: false,
        configurable: true
    });
    return ConversationConnectionMessage;
}(Exports_1.ConnectionMessage));
exports.ConversationConnectionMessage = ConversationConnectionMessage;



/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationServiceAdapter = void 0;
var Exports_1 = __webpack_require__(4);
var Exports_2 = __webpack_require__(61);
var Exports_3 = __webpack_require__(53);
var ConversationConnectionMessage_1 = __webpack_require__(214);
var ConversationRequestSession_1 = __webpack_require__(216);
var ConversationTranslatorEventArgs_1 = __webpack_require__(217);
var ConversationTranslatorInterfaces_1 = __webpack_require__(218);
var Exports_4 = __webpack_require__(219);
/***
 * The service adapter handles sending and receiving messages to the Conversation Translator websocket.
 */
var ConversationServiceAdapter = /** @class */ (function (_super) {
    __extends(ConversationServiceAdapter, _super);
    function ConversationServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, conversationServiceConnector) {
        var _this = _super.call(this, authentication, connectionFactory, audioSource, recognizerConfig, conversationServiceConnector) || this;
        _this.privLastPartialUtteranceId = "";
        _this.noOp = function () {
            // operation not supported
        };
        _this.privConversationServiceConnector = conversationServiceConnector;
        _this.privConversationAuthentication = authentication;
        _this.receiveMessageOverride = _this.receiveConversationMessageOverride;
        _this.recognizeOverride = _this.noOp;
        _this.postConnectImplOverride = _this.conversationConnectImpl;
        _this.configConnectionOverride = _this.configConnection;
        _this.disconnectOverride = _this.privDisconnect;
        _this.privConversationRequestSession = new ConversationRequestSession_1.ConversationRequestSession(Exports_1.createNoDashGuid());
        _this.privConversationConnectionFactory = connectionFactory;
        _this.privConversationIsDisposed = false;
        return _this;
    }
    ConversationServiceAdapter.prototype.isDisposed = function () {
        return _super.prototype.isDisposed.call(this) || this.privConversationIsDisposed;
    };
    ConversationServiceAdapter.prototype.dispose = function (reason) {
        return __awaiter(this, void 0, void 0, function () {
            var connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.privConversationIsDisposed = true;
                        if (!this.privConnectionConfigPromise) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.privConnectionConfigPromise];
                    case 1:
                        connection = _a.sent();
                        return [4 /*yield*/, connection.dispose(reason)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [4 /*yield*/, _super.prototype.dispose.call(this, reason)];
                    case 4:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    ConversationServiceAdapter.prototype.sendMessage = function (message) {
        return __awaiter(this, void 0, void 0, function () {
            var connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _a.sent();
                        return [2 /*return*/, connection.send(new ConversationConnectionMessage_1.ConversationConnectionMessage(Exports_1.MessageType.Text, message))];
                }
            });
        });
    };
    ConversationServiceAdapter.prototype.sendMessageAsync = function (message) {
        return __awaiter(this, void 0, void 0, function () {
            var sink, connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        sink = new Exports_1.Deferred();
                        return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _a.sent();
                        return [4 /*yield*/, connection.send(new ConversationConnectionMessage_1.ConversationConnectionMessage(Exports_1.MessageType.Text, message))];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    ConversationServiceAdapter.prototype.privDisconnect = function () {
        if (this.terminateMessageLoop) {
            return;
        }
        this.cancelRecognition(this.privConversationRequestSession.sessionId, this.privConversationRequestSession.requestId, Exports_2.CancellationReason.Error, Exports_2.CancellationErrorCode.NoError, "Disconnecting");
        this.terminateMessageLoop = true;
        return Promise.resolve();
    };
    ConversationServiceAdapter.prototype.processTypeSpecificMessages = function (connectionMessage, successCallback, errorCallBack) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, true];
            });
        });
    };
    // Cancels recognition.
    ConversationServiceAdapter.prototype.cancelRecognition = function (sessionId, requestId, cancellationReason, errorCode, error) {
        this.terminateMessageLoop = true;
        var cancelEvent = new Exports_2.ConversationTranslationCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId);
        try {
            if (!!this.privConversationServiceConnector.canceled) {
                this.privConversationServiceConnector.canceled(this.privConversationServiceConnector, cancelEvent);
            }
        }
        catch (_a) {
            // continue on error
        }
    };
    /**
     * Establishes a websocket connection to the end point.
     */
    ConversationServiceAdapter.prototype.conversationConnectImpl = function (connection) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.privConnectionLoop = this.startMessageLoop();
                return [2 /*return*/, connection];
            });
        });
    };
    /**
     * Process incoming websocket messages
     */
    ConversationServiceAdapter.prototype.receiveConversationMessageOverride = function () {
        return __awaiter(this, void 0, void 0, function () {
            var communicationCustodian, connection, message, sessionId, sendFinal, commandPayload_1, participantsPayload, participantsResult, joinParticipantPayload, joiningParticipant, leavingParticipant, disconnectParticipant, token, speechPayload, speechResult, textPayload, textResult, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.isDisposed() || this.terminateMessageLoop) {
                            return [2 /*return*/, Promise.resolve()];
                        }
                        communicationCustodian = new Exports_1.Deferred();
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 4, , 5]);
                        return [4 /*yield*/, this.fetchConnection()];
                    case 2:
                        connection = _a.sent();
                        return [4 /*yield*/, connection.read()];
                    case 3:
                        message = _a.sent();
                        if (this.isDisposed() || this.terminateMessageLoop) {
                            // We're done.
                            communicationCustodian.resolve();
                            return [2 /*return*/, Promise.resolve()];
                        }
                        if (!message) {
                            return [2 /*return*/, this.receiveConversationMessageOverride()];
                        }
                        sessionId = this.privConversationRequestSession.sessionId;
                        sendFinal = false;
                        try {
                            switch (message.conversationMessageType.toLowerCase()) {
                                case "info":
                                case "participant_command":
                                case "command":
                                    commandPayload_1 = Exports_4.CommandResponsePayload.fromJSON(message.textBody);
                                    switch (commandPayload_1.command.toLowerCase()) {
                                        /**
                                         * 'ParticpantList' is the first message sent to the user after the websocket connection has opened.
                                         * The consuming client must wait for this message to arrive
                                         * before starting to send their own data.
                                         */
                                        case "participantlist":
                                            participantsPayload = Exports_4.ParticipantsListPayloadResponse.fromJSON(message.textBody);
                                            participantsResult = participantsPayload.participants.map(function (p) {
                                                var participant = {
                                                    avatar: p.avatar,
                                                    displayName: p.nickname,
                                                    id: p.participantId,
                                                    isHost: p.ishost,
                                                    isMuted: p.ismuted,
                                                    isUsingTts: p.usetts,
                                                    preferredLanguage: p.locale
                                                };
                                                return participant;
                                            });
                                            if (!!this.privConversationServiceConnector.participantsListReceived) {
                                                this.privConversationServiceConnector.participantsListReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantsListEventArgs(participantsPayload.roomid, participantsPayload.token, participantsPayload.translateTo, participantsPayload.profanityFilter, participantsPayload.roomProfanityFilter, participantsPayload.roomLocked, participantsPayload.muteAll, participantsResult, sessionId));
                                            }
                                            break;
                                        /**
                                         * 'SetTranslateToLanguages' represents the list of languages being used in the Conversation by all users(?).
                                         * This is sent at the start of the Conversation
                                         */
                                        case "settranslatetolanguages":
                                            if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {
                                                this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs(commandPayload_1.participantId, ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes.setTranslateToLanguages, commandPayload_1.value, sessionId));
                                            }
                                            break;
                                        /**
                                         * 'SetProfanityFiltering' lets the client set the level of profanity filtering.
                                         * If sent by the participant the setting will effect only their own profanity level.
                                         * If sent by the host, the setting will effect all participants including the host.
                                         * Note: the profanity filters differ from Speech Service (?): 'marked', 'raw', 'removed', 'tagged'
                                         */
                                        case "setprofanityfiltering":
                                            if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {
                                                this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs(commandPayload_1.participantId, ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes.setProfanityFiltering, commandPayload_1.value, sessionId));
                                            }
                                            break;
                                        /**
                                         * 'SetMute' is sent if the participant has been muted by the host.
                                         * Check the 'participantId' to determine if the current user has been muted.
                                         */
                                        case "setmute":
                                            if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {
                                                this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs(commandPayload_1.participantId, ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes.setMute, commandPayload_1.value, sessionId));
                                            }
                                            break;
                                        /**
                                         * 'SetMuteAll' is sent if the Conversation has been muted by the host.
                                         */
                                        case "setmuteall":
                                            if (!!this.privConversationServiceConnector.muteAllCommandReceived) {
                                                this.privConversationServiceConnector.muteAllCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.MuteAllEventArgs(commandPayload_1.value, sessionId));
                                            }
                                            break;
                                        /**
                                         * 'RoomExpirationWarning' is sent towards the end of the Conversation session to give a timeout warning.
                                         */
                                        case "roomexpirationwarning":
                                            if (!!this.privConversationServiceConnector.conversationExpiration) {
                                                this.privConversationServiceConnector.conversationExpiration(this.privConversationServiceConnector, new Exports_2.ConversationExpirationEventArgs(commandPayload_1.value, this.privConversationRequestSession.sessionId));
                                            }
                                            break;
                                        /**
                                         * 'SetUseTts' is sent as a confirmation if the user requests TTS to be turned on or off.
                                         */
                                        case "setusetts":
                                            if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {
                                                this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs(commandPayload_1.participantId, ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes.setUseTTS, commandPayload_1.value, sessionId));
                                            }
                                            break;
                                        /**
                                         * 'SetLockState' is set if the host has locked or unlocked the Conversation.
                                         */
                                        case "setlockstate":
                                            if (!!this.privConversationServiceConnector.lockRoomCommandReceived) {
                                                this.privConversationServiceConnector.lockRoomCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.LockRoomEventArgs(commandPayload_1.value, sessionId));
                                            }
                                            break;
                                        /**
                                         * 'ChangeNickname' is received if a user changes their display name.
                                         * Any cached particpiants list should be updated to reflect the display name.
                                         */
                                        case "changenickname":
                                            if (!!this.privConversationServiceConnector.participantUpdateCommandReceived) {
                                                this.privConversationServiceConnector.participantUpdateCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantAttributeEventArgs(commandPayload_1.participantId, ConversationTranslatorInterfaces_1.ConversationTranslatorCommandTypes.changeNickname, commandPayload_1.nickname, sessionId));
                                            }
                                            break;
                                        /**
                                         * 'JoinSession' is sent when a user joins the Conversation.
                                         */
                                        case "joinsession":
                                            joinParticipantPayload = Exports_4.ParticipantPayloadResponse.fromJSON(message.textBody);
                                            joiningParticipant = {
                                                avatar: joinParticipantPayload.avatar,
                                                displayName: joinParticipantPayload.nickname,
                                                id: joinParticipantPayload.participantId,
                                                isHost: joinParticipantPayload.ishost,
                                                isMuted: joinParticipantPayload.ismuted,
                                                isUsingTts: joinParticipantPayload.usetts,
                                                preferredLanguage: joinParticipantPayload.locale,
                                            };
                                            if (!!this.privConversationServiceConnector.participantJoinCommandReceived) {
                                                this.privConversationServiceConnector.participantJoinCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantEventArgs(joiningParticipant, sessionId));
                                            }
                                            break;
                                        /**
                                         * 'LeaveSession' is sent when a user leaves the Conversation'.
                                         */
                                        case "leavesession":
                                            leavingParticipant = {
                                                id: commandPayload_1.participantId
                                            };
                                            if (!!this.privConversationServiceConnector.participantLeaveCommandReceived) {
                                                this.privConversationServiceConnector.participantLeaveCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ParticipantEventArgs(leavingParticipant, sessionId));
                                            }
                                            break;
                                        /**
                                         * 'DisconnectSession' is sent when a user is disconnected from the session (e.g. network problem).
                                         * Check the 'ParticipantId' to check whether the message is for the current user.
                                         */
                                        case "disconnectsession":
                                            disconnectParticipant = {
                                                id: commandPayload_1.participantId
                                            };
                                            break;
                                        case "token":
                                            token = new Exports_3.CognitiveTokenAuthentication(function (authFetchEventId) {
                                                var authorizationToken = commandPayload_1.token;
                                                return Promise.resolve(authorizationToken);
                                            }, function (authFetchEventId) {
                                                var authorizationToken = commandPayload_1.token;
                                                return Promise.resolve(authorizationToken);
                                            });
                                            this.authentication = token;
                                            break;
                                        /**
                                         * Message not recognized.
                                         */
                                        default:
                                            break;
                                    }
                                    break;
                                /**
                                 * 'partial' (or 'hypothesis') represents a unfinalized speech message.
                                 */
                                case "partial":
                                /**
                                 * 'final' (or 'phrase') represents a finalized speech message.
                                 */
                                case "final":
                                    speechPayload = Exports_4.SpeechResponsePayload.fromJSON(message.textBody);
                                    speechResult = new Exports_2.ConversationTranslationResult(speechPayload.participantId, this.getTranslations(speechPayload.translations), speechPayload.language, undefined, undefined, speechPayload.recognition, undefined, undefined, message.textBody, undefined);
                                    if (speechPayload.isFinal) {
                                        // check the length, sometimes empty finals are returned
                                        if (speechResult.text !== undefined && speechResult.text.length > 0) {
                                            sendFinal = true;
                                        }
                                        else if (speechPayload.id === this.privLastPartialUtteranceId) {
                                            // send final as normal. We had a non-empty partial for this same utterance
                                            // so sending the empty final is important
                                            sendFinal = true;
                                        }
                                        else {
                                            // suppress unneeded final
                                        }
                                        if (sendFinal) {
                                            if (!!this.privConversationServiceConnector.translationReceived) {
                                                this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ConversationReceivedTranslationEventArgs(ConversationTranslatorInterfaces_1.ConversationTranslatorMessageTypes.final, speechResult, sessionId));
                                            }
                                        }
                                    }
                                    else if (speechResult.text !== undefined) {
                                        this.privLastPartialUtteranceId = speechPayload.id;
                                        if (!!this.privConversationServiceConnector.translationReceived) {
                                            this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ConversationReceivedTranslationEventArgs(ConversationTranslatorInterfaces_1.ConversationTranslatorMessageTypes.partial, speechResult, sessionId));
                                        }
                                    }
                                    break;
                                /**
                                 * "translated_message" is a text message or instant message (IM).
                                 */
                                case "translated_message":
                                    textPayload = Exports_4.TextResponsePayload.fromJSON(message.textBody);
                                    textResult = new Exports_2.ConversationTranslationResult(textPayload.participantId, this.getTranslations(textPayload.translations), textPayload.language, undefined, undefined, textPayload.originalText, undefined, undefined, undefined, message.textBody, undefined);
                                    if (!!this.privConversationServiceConnector.translationReceived) {
                                        this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_1.ConversationReceivedTranslationEventArgs(ConversationTranslatorInterfaces_1.ConversationTranslatorMessageTypes.instantMessage, textResult, sessionId));
                                    }
                                    break;
                                default:
                                    // ignore any unsupported message types
                                    break;
                            }
                        }
                        catch (e) {
                            // continue
                        }
                        return [2 /*return*/, this.receiveConversationMessageOverride()];
                    case 4:
                        e_1 = _a.sent();
                        this.terminateMessageLoop = true;
                        return [3 /*break*/, 5];
                    case 5: return [2 /*return*/, communicationCustodian.promise];
                }
            });
        });
    };
    ConversationServiceAdapter.prototype.startMessageLoop = function () {
        return __awaiter(this, void 0, void 0, function () {
            var messageRetrievalPromise, r, error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.isDisposed()) {
                            return [2 /*return*/, Promise.resolve()];
                        }
                        this.terminateMessageLoop = false;
                        messageRetrievalPromise = this.receiveConversationMessageOverride();
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, messageRetrievalPromise];
                    case 2:
                        r = _a.sent();
                        return [2 /*return*/, r];
                    case 3:
                        error_1 = _a.sent();
                        this.cancelRecognition(this.privRequestSession ? this.privRequestSession.sessionId : "", this.privRequestSession ? this.privRequestSession.requestId : "", Exports_2.CancellationReason.Error, Exports_2.CancellationErrorCode.RuntimeError, error_1);
                        return [2 /*return*/, null];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    // Takes an established websocket connection to the endpoint
    ConversationServiceAdapter.prototype.configConnection = function () {
        var _this = this;
        if (this.isDisposed()) {
            return Promise.resolve(undefined);
        }
        if (this.privConnectionConfigPromise) {
            return this.privConnectionConfigPromise.then(function (connection) {
                if (connection.state() === Exports_1.ConnectionState.Disconnected) {
                    _this.privConnectionId = null;
                    _this.privConnectionConfigPromise = null;
                    return _this.configConnection();
                }
                return _this.privConnectionConfigPromise;
            }, function (error) {
                _this.privConnectionId = null;
                _this.privConnectionConfigPromise = null;
                return _this.configConnection();
            });
        }
        if (this.terminateMessageLoop) {
            return Promise.resolve(undefined);
        }
        this.privConnectionConfigPromise = this.connectImpl().then(function (connection) {
            return connection;
        });
        return this.privConnectionConfigPromise;
    };
    ConversationServiceAdapter.prototype.getTranslations = function (serviceResultTranslations) {
        var translations;
        if (undefined !== serviceResultTranslations) {
            translations = new Exports_2.Translations();
            for (var _i = 0, serviceResultTranslations_1 = serviceResultTranslations; _i < serviceResultTranslations_1.length; _i++) {
                var translation = serviceResultTranslations_1[_i];
                translations.set(translation.lang, translation.translation);
            }
        }
        return translations;
    };
    return ConversationServiceAdapter;
}(Exports_3.ServiceRecognizerBase));
exports.ConversationServiceAdapter = ConversationServiceAdapter;



/***/ }),
/* 216 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationRequestSession = void 0;
var Exports_1 = __webpack_require__(4);
/**
 * Placeholder class for the Conversation Request Session. Based off RequestSession.
 * TODO: define what telemetry is required.
 */
var ConversationRequestSession = /** @class */ (function () {
    function ConversationRequestSession(sessionId) {
        var _this = this;
        this.privIsDisposed = false;
        this.privDetachables = new Array();
        this.onPreConnectionStart = function (authFetchEventId, connectionId) {
            _this.privSessionId = connectionId;
        };
        this.onAuthCompleted = function (isError, error) {
            if (isError) {
                _this.onComplete();
            }
        };
        this.onConnectionEstablishCompleted = function (statusCode, reason) {
            if (statusCode === 200) {
                return;
            }
            else if (statusCode === 403) {
                _this.onComplete();
            }
        };
        this.onServiceTurnEndResponse = function (continuousRecognition) {
            if (!continuousRecognition) {
                _this.onComplete();
            }
            else {
                _this.privRequestId = Exports_1.createNoDashGuid();
            }
        };
        this.onComplete = function () {
            //
        };
        this.privSessionId = sessionId;
        this.privRequestId = Exports_1.createNoDashGuid();
        this.privRequestCompletionDeferral = new Exports_1.Deferred();
    }
    Object.defineProperty(ConversationRequestSession.prototype, "sessionId", {
        get: function () {
            return this.privSessionId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationRequestSession.prototype, "requestId", {
        get: function () {
            return this.privRequestId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationRequestSession.prototype, "completionPromise", {
        get: function () {
            return this.privRequestCompletionDeferral.promise;
        },
        enumerable: false,
        configurable: true
    });
    ConversationRequestSession.prototype.dispose = function (error) {
        return __awaiter(this, void 0, void 0, function () {
            var _i, _a, detachable;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!!this.privIsDisposed) return [3 /*break*/, 4];
                        // we should have completed by now. If we did not its an unknown error.
                        this.privIsDisposed = true;
                        _i = 0, _a = this.privDetachables;
                        _b.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3 /*break*/, 4];
                        detachable = _a[_i];
                        return [4 /*yield*/, detachable.detach()];
                    case 2:
                        _b.sent();
                        _b.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    return ConversationRequestSession;
}());
exports.ConversationRequestSession = ConversationRequestSession;



/***/ }),
/* 217 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationReceivedTranslationEventArgs = exports.ParticipantsListEventArgs = exports.ParticipantAttributeEventArgs = exports.ParticipantEventArgs = exports.LockRoomEventArgs = exports.MuteAllEventArgs = void 0;
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var Exports_1 = __webpack_require__(61);
var MuteAllEventArgs = /** @class */ (function (_super) {
    __extends(MuteAllEventArgs, _super);
    function MuteAllEventArgs(isMuted, sessionId) {
        var _this = _super.call(this, sessionId) || this;
        _this.privIsMuted = isMuted;
        return _this;
    }
    Object.defineProperty(MuteAllEventArgs.prototype, "isMuted", {
        get: function () {
            return this.privIsMuted;
        },
        enumerable: false,
        configurable: true
    });
    return MuteAllEventArgs;
}(Exports_1.SessionEventArgs));
exports.MuteAllEventArgs = MuteAllEventArgs;
// tslint:disable-next-line: max-classes-per-file
var LockRoomEventArgs = /** @class */ (function (_super) {
    __extends(LockRoomEventArgs, _super);
    function LockRoomEventArgs(isLocked, sessionId) {
        var _this = _super.call(this, sessionId) || this;
        _this.privIsLocked = isLocked;
        return _this;
    }
    Object.defineProperty(LockRoomEventArgs.prototype, "isMuted", {
        get: function () {
            return this.privIsLocked;
        },
        enumerable: false,
        configurable: true
    });
    return LockRoomEventArgs;
}(Exports_1.SessionEventArgs));
exports.LockRoomEventArgs = LockRoomEventArgs;
// tslint:disable-next-line: max-classes-per-file
var ParticipantEventArgs = /** @class */ (function (_super) {
    __extends(ParticipantEventArgs, _super);
    function ParticipantEventArgs(participant, sessionId) {
        var _this = _super.call(this, sessionId) || this;
        _this.privParticipant = participant;
        return _this;
    }
    Object.defineProperty(ParticipantEventArgs.prototype, "participant", {
        get: function () {
            return this.privParticipant;
        },
        enumerable: false,
        configurable: true
    });
    return ParticipantEventArgs;
}(Exports_1.SessionEventArgs));
exports.ParticipantEventArgs = ParticipantEventArgs;
// tslint:disable-next-line: max-classes-per-file
var ParticipantAttributeEventArgs = /** @class */ (function (_super) {
    __extends(ParticipantAttributeEventArgs, _super);
    function ParticipantAttributeEventArgs(participantId, key, value, sessionId) {
        var _this = _super.call(this, sessionId) || this;
        _this.privKey = key;
        _this.privValue = value;
        _this.privParticipantId = participantId;
        return _this;
    }
    Object.defineProperty(ParticipantAttributeEventArgs.prototype, "value", {
        get: function () {
            return this.privValue;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantAttributeEventArgs.prototype, "key", {
        get: function () {
            return this.privKey;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantAttributeEventArgs.prototype, "id", {
        get: function () {
            return this.privParticipantId;
        },
        enumerable: false,
        configurable: true
    });
    return ParticipantAttributeEventArgs;
}(Exports_1.SessionEventArgs));
exports.ParticipantAttributeEventArgs = ParticipantAttributeEventArgs;
// tslint:disable-next-line: max-classes-per-file
var ParticipantsListEventArgs = /** @class */ (function (_super) {
    __extends(ParticipantsListEventArgs, _super);
    function ParticipantsListEventArgs(conversationId, token, translateTo, profanityFilter, roomProfanityFilter, isRoomLocked, isMuteAll, participants, sessionId) {
        var _this = _super.call(this, sessionId) || this;
        _this.privRoomId = conversationId;
        _this.privSessionToken = token;
        _this.privTranslateTo = translateTo;
        _this.privProfanityFilter = profanityFilter;
        _this.privRoomProfanityFilter = roomProfanityFilter;
        _this.privIsRoomLocked = isRoomLocked;
        _this.privIsRoomLocked = isMuteAll;
        _this.privParticipants = participants;
        return _this;
    }
    Object.defineProperty(ParticipantsListEventArgs.prototype, "sessionToken", {
        get: function () {
            return this.privSessionToken;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListEventArgs.prototype, "conversationId", {
        get: function () {
            return this.privRoomId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListEventArgs.prototype, "translateTo", {
        get: function () {
            return this.privTranslateTo;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListEventArgs.prototype, "profanityFilter", {
        get: function () {
            return this.privProfanityFilter;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListEventArgs.prototype, "roomProfanityFilter", {
        get: function () {
            return this.privRoomProfanityFilter;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListEventArgs.prototype, "isRoomLocked", {
        get: function () {
            return this.privIsRoomLocked;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListEventArgs.prototype, "isMuteAll", {
        get: function () {
            return this.privIsMuteAll;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListEventArgs.prototype, "participants", {
        get: function () {
            return this.privParticipants;
        },
        enumerable: false,
        configurable: true
    });
    return ParticipantsListEventArgs;
}(Exports_1.SessionEventArgs));
exports.ParticipantsListEventArgs = ParticipantsListEventArgs;
// tslint:disable-next-line: max-classes-per-file
var ConversationReceivedTranslationEventArgs = /** @class */ (function () {
    function ConversationReceivedTranslationEventArgs(command, payload, sessionId) {
        this.privPayload = payload;
        this.privCommand = command;
        this.privSessionId = sessionId;
    }
    Object.defineProperty(ConversationReceivedTranslationEventArgs.prototype, "payload", {
        get: function () {
            return this.privPayload;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationReceivedTranslationEventArgs.prototype, "command", {
        get: function () {
            return this.privCommand;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ConversationReceivedTranslationEventArgs.prototype, "sessionId", {
        get: function () {
            return this.privSessionId;
        },
        enumerable: false,
        configurable: true
    });
    return ConversationReceivedTranslationEventArgs;
}());
exports.ConversationReceivedTranslationEventArgs = ConversationReceivedTranslationEventArgs;



/***/ }),
/* 218 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslatorCommandTypes = exports.ConversationTranslatorMessageTypes = exports.InternalParticipants = void 0;
/** Users participating in the conversation */
var InternalParticipants = /** @class */ (function () {
    function InternalParticipants(participants, meId) {
        if (participants === void 0) { participants = []; }
        this.participants = participants;
        this.meId = meId;
    }
    /**
     * Add or update a participant
     * @param value
     */
    InternalParticipants.prototype.addOrUpdateParticipant = function (value) {
        if (value === undefined) {
            return;
        }
        var exists = this.getParticipantIndex(value.id);
        if (exists > -1) {
            this.participants.splice(exists, 1, value);
        }
        else {
            this.participants.push(value);
        }
        // ensure it was added ok
        return this.getParticipant(value.id);
    };
    /**
     * Find the participant's position in the participants list.
     * @param id
     */
    InternalParticipants.prototype.getParticipantIndex = function (id) {
        return this.participants.findIndex(function (p) { return p.id === id; });
    };
    /**
     * Find the participant by id.
     * @param id
     */
    InternalParticipants.prototype.getParticipant = function (id) {
        return this.participants.find(function (p) { return p.id === id; });
    };
    /***
     * Remove a participant from the participants list.
     */
    InternalParticipants.prototype.deleteParticipant = function (id) {
        this.participants = this.participants.filter(function (p) { return p.id !== id; });
    };
    Object.defineProperty(InternalParticipants.prototype, "host", {
        /***
         * Helper to return the conversation host.
         */
        get: function () {
            return this.participants.find(function (p) { return p.isHost === true; });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(InternalParticipants.prototype, "me", {
        /**
         * Helper to return the current user.
         */
        get: function () {
            return this.getParticipant(this.meId);
        },
        enumerable: false,
        configurable: true
    });
    return InternalParticipants;
}());
exports.InternalParticipants = InternalParticipants;
/**
 * List of command message types
 */
exports.ConversationTranslatorMessageTypes = {
    command: "command",
    final: "final",
    info: "info",
    instantMessage: "instant_message",
    keepAlive: "keep_alive",
    partial: "partial",
    participantCommand: "participant_command",
    translatedMessage: "translated_message"
};
/**
 * List of command types
 */
exports.ConversationTranslatorCommandTypes = {
    changeNickname: "ChangeNickname",
    disconnectSession: "DisconnectSession",
    ejectParticipant: "EjectParticipant",
    instant_message: "instant_message",
    joinSession: "JoinSession",
    leaveSession: "LeaveSession",
    participantList: "ParticipantList",
    roomExpirationWarning: "RoomExpirationWarning",
    setLockState: "SetLockState",
    setMute: "SetMute",
    setMuteAll: "SetMuteAll",
    setProfanityFiltering: "SetProfanityFiltering",
    setTranslateToLanguages: "SetTranslateToLanguages",
    setUseTTS: "SetUseTTS"
};



/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var CommandResponsePayload_1 = __webpack_require__(220);
Object.defineProperty(exports, "CommandResponsePayload", { enumerable: true, get: function () { return CommandResponsePayload_1.CommandResponsePayload; } });
var ParticipantResponsePayload_1 = __webpack_require__(221);
Object.defineProperty(exports, "ParticipantsListPayloadResponse", { enumerable: true, get: function () { return ParticipantResponsePayload_1.ParticipantsListPayloadResponse; } });
Object.defineProperty(exports, "ParticipantPayloadResponse", { enumerable: true, get: function () { return ParticipantResponsePayload_1.ParticipantPayloadResponse; } });
var TranslationResponsePayload_1 = __webpack_require__(222);
Object.defineProperty(exports, "SpeechResponsePayload", { enumerable: true, get: function () { return TranslationResponsePayload_1.SpeechResponsePayload; } });
Object.defineProperty(exports, "TextResponsePayload", { enumerable: true, get: function () { return TranslationResponsePayload_1.TextResponsePayload; } });



/***/ }),
/* 220 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandResponsePayload = void 0;
var CommandResponsePayload = /** @class */ (function () {
    function CommandResponsePayload(json) {
        this.privCommandResponse = JSON.parse(json);
    }
    CommandResponsePayload.fromJSON = function (json) {
        return new CommandResponsePayload(json);
    };
    Object.defineProperty(CommandResponsePayload.prototype, "type", {
        get: function () {
            return this.privCommandResponse.type;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CommandResponsePayload.prototype, "command", {
        get: function () {
            return this.privCommandResponse.command;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CommandResponsePayload.prototype, "id", {
        get: function () {
            return this.privCommandResponse.id;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CommandResponsePayload.prototype, "nickname", {
        get: function () {
            return this.privCommandResponse.nickname;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CommandResponsePayload.prototype, "participantId", {
        get: function () {
            return this.privCommandResponse.participantId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CommandResponsePayload.prototype, "roomid", {
        get: function () {
            return this.privCommandResponse.roomid;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CommandResponsePayload.prototype, "value", {
        get: function () {
            return this.privCommandResponse.value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CommandResponsePayload.prototype, "token", {
        get: function () {
            return this.privCommandResponse.token;
        },
        enumerable: false,
        configurable: true
    });
    return CommandResponsePayload;
}());
exports.CommandResponsePayload = CommandResponsePayload;



/***/ }),
/* 221 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParticipantPayloadResponse = exports.ParticipantsListPayloadResponse = void 0;
var ParticipantsListPayloadResponse = /** @class */ (function () {
    function ParticipantsListPayloadResponse(json) {
        this.privParticipantsPayloadResponse = JSON.parse(json);
    }
    ParticipantsListPayloadResponse.fromJSON = function (json) {
        return new ParticipantsListPayloadResponse(json);
    };
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "roomid", {
        get: function () {
            return this.privParticipantsPayloadResponse.roomid;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "id", {
        get: function () {
            return this.privParticipantsPayloadResponse.id;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "command", {
        get: function () {
            return this.privParticipantsPayloadResponse.command;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "participants", {
        get: function () {
            return this.privParticipantsPayloadResponse.participants;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "token", {
        get: function () {
            return this.privParticipantsPayloadResponse.token;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "translateTo", {
        get: function () {
            return this.privParticipantsPayloadResponse.translateTo;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "profanityFilter", {
        get: function () {
            return this.privParticipantsPayloadResponse.profanityFilter;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "roomProfanityFilter", {
        get: function () {
            return this.privParticipantsPayloadResponse.roomProfanityFilter;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "roomLocked", {
        get: function () {
            return this.privParticipantsPayloadResponse.roomLocked;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "muteAll", {
        get: function () {
            return this.privParticipantsPayloadResponse.muteAll;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantsListPayloadResponse.prototype, "type", {
        get: function () {
            return this.privParticipantsPayloadResponse.type;
        },
        enumerable: false,
        configurable: true
    });
    return ParticipantsListPayloadResponse;
}());
exports.ParticipantsListPayloadResponse = ParticipantsListPayloadResponse;
// tslint:disable-next-line: max-classes-per-file
var ParticipantPayloadResponse = /** @class */ (function () {
    function ParticipantPayloadResponse(json) {
        this.privParticipantPayloadResponse = JSON.parse(json);
    }
    ParticipantPayloadResponse.fromJSON = function (json) {
        return new ParticipantPayloadResponse(json);
    };
    Object.defineProperty(ParticipantPayloadResponse.prototype, "nickname", {
        get: function () {
            return this.privParticipantPayloadResponse.nickname;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantPayloadResponse.prototype, "locale", {
        get: function () {
            return this.privParticipantPayloadResponse.locale;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantPayloadResponse.prototype, "usetts", {
        get: function () {
            return this.privParticipantPayloadResponse.usetts;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantPayloadResponse.prototype, "ismuted", {
        get: function () {
            return this.privParticipantPayloadResponse.ismuted;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantPayloadResponse.prototype, "ishost", {
        get: function () {
            return this.privParticipantPayloadResponse.ishost;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantPayloadResponse.prototype, "participantId", {
        get: function () {
            return this.privParticipantPayloadResponse.participantId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ParticipantPayloadResponse.prototype, "avatar", {
        get: function () {
            return this.privParticipantPayloadResponse.avatar;
        },
        enumerable: false,
        configurable: true
    });
    return ParticipantPayloadResponse;
}());
exports.ParticipantPayloadResponse = ParticipantPayloadResponse;



/***/ }),
/* 222 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextResponsePayload = exports.SpeechResponsePayload = void 0;
var SpeechResponsePayload = /** @class */ (function () {
    function SpeechResponsePayload(json) {
        this.privSpeechResponse = JSON.parse(json);
    }
    SpeechResponsePayload.fromJSON = function (json) {
        return new SpeechResponsePayload(json);
    };
    Object.defineProperty(SpeechResponsePayload.prototype, "recognition", {
        get: function () {
            return this.privSpeechResponse.recognition;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechResponsePayload.prototype, "translations", {
        get: function () {
            return this.privSpeechResponse.translations;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechResponsePayload.prototype, "id", {
        get: function () {
            return this.privSpeechResponse.id;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechResponsePayload.prototype, "language", {
        get: function () {
            return this.privSpeechResponse.language;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechResponsePayload.prototype, "nickname", {
        get: function () {
            return this.privSpeechResponse.nickname;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechResponsePayload.prototype, "participantId", {
        get: function () {
            return this.privSpeechResponse.participantId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechResponsePayload.prototype, "roomid", {
        get: function () {
            return this.privSpeechResponse.roomid;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechResponsePayload.prototype, "timestamp", {
        get: function () {
            return this.privSpeechResponse.timestamp;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechResponsePayload.prototype, "type", {
        get: function () {
            return this.privSpeechResponse.type;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeechResponsePayload.prototype, "isFinal", {
        get: function () {
            return this.privSpeechResponse.type === "final";
        },
        enumerable: false,
        configurable: true
    });
    return SpeechResponsePayload;
}());
exports.SpeechResponsePayload = SpeechResponsePayload;
// tslint:disable-next-line: max-classes-per-file
var TextResponsePayload = /** @class */ (function () {
    function TextResponsePayload(json) {
        this.privTextResponse = JSON.parse(json);
    }
    TextResponsePayload.fromJSON = function (json) {
        return new TextResponsePayload(json);
    };
    Object.defineProperty(TextResponsePayload.prototype, "originalText", {
        get: function () {
            return this.privTextResponse.originalText;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextResponsePayload.prototype, "translations", {
        get: function () {
            return this.privTextResponse.translations;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextResponsePayload.prototype, "id", {
        get: function () {
            return this.privTextResponse.id;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextResponsePayload.prototype, "language", {
        get: function () {
            return this.privTextResponse.language;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextResponsePayload.prototype, "nickname", {
        get: function () {
            return this.privTextResponse.nickname;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextResponsePayload.prototype, "participantId", {
        get: function () {
            return this.privTextResponse.participantId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextResponsePayload.prototype, "roomid", {
        get: function () {
            return this.privTextResponse.roomid;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextResponsePayload.prototype, "timestamp", {
        get: function () {
            return this.privTextResponse.timestamp;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TextResponsePayload.prototype, "type", {
        get: function () {
            return this.privTextResponse.type;
        },
        enumerable: false,
        configurable: true
    });
    return TextResponsePayload;
}());
exports.TextResponsePayload = TextResponsePayload;



/***/ }),
/* 223 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranscriberRecognizer = void 0;
var Exports_1 = __webpack_require__(4);
var Contracts_1 = __webpack_require__(63);
var Exports_2 = __webpack_require__(61);
var Exports_3 = __webpack_require__(53);
var TranscriberRecognizer = /** @class */ (function (_super) {
    __extends(TranscriberRecognizer, _super);
    /**
     * TranscriberRecognizer constructor.
     * @constructor
     * @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer
     */
    function TranscriberRecognizer(speechTranslationConfig, audioConfig) {
        var _this = this;
        var speechTranslationConfigImpl = speechTranslationConfig;
        Contracts_1.Contracts.throwIfNull(speechTranslationConfigImpl, "speechTranslationConfig");
        Contracts_1.Contracts.throwIfNullOrWhitespace(speechTranslationConfigImpl.speechRecognitionLanguage, Exports_2.PropertyId[Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage]);
        _this = _super.call(this, audioConfig, speechTranslationConfigImpl.properties, new Exports_3.TranscriberConnectionFactory()) || this;
        _this.privDisposedRecognizer = false;
        return _this;
    }
    TranscriberRecognizer.prototype.getConversationInfo = function () {
        Contracts_1.Contracts.throwIfNullOrUndefined(this.privConversation, "Conversation");
        return this.privConversation.conversationInfo;
    };
    Object.defineProperty(TranscriberRecognizer.prototype, "authorizationToken", {
        get: function () {
            return this.properties.getProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token);
        },
        set: function (token) {
            Contracts_1.Contracts.throwIfNullOrWhitespace(token, "token");
            this.properties.setProperty(Exports_2.PropertyId.SpeechServiceAuthorization_Token, token);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranscriberRecognizer.prototype, "conversation", {
        set: function (c) {
            Contracts_1.Contracts.throwIfNullOrUndefined(c, "Conversation");
            this.privConversation = c;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranscriberRecognizer.prototype, "speechRecognitionLanguage", {
        get: function () {
            Contracts_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
            return this.properties.getProperty(Exports_2.PropertyId.SpeechServiceConnection_RecoLanguage);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TranscriberRecognizer.prototype, "properties", {
        get: function () {
            return this.privProperties;
        },
        enumerable: false,
        configurable: true
    });
    TranscriberRecognizer.prototype.startContinuousRecognitionAsync = function (cb, err) {
        Exports_1.marshalPromiseToCallbacks(this.startContinuousRecognitionAsyncImpl(Exports_3.RecognitionMode.Conversation), cb, err);
    };
    TranscriberRecognizer.prototype.stopContinuousRecognitionAsync = function (cb, err) {
        Exports_1.marshalPromiseToCallbacks(this.stopContinuousRecognitionAsyncImpl(), cb, err);
    };
    TranscriberRecognizer.prototype.close = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!this.privDisposedRecognizer) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.dispose(true)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    // Push async join/leave conversation message via serviceRecognizer
    TranscriberRecognizer.prototype.pushConversationEvent = function (conversationInfo, command) {
        return __awaiter(this, void 0, void 0, function () {
            var reco;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        reco = (this.privReco);
                        Contracts_1.Contracts.throwIfNullOrUndefined(reco, "serviceRecognizer");
                        return [4 /*yield*/, reco.sendSpeechEventAsync(conversationInfo, command)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    TranscriberRecognizer.prototype.connectCallbacks = function (transcriber) {
        this.canceled = function (s, e) {
            if (!!transcriber.canceled) {
                transcriber.canceled(transcriber, e);
            }
        };
        this.conversationCanceled = function (s, e) {
            if (!!transcriber.conversationCanceled) {
                transcriber.conversationCanceled(transcriber, e);
            }
        };
        this.recognizing = function (s, e) {
            if (!!transcriber.transcribing) {
                transcriber.transcribing(transcriber, e);
            }
        };
        this.recognized = function (s, e) {
            if (!!transcriber.transcribed) {
                transcriber.transcribed(transcriber, e);
            }
        };
        this.conversationStarted = function (s, e) {
            if (!!transcriber.conversationStarted) {
                transcriber.conversationStarted(transcriber, e);
            }
        };
        this.conversationStopped = function (s, e) {
            if (!!transcriber.conversationStopped) {
                transcriber.conversationStopped(transcriber, e);
            }
        };
        this.sessionStarted = function (s, e) {
            if (!!transcriber.sessionStarted) {
                transcriber.sessionStarted(transcriber, e);
            }
        };
        this.sessionStopped = function (s, e) {
            if (!!transcriber.sessionStopped) {
                transcriber.sessionStopped(transcriber, e);
            }
        };
    };
    TranscriberRecognizer.prototype.disconnectCallbacks = function () {
        this.canceled = undefined;
        this.recognizing = undefined;
        this.recognized = undefined;
        this.sessionStarted = undefined;
        this.sessionStopped = undefined;
        this.conversationCanceled = undefined;
        this.conversationStarted = undefined;
        this.conversationStopped = undefined;
    };
    /**
     * Disposes any resources held by the object.
     * @member ConversationTranscriber.prototype.dispose
     * @function
     * @public
     * @param {boolean} disposing - true if disposing the object.
     */
    TranscriberRecognizer.prototype.dispose = function (disposing) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privDisposedRecognizer) {
                            return [2 /*return*/];
                        }
                        if (!disposing) return [3 /*break*/, 2];
                        this.privDisposedRecognizer = true;
                        return [4 /*yield*/, this.implRecognizerStop()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [4 /*yield*/, _super.prototype.dispose.call(this, disposing)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    TranscriberRecognizer.prototype.createRecognizerConfig = function (speechConfig) {
        return new Exports_3.RecognizerConfig(speechConfig, this.properties);
    };
    TranscriberRecognizer.prototype.createServiceRecognizer = function (authentication, connectionFactory, audioConfig, recognizerConfig) {
        var configImpl = audioConfig;
        return new Exports_3.TranscriptionServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);
    };
    return TranscriberRecognizer;
}(Exports_2.Recognizer));
exports.TranscriberRecognizer = TranscriberRecognizer;



/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisAudioMetadata = exports.MetadataType = void 0;
var MetadataType;
(function (MetadataType) {
    MetadataType["WordBoundary"] = "WordBoundary";
    MetadataType["Bookmark"] = "Bookmark";
    MetadataType["Viseme"] = "Viseme";
})(MetadataType = exports.MetadataType || (exports.MetadataType = {}));
var SynthesisAudioMetadata = /** @class */ (function () {
    function SynthesisAudioMetadata(json) {
        this.privSynthesisAudioMetadata = JSON.parse(json);
    }
    SynthesisAudioMetadata.fromJSON = function (json) {
        return new SynthesisAudioMetadata(json);
    };
    Object.defineProperty(SynthesisAudioMetadata.prototype, "Metadata", {
        get: function () {
            return this.privSynthesisAudioMetadata.Metadata;
        },
        enumerable: false,
        configurable: true
    });
    return SynthesisAudioMetadata;
}());
exports.SynthesisAudioMetadata = SynthesisAudioMetadata;



/***/ }),
/* 225 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisTurn = void 0;
var Exports_1 = __webpack_require__(4);
var AudioOutputStream_1 = __webpack_require__(73);
var SynthesisAdapterBase_1 = __webpack_require__(226);
var SynthesisEvents_1 = __webpack_require__(227);
var SynthesisTurn = /** @class */ (function () {
    function SynthesisTurn() {
        var _this = this;
        this.privIsDisposed = false;
        this.privIsSynthesizing = false;
        this.privIsSynthesisEnded = false;
        this.privBytesReceived = 0;
        this.privInTurn = false;
        this.privTextOffset = 0;
        this.privNextSearchTextIndex = 0;
        this.onPreConnectionStart = function (authFetchEventId, connectionId) {
            _this.privAuthFetchEventId = authFetchEventId;
            _this.onEvent(new SynthesisEvents_1.ConnectingToSynthesisServiceEvent(_this.privRequestId, _this.privAuthFetchEventId));
        };
        this.onAuthCompleted = function (isError, error) {
            if (isError) {
                _this.onComplete();
            }
        };
        this.onConnectionEstablishCompleted = function (statusCode, reason) {
            if (statusCode === 200) {
                _this.onEvent(new SynthesisEvents_1.SynthesisStartedEvent(_this.requestId, _this.privAuthFetchEventId));
                _this.privBytesReceived = 0;
                return;
            }
            else if (statusCode === 403) {
                _this.onComplete();
            }
        };
        this.onServiceResponseMessage = function (responseJson) {
            var response = JSON.parse(responseJson);
            _this.streamId = response.audio.streamId;
        };
        this.onServiceTurnEndResponse = function () {
            _this.privInTurn = false;
            _this.privTurnDeferral.resolve();
            _this.onComplete();
        };
        this.onServiceTurnStartResponse = function () {
            if (!!_this.privTurnDeferral && !!_this.privInTurn) {
                // What? How are we starting a turn with another not done?
                _this.privTurnDeferral.reject("Another turn started before current completed.");
                // Avoid UnhandledPromiseRejection if privTurnDeferral is not being awaited
                /* tslint:disable:no-empty */
                _this.privTurnDeferral.promise.then().catch(function () { });
            }
            _this.privInTurn = true;
            _this.privTurnDeferral = new Exports_1.Deferred();
        };
        this.dispose = function (error) {
            if (!_this.privIsDisposed) {
                // we should have completed by now. If we did not its an unknown error.
                _this.privIsDisposed = true;
            }
        };
        this.onEvent = function (event) {
            Exports_1.Events.instance.onEvent(event);
        };
        this.onComplete = function () {
            if (_this.privIsSynthesizing) {
                _this.privIsSynthesizing = false;
                _this.privIsSynthesisEnded = true;
                _this.privAudioOutputStream.close();
                _this.privInTurn = false;
                if (_this.privTurnAudioDestination !== undefined) {
                    _this.privTurnAudioDestination.close();
                    _this.privTurnAudioDestination = undefined;
                }
            }
        };
        this.privRequestId = Exports_1.createNoDashGuid();
        this.privTurnDeferral = new Exports_1.Deferred();
        // We're not in a turn, so resolve.
        this.privTurnDeferral.resolve();
    }
    Object.defineProperty(SynthesisTurn.prototype, "requestId", {
        get: function () {
            return this.privRequestId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisTurn.prototype, "streamId", {
        get: function () {
            return this.privStreamId;
        },
        set: function (value) {
            this.privStreamId = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisTurn.prototype, "audioOutputFormat", {
        get: function () {
            return this.privAudioOutputFormat;
        },
        set: function (format) {
            this.privAudioOutputFormat = format;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisTurn.prototype, "turnCompletionPromise", {
        get: function () {
            return this.privTurnDeferral.promise;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisTurn.prototype, "isSynthesisEnded", {
        get: function () {
            return this.privIsSynthesisEnded;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisTurn.prototype, "isSynthesizing", {
        get: function () {
            return this.privIsSynthesizing;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisTurn.prototype, "currentTextOffset", {
        get: function () {
            return this.privTextOffset;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisTurn.prototype, "bytesReceived", {
        // The number of bytes received for current turn
        get: function () {
            return this.privBytesReceived;
        },
        enumerable: false,
        configurable: true
    });
    SynthesisTurn.prototype.getAllReceivedAudio = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!this.privReceivedAudio) {
                            return [2 /*return*/, Promise.resolve(this.privReceivedAudio)];
                        }
                        if (!this.privIsSynthesisEnded) {
                            return [2 /*return*/, null];
                        }
                        return [4 /*yield*/, this.readAllAudioFromStream()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, Promise.resolve(this.privReceivedAudio)];
                }
            });
        });
    };
    SynthesisTurn.prototype.getAllReceivedAudioWithHeader = function () {
        return __awaiter(this, void 0, void 0, function () {
            var audio;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!this.privReceivedAudioWithHeader) {
                            return [2 /*return*/, this.privReceivedAudioWithHeader];
                        }
                        if (!this.privIsSynthesisEnded) {
                            return [2 /*return*/, null];
                        }
                        if (!this.audioOutputFormat.hasHeader) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.getAllReceivedAudio()];
                    case 1:
                        audio = _a.sent();
                        this.privReceivedAudioWithHeader = SynthesisAdapterBase_1.SynthesisAdapterBase.addHeader(audio, this.audioOutputFormat);
                        return [2 /*return*/, this.privReceivedAudioWithHeader];
                    case 2: return [2 /*return*/, this.getAllReceivedAudio()];
                }
            });
        });
    };
    SynthesisTurn.prototype.startNewSynthesis = function (requestId, rawText, isSSML, audioDestination) {
        this.privIsSynthesisEnded = false;
        this.privIsSynthesizing = true;
        this.privRequestId = requestId;
        this.privRawText = rawText;
        this.privIsSSML = isSSML;
        this.privAudioOutputStream = new AudioOutputStream_1.PullAudioOutputStreamImpl();
        this.privAudioOutputStream.format = this.privAudioOutputFormat;
        this.privReceivedAudio = null;
        this.privReceivedAudioWithHeader = null;
        this.privBytesReceived = 0;
        this.privTextOffset = 0;
        this.privNextSearchTextIndex = 0;
        this.privPartialVisemeAnimation = "";
        if (audioDestination !== undefined) {
            this.privTurnAudioDestination = audioDestination;
            this.privTurnAudioDestination.format = this.privAudioOutputFormat;
        }
        this.onEvent(new SynthesisEvents_1.SynthesisTriggeredEvent(this.requestId, undefined, audioDestination === undefined ? undefined : audioDestination.id()));
    };
    SynthesisTurn.prototype.onAudioChunkReceived = function (data) {
        if (this.isSynthesizing) {
            this.privAudioOutputStream.write(data);
            this.privBytesReceived += data.byteLength;
            if (this.privTurnAudioDestination !== undefined) {
                this.privTurnAudioDestination.write(data);
            }
        }
    };
    SynthesisTurn.prototype.onWordBoundaryEvent = function (text) {
        this.updateTextOffset(text);
    };
    SynthesisTurn.prototype.onVisemeMetadataReceived = function (metadata) {
        if (metadata.Data.AnimationChunk !== undefined) {
            this.privPartialVisemeAnimation += metadata.Data.AnimationChunk;
        }
    };
    SynthesisTurn.prototype.onStopSynthesizing = function () {
        this.onComplete();
    };
    /**
     * Gets the viseme animation string (merged from animation chunk), and clears the internal
     * partial animation.
     */
    SynthesisTurn.prototype.getAndClearVisemeAnimation = function () {
        var animation = this.privPartialVisemeAnimation;
        this.privPartialVisemeAnimation = "";
        return animation;
    };
    SynthesisTurn.prototype.updateTextOffset = function (text) {
        if (this.privTextOffset >= 0) {
            this.privTextOffset = this.privRawText.indexOf(text, this.privNextSearchTextIndex);
            if (this.privTextOffset >= 0) {
                this.privNextSearchTextIndex = this.privTextOffset + text.length;
            }
            if (this.privIsSSML) {
                if (this.privRawText.indexOf("<", this.privTextOffset + 1) > this.privRawText.indexOf(">", this.privTextOffset + 1)) {
                    this.updateTextOffset(text);
                }
            }
        }
    };
    SynthesisTurn.prototype.readAllAudioFromStream = function () {
        return __awaiter(this, void 0, void 0, function () {
            var e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.privIsSynthesisEnded) return [3 /*break*/, 4];
                        this.privReceivedAudio = new ArrayBuffer(this.bytesReceived);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.privAudioOutputStream.read(this.privReceivedAudio)];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        e_1 = _a.sent();
                        this.privReceivedAudio = new ArrayBuffer(0);
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    return SynthesisTurn;
}());
exports.SynthesisTurn = SynthesisTurn;



/***/ }),
/* 226 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisAdapterBase = void 0;
var Exports_1 = __webpack_require__(4);
var Exports_2 = __webpack_require__(61);
var Exports_3 = __webpack_require__(53);
var SpeechConnectionMessage_Internal_1 = __webpack_require__(173);
var SynthesisAdapterBase = /** @class */ (function () {
    function SynthesisAdapterBase(authentication, connectionFactory, synthesizerConfig, speechSynthesizer, audioDestination) {
        var _this = this;
        this.speakOverride = undefined;
        this.receiveMessageOverride = undefined;
        this.connectImplOverride = undefined;
        this.configConnectionOverride = undefined;
        this.sendSynthesisContext = function (connection) {
            var synthesisContextJson = _this.synthesisContext.toJSON();
            if (synthesisContextJson) {
                return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_1.MessageType.Text, "synthesis.context", _this.privSynthesisTurn.requestId, "application/json", synthesisContextJson));
            }
            return;
        };
        this.sendSpeechServiceConfig = function (connection, SpeechServiceConfigJson) {
            if (SpeechServiceConfigJson) {
                return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_1.MessageType.Text, "speech.config", _this.privSynthesisTurn.requestId, "application/json", SpeechServiceConfigJson));
            }
        };
        this.sendSsmlMessage = function (connection, ssml, requestId) {
            return connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(Exports_1.MessageType.Text, "ssml", requestId, "application/ssml+xml", ssml));
        };
        if (!authentication) {
            throw new Exports_1.ArgumentNullError("authentication");
        }
        if (!connectionFactory) {
            throw new Exports_1.ArgumentNullError("connectionFactory");
        }
        if (!synthesizerConfig) {
            throw new Exports_1.ArgumentNullError("synthesizerConfig");
        }
        this.privAuthentication = authentication;
        this.privConnectionFactory = connectionFactory;
        this.privSynthesizerConfig = synthesizerConfig;
        this.privIsDisposed = false;
        this.privSpeechSynthesizer = speechSynthesizer;
        this.privSessionAudioDestination = audioDestination;
        this.privSynthesisTurn = new Exports_3.SynthesisTurn();
        this.privConnectionEvents = new Exports_1.EventSource();
        this.privServiceEvents = new Exports_1.EventSource();
        this.privSynthesisContext = new Exports_3.SynthesisContext(this.privSpeechSynthesizer);
        this.privAgentConfig = new Exports_3.AgentConfig();
        this.connectionEvents.attach(function (connectionEvent) {
            if (connectionEvent.name === "ConnectionClosedEvent") {
                var connectionClosedEvent = connectionEvent;
                if (connectionClosedEvent.statusCode !== 1000) {
                    _this.cancelSynthesisLocal(Exports_2.CancellationReason.Error, connectionClosedEvent.statusCode === 1007 ? Exports_2.CancellationErrorCode.BadRequestParameters : Exports_2.CancellationErrorCode.ConnectionFailure, connectionClosedEvent.reason + " websocket error code: " + connectionClosedEvent.statusCode);
                }
            }
        });
    }
    Object.defineProperty(SynthesisAdapterBase.prototype, "synthesisContext", {
        get: function () {
            return this.privSynthesisContext;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisAdapterBase.prototype, "agentConfig", {
        get: function () {
            return this.privAgentConfig;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisAdapterBase.prototype, "connectionEvents", {
        get: function () {
            return this.privConnectionEvents;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisAdapterBase.prototype, "serviceEvents", {
        get: function () {
            return this.privServiceEvents;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisAdapterBase.prototype, "activityTemplate", {
        get: function () { return this.privActivityTemplate; },
        set: function (messagePayload) { this.privActivityTemplate = messagePayload; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisAdapterBase.prototype, "audioOutputFormat", {
        set: function (format) {
            this.privAudioOutputFormat = format;
            this.privSynthesisTurn.audioOutputFormat = format;
            if (this.privSessionAudioDestination !== undefined) {
                this.privSessionAudioDestination.format = format;
            }
            if (this.synthesisContext !== undefined) {
                this.synthesisContext.audioOutputFormat = format;
            }
        },
        enumerable: false,
        configurable: true
    });
    SynthesisAdapterBase.addHeader = function (audio, format) {
        if (!format.hasHeader) {
            return audio;
        }
        format.updateHeader(audio.byteLength);
        var tmp = new Uint8Array(audio.byteLength + format.header.byteLength);
        tmp.set(new Uint8Array(format.header), 0);
        tmp.set(new Uint8Array(audio), format.header.byteLength);
        return tmp.buffer;
    };
    SynthesisAdapterBase.prototype.isDisposed = function () {
        return this.privIsDisposed;
    };
    SynthesisAdapterBase.prototype.dispose = function (reason) {
        return __awaiter(this, void 0, void 0, function () {
            var connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.privIsDisposed = true;
                        if (this.privSessionAudioDestination !== undefined) {
                            this.privSessionAudioDestination.close();
                        }
                        if (!this.privConnectionConfigurationPromise) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.privConnectionConfigurationPromise];
                    case 1:
                        connection = _a.sent();
                        return [4 /*yield*/, connection.dispose(reason)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    SynthesisAdapterBase.prototype.connect = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.connectImpl()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    SynthesisAdapterBase.prototype.sendNetworkMessage = function (path, payload) {
        return __awaiter(this, void 0, void 0, function () {
            var type, contentType, connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        type = typeof payload === "string" ? Exports_1.MessageType.Text : Exports_1.MessageType.Binary;
                        contentType = typeof payload === "string" ? "application/json" : "";
                        return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _a.sent();
                        return [2 /*return*/, connection.send(new SpeechConnectionMessage_Internal_1.SpeechConnectionMessage(type, path, this.privSynthesisTurn.requestId, contentType, payload))];
                }
            });
        });
    };
    SynthesisAdapterBase.prototype.Speak = function (text, isSSML, requestId, successCallback, errorCallBack, audioDestination) {
        return __awaiter(this, void 0, void 0, function () {
            var ssml, connection, synthesisStartEventArgs, messageRetrievalPromise, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (isSSML) {
                            ssml = text;
                        }
                        else {
                            ssml = this.privSpeechSynthesizer.buildSsml(text);
                        }
                        if (this.speakOverride !== undefined) {
                            return [2 /*return*/, this.speakOverride(ssml, requestId, successCallback, errorCallBack)];
                        }
                        this.privSuccessCallback = successCallback;
                        this.privErrorCallback = errorCallBack;
                        this.privSynthesisTurn.startNewSynthesis(requestId, text, isSSML, audioDestination);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 6, , 7]);
                        return [4 /*yield*/, this.connectImpl()];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.fetchConnection()];
                    case 3:
                        connection = _a.sent();
                        return [4 /*yield*/, this.sendSynthesisContext(connection)];
                    case 4:
                        _a.sent();
                        return [4 /*yield*/, this.sendSsmlMessage(connection, ssml, requestId)];
                    case 5:
                        _a.sent();
                        synthesisStartEventArgs = new Exports_2.SpeechSynthesisEventArgs(new Exports_2.SpeechSynthesisResult(requestId, Exports_2.ResultReason.SynthesizingAudioStarted));
                        if (!!this.privSpeechSynthesizer.synthesisStarted) {
                            this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer, synthesisStartEventArgs);
                        }
                        messageRetrievalPromise = this.receiveMessage();
                        return [3 /*break*/, 7];
                    case 6:
                        e_1 = _a.sent();
                        this.cancelSynthesisLocal(Exports_2.CancellationReason.Error, Exports_2.CancellationErrorCode.ConnectionFailure, e_1);
                        return [2 /*return*/, Promise.reject(e_1)];
                    case 7: return [2 /*return*/];
                }
            });
        });
    };
    // Cancels synthesis.
    SynthesisAdapterBase.prototype.cancelSynthesis = function (requestId, cancellationReason, errorCode, error) {
        var properties = new Exports_2.PropertyCollection();
        properties.setProperty(Exports_3.CancellationErrorCodePropertyName, Exports_2.CancellationErrorCode[errorCode]);
        var result = new Exports_2.SpeechSynthesisResult(requestId, Exports_2.ResultReason.Canceled, undefined, error, properties);
        if (!!this.privSpeechSynthesizer.SynthesisCanceled) {
            var cancelEvent = new Exports_2.SpeechSynthesisEventArgs(result);
            try {
                this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer, cancelEvent);
                /* tslint:disable:no-empty */
            }
            catch (_a) { }
        }
        if (!!this.privSuccessCallback) {
            try {
                this.privSuccessCallback(result);
                /* tslint:disable:no-empty */
            }
            catch (_b) { }
        }
    };
    // Cancels synthesis.
    SynthesisAdapterBase.prototype.cancelSynthesisLocal = function (cancellationReason, errorCode, error) {
        if (!!this.privSynthesisTurn.isSynthesizing) {
            this.privSynthesisTurn.onStopSynthesizing();
            this.cancelSynthesis(this.privSynthesisTurn.requestId, cancellationReason, errorCode, error);
        }
    };
    SynthesisAdapterBase.prototype.processTypeSpecificMessages = function (connectionMessage, successCallback, errorCallBack) {
        return true;
    };
    SynthesisAdapterBase.prototype.receiveMessage = function () {
        return __awaiter(this, void 0, void 0, function () {
            var connection, message, connectionMessage, _a, audioWithHeader, ev, metadataList, _i, metadataList_1, metadata, wordBoundaryEventArgs, bookmarkEventArgs, visemeEventArgs, result, audioBuffer, error_1, e_2;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 14, , 15]);
                        return [4 /*yield*/, this.fetchConnection()];
                    case 1:
                        connection = _b.sent();
                        return [4 /*yield*/, connection.read()];
                    case 2:
                        message = _b.sent();
                        if (this.receiveMessageOverride !== undefined) {
                            return [2 /*return*/, this.receiveMessageOverride()];
                        }
                        if (this.privIsDisposed) {
                            // We're done.
                            return [2 /*return*/];
                        }
                        // indicates we are draining the queue and it came with no message;
                        if (!message) {
                            if (!this.privSynthesisTurn.isSynthesizing) {
                                return [2 /*return*/];
                            }
                            else {
                                return [2 /*return*/, this.receiveMessage()];
                            }
                        }
                        this.privServiceHasSentMessage = true;
                        connectionMessage = SpeechConnectionMessage_Internal_1.SpeechConnectionMessage.fromConnectionMessage(message);
                        if (!(connectionMessage.requestId.toLowerCase() === this.privSynthesisTurn.requestId.toLowerCase())) return [3 /*break*/, 13];
                        _a = connectionMessage.path.toLowerCase();
                        switch (_a) {
                            case "turn.start": return [3 /*break*/, 3];
                            case "response": return [3 /*break*/, 4];
                            case "audio": return [3 /*break*/, 5];
                            case "audio.metadata": return [3 /*break*/, 6];
                            case "turn.end": return [3 /*break*/, 7];
                        }
                        return [3 /*break*/, 12];
                    case 3:
                        this.privSynthesisTurn.onServiceTurnStartResponse();
                        return [3 /*break*/, 13];
                    case 4:
                        this.privSynthesisTurn.onServiceResponseMessage(connectionMessage.textBody);
                        return [3 /*break*/, 13];
                    case 5:
                        if (this.privSynthesisTurn.streamId.toLowerCase() === connectionMessage.streamId.toLowerCase()
                            && !!connectionMessage.binaryBody) {
                            this.privSynthesisTurn.onAudioChunkReceived(connectionMessage.binaryBody);
                            if (!!this.privSpeechSynthesizer.synthesizing) {
                                try {
                                    audioWithHeader = SynthesisAdapterBase.addHeader(connectionMessage.binaryBody, this.privSynthesisTurn.audioOutputFormat);
                                    ev = new Exports_2.SpeechSynthesisEventArgs(new Exports_2.SpeechSynthesisResult(this.privSynthesisTurn.requestId, Exports_2.ResultReason.SynthesizingAudio, audioWithHeader));
                                    this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer, ev);
                                }
                                catch (error) {
                                    // Not going to let errors in the event handler
                                    // trip things up.
                                }
                            }
                            if (this.privSessionAudioDestination !== undefined) {
                                this.privSessionAudioDestination.write(connectionMessage.binaryBody);
                            }
                        }
                        return [3 /*break*/, 13];
                    case 6:
                        metadataList = Exports_3.SynthesisAudioMetadata.fromJSON(connectionMessage.textBody).Metadata;
                        for (_i = 0, metadataList_1 = metadataList; _i < metadataList_1.length; _i++) {
                            metadata = metadataList_1[_i];
                            switch (metadata.Type) {
                                case Exports_3.MetadataType.WordBoundary:
                                    this.privSynthesisTurn.onWordBoundaryEvent(metadata.Data.text.Text);
                                    wordBoundaryEventArgs = new Exports_2.SpeechSynthesisWordBoundaryEventArgs(metadata.Data.Offset, metadata.Data.text.Text, metadata.Data.text.Length, this.privSynthesisTurn.currentTextOffset);
                                    if (!!this.privSpeechSynthesizer.wordBoundary) {
                                        try {
                                            this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer, wordBoundaryEventArgs);
                                        }
                                        catch (error) {
                                            // Not going to let errors in the event handler
                                            // trip things up.
                                        }
                                    }
                                    break;
                                case Exports_3.MetadataType.Bookmark:
                                    bookmarkEventArgs = new Exports_2.SpeechSynthesisBookmarkEventArgs(metadata.Data.Offset, metadata.Data.Bookmark);
                                    if (!!this.privSpeechSynthesizer.bookmarkReached) {
                                        try {
                                            this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer, bookmarkEventArgs);
                                        }
                                        catch (error) {
                                            // Not going to let errors in the event handler
                                            // trip things up.
                                        }
                                    }
                                    break;
                                case Exports_3.MetadataType.Viseme:
                                    this.privSynthesisTurn.onVisemeMetadataReceived(metadata);
                                    if (metadata.Data.IsLastAnimation) {
                                        visemeEventArgs = new Exports_2.SpeechSynthesisVisemeEventArgs(metadata.Data.Offset, metadata.Data.VisemeId, this.privSynthesisTurn.getAndClearVisemeAnimation());
                                        if (!!this.privSpeechSynthesizer.visemeReceived) {
                                            try {
                                                this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer, visemeEventArgs);
                                            }
                                            catch (error) {
                                                // Not going to let errors in the event handler
                                                // trip things up.
                                            }
                                        }
                                    }
                                    break;
                            }
                        }
                        return [3 /*break*/, 13];
                    case 7:
                        this.privSynthesisTurn.onServiceTurnEndResponse();
                        result = void 0;
                        _b.label = 8;
                    case 8:
                        _b.trys.push([8, 10, , 11]);
                        return [4 /*yield*/, this.privSynthesisTurn.getAllReceivedAudioWithHeader()];
                    case 9:
                        audioBuffer = _b.sent();
                        result = new Exports_2.SpeechSynthesisResult(this.privSynthesisTurn.requestId, Exports_2.ResultReason.SynthesizingAudioCompleted, audioBuffer);
                        if (!!this.privSuccessCallback) {
                            this.privSuccessCallback(result);
                        }
                        return [3 /*break*/, 11];
                    case 10:
                        error_1 = _b.sent();
                        if (!!this.privErrorCallback) {
                            this.privErrorCallback(error_1);
                        }
                        return [3 /*break*/, 11];
                    case 11:
                        if (this.privSpeechSynthesizer.synthesisCompleted) {
                            try {
                                this.privSpeechSynthesizer.synthesisCompleted(this.privSpeechSynthesizer, new Exports_2.SpeechSynthesisEventArgs(result));
                            }
                            catch (e) {
                                // Not going to let errors in the event handler
                                // trip things up.
                            }
                        }
                        return [3 /*break*/, 13];
                    case 12:
                        if (!this.processTypeSpecificMessages(connectionMessage)) {
                            // here are some messages that the derived class has not processed, dispatch them to connect class
                            if (!!this.privServiceEvents) {
                                this.serviceEvents.onEvent(new Exports_1.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));
                            }
                        }
                        _b.label = 13;
                    case 13: return [2 /*return*/, this.receiveMessage()];
                    case 14:
                        e_2 = _b.sent();
                        return [3 /*break*/, 15];
                    case 15: return [2 /*return*/];
                }
            });
        });
    };
    SynthesisAdapterBase.prototype.connectImpl = function (isUnAuthorized) {
        var _this = this;
        if (isUnAuthorized === void 0) { isUnAuthorized = false; }
        if (this.privConnectionPromise) {
            return this.privConnectionPromise.then(function (connection) {
                if (connection.state() === Exports_1.ConnectionState.Disconnected) {
                    _this.privConnectionId = null;
                    _this.privConnectionPromise = null;
                    _this.privServiceHasSentMessage = false;
                    return _this.connectImpl();
                }
                return _this.privConnectionPromise;
            }, function (error) {
                _this.privConnectionId = null;
                _this.privConnectionPromise = null;
                _this.privServiceHasSentMessage = false;
                return _this.connectImpl();
            });
        }
        this.privAuthFetchEventId = Exports_1.createNoDashGuid();
        this.privConnectionId = Exports_1.createNoDashGuid();
        this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId, this.privConnectionId);
        var authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId);
        this.privConnectionPromise = authPromise.then(function (result) { return __awaiter(_this, void 0, void 0, function () {
            var connection, response;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.privSynthesisTurn.onAuthCompleted(false)];
                    case 1:
                        _a.sent();
                        connection = this.privConnectionFactory.create(this.privSynthesizerConfig, result, this.privConnectionId);
                        // Attach to the underlying event. No need to hold onto the detach pointers as in the event the connection goes away,
                        // it'll stop sending events.
                        connection.events.attach(function (event) {
                            _this.connectionEvents.onEvent(event);
                        });
                        return [4 /*yield*/, connection.open()];
                    case 2:
                        response = _a.sent();
                        if (!(response.statusCode === 200)) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode)];
                    case 3:
                        _a.sent();
                        return [2 /*return*/, Promise.resolve(connection)];
                    case 4:
                        if (!(response.statusCode === 403 && !isUnAuthorized)) return [3 /*break*/, 5];
                        return [2 /*return*/, this.connectImpl(true)];
                    case 5: return [4 /*yield*/, this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode, response.reason)];
                    case 6:
                        _a.sent();
                        return [2 /*return*/, Promise.reject("Unable to contact server. StatusCode: " + response.statusCode + ", " + this.privSynthesizerConfig.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint) + " Reason: " + response.reason)];
                }
            });
        }); }, function (error) { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.privSynthesisTurn.onAuthCompleted(true, error)];
                    case 1:
                        _a.sent();
                        throw new Error(error);
                }
            });
        }); });
        // Attach an empty handler to allow the promise to run in the background while
        // other startup events happen. It'll eventually be awaited on.
        this.privConnectionPromise.catch(function () { });
        return this.privConnectionPromise;
    };
    SynthesisAdapterBase.prototype.fetchConnection = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.privConnectionConfigurationPromise) {
                            return [2 /*return*/, this.privConnectionConfigurationPromise.then(function (connection) {
                                    if (connection.state() === Exports_1.ConnectionState.Disconnected) {
                                        _this.privConnectionId = null;
                                        _this.privConnectionConfigurationPromise = null;
                                        _this.privServiceHasSentMessage = false;
                                        return _this.fetchConnection();
                                    }
                                    return _this.privConnectionConfigurationPromise;
                                }, function (error) {
                                    _this.privConnectionId = null;
                                    _this.privConnectionConfigurationPromise = null;
                                    _this.privServiceHasSentMessage = false;
                                    return _this.fetchConnection();
                                })];
                        }
                        this.privConnectionConfigurationPromise = this.configureConnection();
                        return [4 /*yield*/, this.privConnectionConfigurationPromise];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    // Takes an established websocket connection to the endpoint and sends speech configuration information.
    SynthesisAdapterBase.prototype.configureConnection = function () {
        return __awaiter(this, void 0, void 0, function () {
            var connection;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.connectImpl()];
                    case 1:
                        connection = _a.sent();
                        if (this.configConnectionOverride !== undefined) {
                            return [2 /*return*/, this.configConnectionOverride(connection)];
                        }
                        return [4 /*yield*/, this.sendSpeechServiceConfig(connection, this.privSynthesizerConfig.SpeechServiceConfig.serialize())];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, connection];
                }
            });
        });
    };
    SynthesisAdapterBase.telemetryDataEnabled = true;
    return SynthesisAdapterBase;
}());
exports.SynthesisAdapterBase = SynthesisAdapterBase;



/***/ }),
/* 227 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisStartedEvent = exports.ConnectingToSynthesisServiceEvent = exports.SynthesisTriggeredEvent = exports.SpeechSynthesisEvent = void 0;
// tslint:disable:max-classes-per-file
var Exports_1 = __webpack_require__(4);
var SpeechSynthesisEvent = /** @class */ (function (_super) {
    __extends(SpeechSynthesisEvent, _super);
    function SpeechSynthesisEvent(eventName, requestId, eventType) {
        if (eventType === void 0) { eventType = Exports_1.EventType.Info; }
        var _this = _super.call(this, eventName, eventType) || this;
        _this.privRequestId = requestId;
        return _this;
    }
    Object.defineProperty(SpeechSynthesisEvent.prototype, "requestId", {
        get: function () {
            return this.privRequestId;
        },
        enumerable: false,
        configurable: true
    });
    return SpeechSynthesisEvent;
}(Exports_1.PlatformEvent));
exports.SpeechSynthesisEvent = SpeechSynthesisEvent;
var SynthesisTriggeredEvent = /** @class */ (function (_super) {
    __extends(SynthesisTriggeredEvent, _super);
    function SynthesisTriggeredEvent(requestId, sessionAudioDestinationId, turnAudioDestinationId) {
        var _this = _super.call(this, "SynthesisTriggeredEvent", requestId) || this;
        _this.privSessionAudioDestinationId = sessionAudioDestinationId;
        _this.privTurnAudioDestinationId = turnAudioDestinationId;
        return _this;
    }
    Object.defineProperty(SynthesisTriggeredEvent.prototype, "audioSessionDestinationId", {
        get: function () {
            return this.privSessionAudioDestinationId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesisTriggeredEvent.prototype, "audioTurnDestinationId", {
        get: function () {
            return this.privTurnAudioDestinationId;
        },
        enumerable: false,
        configurable: true
    });
    return SynthesisTriggeredEvent;
}(SpeechSynthesisEvent));
exports.SynthesisTriggeredEvent = SynthesisTriggeredEvent;
var ConnectingToSynthesisServiceEvent = /** @class */ (function (_super) {
    __extends(ConnectingToSynthesisServiceEvent, _super);
    function ConnectingToSynthesisServiceEvent(requestId, authFetchEventId) {
        var _this = _super.call(this, "ConnectingToSynthesisServiceEvent", requestId) || this;
        _this.privAuthFetchEventId = authFetchEventId;
        return _this;
    }
    Object.defineProperty(ConnectingToSynthesisServiceEvent.prototype, "authFetchEventId", {
        get: function () {
            return this.privAuthFetchEventId;
        },
        enumerable: false,
        configurable: true
    });
    return ConnectingToSynthesisServiceEvent;
}(SpeechSynthesisEvent));
exports.ConnectingToSynthesisServiceEvent = ConnectingToSynthesisServiceEvent;
var SynthesisStartedEvent = /** @class */ (function (_super) {
    __extends(SynthesisStartedEvent, _super);
    function SynthesisStartedEvent(requestId, authFetchEventId) {
        var _this = _super.call(this, "SynthesisStartedEvent", requestId) || this;
        _this.privAuthFetchEventId = authFetchEventId;
        return _this;
    }
    Object.defineProperty(SynthesisStartedEvent.prototype, "authFetchEventId", {
        get: function () {
            return this.privAuthFetchEventId;
        },
        enumerable: false,
        configurable: true
    });
    return SynthesisStartedEvent;
}(SpeechSynthesisEvent));
exports.SynthesisStartedEvent = SynthesisStartedEvent;



/***/ }),
/* 228 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisRestAdapter = void 0;
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(61);
var ConnectionFactoryBase_1 = __webpack_require__(123);
var HeaderNames_1 = __webpack_require__(55);
/**
 * Implements methods for speaker recognition classes, sending requests to endpoint
 * and parsing response into expected format
 * @class SynthesisRestAdapter
 */
var SynthesisRestAdapter = /** @class */ (function () {
    function SynthesisRestAdapter(config) {
        var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, undefined);
        if (!endpoint) {
            var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, "westus");
            var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region);
            endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, "https://" + region + ".tts.speech" + hostSuffix);
        }
        this.privUri = endpoint + "/cognitiveservices/voices/list";
        var options = Exports_1.RestConfigBase.requestOptions;
        options.headers[Exports_1.RestConfigBase.configParams.subscriptionKey] = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, undefined);
        this.privRestAdapter = new Exports_1.RestMessageAdapter(options);
    }
    /**
     * Sends list voices request to endpoint.
     * @function
     * @public
     * @param connectionId - guid for connectionId
     * @returns {Promise<IRestResponse>} rest response to status request
     */
    SynthesisRestAdapter.prototype.getVoicesList = function (connectionId) {
        this.privRestAdapter.setHeaders(HeaderNames_1.HeaderNames.ConnectionId, connectionId);
        return this.privRestAdapter.request(Exports_1.RestRequestType.Get, this.privUri);
    };
    return SynthesisRestAdapter;
}());
exports.SynthesisRestAdapter = SynthesisRestAdapter;



/***/ }),
/* 229 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesizerConfig = exports.SynthesisServiceType = void 0;
var Exports_1 = __webpack_require__(53);
var SynthesisServiceType;
(function (SynthesisServiceType) {
    SynthesisServiceType[SynthesisServiceType["Standard"] = 0] = "Standard";
    SynthesisServiceType[SynthesisServiceType["Custom"] = 1] = "Custom";
})(SynthesisServiceType = exports.SynthesisServiceType || (exports.SynthesisServiceType = {}));
var SynthesizerConfig = /** @class */ (function () {
    function SynthesizerConfig(speechServiceConfig, parameters) {
        this.privSynthesisServiceType = SynthesisServiceType.Standard;
        this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new Exports_1.SpeechServiceConfig(new Exports_1.Context(null));
        this.privParameters = parameters;
    }
    Object.defineProperty(SynthesizerConfig.prototype, "parameters", {
        get: function () {
            return this.privParameters;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesizerConfig.prototype, "synthesisServiceType", {
        get: function () {
            return this.privSynthesisServiceType;
        },
        set: function (value) {
            this.privSynthesisServiceType = value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SynthesizerConfig.prototype, "SpeechServiceConfig", {
        get: function () {
            return this.privSpeechServiceConfig;
        },
        enumerable: false,
        configurable: true
    });
    return SynthesizerConfig;
}());
exports.SynthesizerConfig = SynthesizerConfig;



/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisContext = void 0;
/**
 * Represents the JSON used in the synthesis.context message sent to the speech service.
 * The dynamic grammar is always refreshed from the encapsulated dynamic grammar object.
 */
var SynthesisContext = /** @class */ (function () {
    function SynthesisContext(speechSynthesizer) {
        this.privContext = {};
        this.privSpeechSynthesizer = speechSynthesizer;
    }
    /**
     * Adds a section to the synthesis.context object.
     * @param sectionName Name of the section to add.
     * @param value JSON serializable object that represents the value.
     */
    SynthesisContext.prototype.setSection = function (sectionName, value) {
        this.privContext[sectionName] = value;
    };
    Object.defineProperty(SynthesisContext.prototype, "audioOutputFormat", {
        /**
         * Sets the audio output format for synthesis context generation.
         * @param format {AudioOutputFormatImpl} the output format
         */
        set: function (format) {
            this.privAudioOutputFormat = format;
        },
        enumerable: false,
        configurable: true
    });
    SynthesisContext.prototype.toJSON = function () {
        var synthesisSection = this.buildSynthesisContext();
        this.setSection("synthesis", synthesisSection);
        return JSON.stringify(this.privContext);
    };
    SynthesisContext.prototype.buildSynthesisContext = function () {
        return {
            audio: {
                metadataOptions: {
                    bookmarkEnabled: (!!this.privSpeechSynthesizer.bookmarkReached),
                    sentenceBoundaryEnabled: false,
                    visemeEnabled: (!!this.privSpeechSynthesizer.visemeReceived),
                    wordBoundaryEnabled: (!!this.privSpeechSynthesizer.wordBoundary),
                },
                outputFormat: this.privAudioOutputFormat.requestAudioFormatString,
            },
            language: {
                autoDetection: this.privSpeechSynthesizer.autoDetectSourceLanguage
            }
        };
    };
    return SynthesisContext;
}());
exports.SynthesisContext = SynthesisContext;



/***/ }),
/* 231 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerRecognitionConfig = void 0;
var Exports_1 = __webpack_require__(53);
var SpeakerRecognitionConfig = /** @class */ (function () {
    function SpeakerRecognitionConfig(context, parameters) {
        this.privContext = context ? context : new Exports_1.Context(null);
        this.privParameters = parameters;
    }
    Object.defineProperty(SpeakerRecognitionConfig.prototype, "parameters", {
        get: function () {
            return this.privParameters;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SpeakerRecognitionConfig.prototype, "Context", {
        get: function () {
            return this.privContext;
        },
        enumerable: false,
        configurable: true
    });
    return SpeakerRecognitionConfig;
}());
exports.SpeakerRecognitionConfig = SpeakerRecognitionConfig;



/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerIdMessageAdapter = void 0;
var Exports_1 = __webpack_require__(2);
var Exports_2 = __webpack_require__(61);
var ConnectionFactoryBase_1 = __webpack_require__(123);
/**
 * Implements methods for speaker recognition classes, sending requests to endpoint
 * and parsing response into expected format
 * @class SpeakerIdMessageAdapter
 */
var SpeakerIdMessageAdapter = /** @class */ (function () {
    function SpeakerIdMessageAdapter(config) {
        var endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Endpoint, undefined);
        if (!endpoint) {
            var region = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Region, "westus");
            var hostSuffix = ConnectionFactoryBase_1.ConnectionFactoryBase.getHostSuffix(region);
            endpoint = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Host, "https://" + region + ".api.cognitive" + hostSuffix);
        }
        this.privUri = endpoint + "/speaker-recognition/{mode}/{dependency}/profiles";
        var options = Exports_1.RestConfigBase.requestOptions;
        options.headers[Exports_1.RestConfigBase.configParams.subscriptionKey] = config.parameters.getProperty(Exports_2.PropertyId.SpeechServiceConnection_Key, undefined);
        this.privApiVersion = config.parameters.getProperty(Exports_2.PropertyId.SpeakerRecognition_Api_Version, "2021-09-05");
        this.privRestAdapter = new Exports_1.RestMessageAdapter(options);
    }
    /**
     * Sends create profile request to endpoint.
     * @function
     * @param {VoiceProfileType} profileType - type of voice profile to create.
     * @param {string} lang - language/locale of voice profile
     * @public
     * @returns {Promise<IRestResponse>} promised rest response containing id of created profile.
     */
    SpeakerIdMessageAdapter.prototype.createProfile = function (profileType, lang) {
        var uri = this.getOperationUri(profileType);
        return this.privRestAdapter.request(Exports_1.RestRequestType.Post, uri, this.getQueryParams(), { locale: lang });
    };
    /**
     * Sends create enrollment request to endpoint.
     * @function
     * @param {VoiceProfile} profileType - voice profile for which to create new enrollment.
     * @param {IAudioSource} audioSource - audioSource from which to pull data to send
     * @public
     * @returns {Promise<IRestResponse>} rest response to enrollment request.
     */
    SpeakerIdMessageAdapter.prototype.createEnrollment = function (profile, audioSource) {
        var _this = this;
        var uri = this.getOperationUri(profile.profileType) + "/" + profile.profileId + "/enrollments";
        return audioSource.blob.then(function (result) {
            return _this.privRestAdapter.request(Exports_1.RestRequestType.File, uri, _this.getQueryParams({ ignoreMinLength: "true" }), null, result);
        });
    };
    /**
     * Sends verification request to endpoint.
     * @function
     * @param {SpeakerVerificationModel} model - voice model to verify against.
     * @param {IAudioSource} audioSource - audioSource from which to pull data to send
     * @public
     * @returns {Promise<IRestResponse>} rest response to enrollment request.
     */
    SpeakerIdMessageAdapter.prototype.verifySpeaker = function (model, audioSource) {
        return __awaiter(this, void 0, void 0, function () {
            var uri, result, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        uri = this.getOperationUri(model.voiceProfile.profileType) + "/" + model.voiceProfile.profileId + ":verify";
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, audioSource.blob];
                    case 2:
                        result = _a.sent();
                        return [2 /*return*/, this.privRestAdapter.request(Exports_1.RestRequestType.File, uri, this.getQueryParams({ ignoreMinLength: "true" }), null, result)];
                    case 3:
                        e_1 = _a.sent();
                        return [2 /*return*/, Promise.resolve({ data: e_1 })];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Sends identification request to endpoint.
     * @function
     * @param {SpeakerIdentificationModel} model - voice profiles against which to identify.
     * @param {IAudioSource} audioSource - audioSource from which to pull data to send
     * @public
     * @returns {Promise<IRestResponse>} rest response to enrollment request.
     */
    SpeakerIdMessageAdapter.prototype.identifySpeaker = function (model, audioSource) {
        return __awaiter(this, void 0, void 0, function () {
            var uri, result, e_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        uri = this.getOperationUri(Exports_2.VoiceProfileType.TextIndependentIdentification) + ":identifySingleSpeaker";
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, audioSource.blob];
                    case 2:
                        result = _a.sent();
                        return [2 /*return*/, this.privRestAdapter.request(Exports_1.RestRequestType.File, uri, this.getQueryParams({ profileIds: model.voiceProfileIds, ignoreMinLength: "true" }), null, result)];
                    case 3:
                        e_2 = _a.sent();
                        return [2 /*return*/, Promise.resolve({ data: e_2 })];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Sends profile status request to endpoint.
     * @function
     * @param {VoiceProfile} profile - voice profile to check.
     * @public
     * @returns {Promise<IRestResponse>} rest response to status request
     */
    SpeakerIdMessageAdapter.prototype.getProfileStatus = function (profile) {
        var uri = this.getOperationUri(profile.profileType) + "/" + profile.profileId;
        return this.privRestAdapter.request(Exports_1.RestRequestType.Get, uri, this.getQueryParams());
    };
    /**
     * Sends get all profiles request to endpoint.
     * @function
     * @param {VoiceProfileType} profileType - type of profiles to return list of
     * @public
     * @returns {Promise<IRestResponse>} promised rest response containing all profiles
     */
    SpeakerIdMessageAdapter.prototype.getProfiles = function (profileType) {
        var uri = this.getOperationUri(profileType);
        return this.privRestAdapter.request(Exports_1.RestRequestType.Get, uri, this.getQueryParams());
    };
    /**
     * Sends get activation/auth phrases request to endpoint.
     * @function
     * @param {VoiceProfileType} profileType - type of profiles to return phrases for
     * @param {string} lang - language/locale of voice profile
     * @public
     * @returns {Promise<IRestResponse>} promised rest response containing list of valid phrases
     */
    SpeakerIdMessageAdapter.prototype.getPhrases = function (profileType, lang) {
        var uri = ("" + this.getOperationUri(profileType)).replace("profiles", "phrases") + "/" + lang;
        return this.privRestAdapter.request(Exports_1.RestRequestType.Get, uri, this.getQueryParams());
    };
    /**
     * Sends delete profile request to endpoint.
     * @function
     * @param {VoiceProfile} profile - voice profile to delete.
     * @public
     * @returns {Promise<IRestResponse>} rest response to deletion request
     */
    SpeakerIdMessageAdapter.prototype.deleteProfile = function (profile) {
        var uri = this.getOperationUri(profile.profileType) + "/" + profile.profileId;
        return this.privRestAdapter.request(Exports_1.RestRequestType.Delete, uri, this.getQueryParams());
    };
    /**
     * Sends reset profile request to endpoint.
     * @function
     * @param {VoiceProfile} profile - voice profile to reset enrollments for.
     * @public
     * @returns {Promise<IRestResponse>} rest response to reset request
     */
    SpeakerIdMessageAdapter.prototype.resetProfile = function (profile) {
        var uri = this.getOperationUri(profile.profileType) + "/" + profile.profileId + ":reset";
        return this.privRestAdapter.request(Exports_1.RestRequestType.Post, uri, this.getQueryParams());
    };
    SpeakerIdMessageAdapter.prototype.getOperationUri = function (profileType) {
        var mode = profileType === Exports_2.VoiceProfileType.TextIndependentIdentification ? "identification" : "verification";
        var dependency = profileType === Exports_2.VoiceProfileType.TextDependentVerification ? "text-dependent" : "text-independent";
        return this.privUri.replace("{mode}", mode).replace("{dependency}", dependency);
    };
    SpeakerIdMessageAdapter.prototype.getQueryParams = function (params) {
        if (params === void 0) { params = {}; }
        params[Exports_1.RestConfigBase.configParams.apiVersion] = this.privApiVersion;
        return params;
    };
    return SpeakerIdMessageAdapter;
}());
exports.SpeakerIdMessageAdapter = SpeakerIdMessageAdapter;



/***/ }),
/* 233 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileAudioSource = void 0;
var Exports_1 = __webpack_require__(53);
var Exports_2 = __webpack_require__(4);
var AudioStreamFormat_1 = __webpack_require__(72);
var FileAudioSource = /** @class */ (function () {
    function FileAudioSource(file, filename, audioSourceId) {
        var _this = this;
        this.privStreams = {};
        this.privHeaderEnd = 44;
        this.turnOn = function () {
            if (_this.privFilename.lastIndexOf(".wav") !== _this.privFilename.length - 4) {
                var errorMsg = _this.privFilename + " is not supported. Only WAVE files are allowed at the moment.";
                _this.onEvent(new Exports_2.AudioSourceErrorEvent(errorMsg, ""));
                return Promise.reject(errorMsg);
            }
            _this.onEvent(new Exports_2.AudioSourceInitializingEvent(_this.privId)); // no stream id
            _this.onEvent(new Exports_2.AudioSourceReadyEvent(_this.privId));
            return;
        };
        this.id = function () {
            return _this.privId;
        };
        this.attach = function (audioNodeId) { return __awaiter(_this, void 0, void 0, function () {
            var stream;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.onEvent(new Exports_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId));
                        return [4 /*yield*/, this.upload(audioNodeId)];
                    case 1:
                        stream = _a.sent();
                        this.onEvent(new Exports_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId));
                        return [2 /*return*/, Promise.resolve({
                                detach: function () { return __awaiter(_this, void 0, void 0, function () {
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0:
                                                stream.readEnded();
                                                delete this.privStreams[audioNodeId];
                                                this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
                                                return [4 /*yield*/, this.turnOff()];
                                            case 1:
                                                _a.sent();
                                                return [2 /*return*/];
                                        }
                                    });
                                }); },
                                id: function () {
                                    return audioNodeId;
                                },
                                read: function () {
                                    return stream.read();
                                },
                            })];
                }
            });
        }); };
        this.detach = function (audioNodeId) {
            if (audioNodeId && _this.privStreams[audioNodeId]) {
                _this.privStreams[audioNodeId].close();
                delete _this.privStreams[audioNodeId];
                _this.onEvent(new Exports_2.AudioStreamNodeDetachedEvent(_this.privId, audioNodeId));
            }
        };
        this.turnOff = function () {
            for (var streamId in _this.privStreams) {
                if (streamId) {
                    var stream = _this.privStreams[streamId];
                    if (stream && !stream.isClosed) {
                        stream.close();
                    }
                }
            }
            _this.onEvent(new Exports_2.AudioSourceOffEvent(_this.privId)); // no stream now
            return Promise.resolve();
        };
        this.onEvent = function (event) {
            _this.privEvents.onEvent(event);
            Exports_2.Events.instance.onEvent(event);
        };
        this.privId = audioSourceId ? audioSourceId : Exports_2.createNoDashGuid();
        this.privEvents = new Exports_2.EventSource();
        this.privSource = file;
        if (typeof window !== "undefined" && typeof Blob !== "undefined" && this.privSource instanceof Blob) {
            this.privFilename = file.name;
        }
        else {
            this.privFilename = filename || "unknown.wav";
        }
        // Read the header.
        this.privAudioFormatPromise = this.readHeader();
    }
    Object.defineProperty(FileAudioSource.prototype, "format", {
        get: function () {
            return this.privAudioFormatPromise;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FileAudioSource.prototype, "blob", {
        get: function () {
            return Promise.resolve(this.privSource);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FileAudioSource.prototype, "events", {
        get: function () {
            return this.privEvents;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(FileAudioSource.prototype, "deviceInfo", {
        get: function () {
            return this.privAudioFormatPromise.then(function (result) {
                return Promise.resolve({
                    bitspersample: result.bitsPerSample,
                    channelcount: result.channels,
                    connectivity: Exports_1.connectivity.Unknown,
                    manufacturer: "Speech SDK",
                    model: "File",
                    samplerate: result.samplesPerSec,
                    type: Exports_1.type.File,
                });
            });
        },
        enumerable: false,
        configurable: true
    });
    FileAudioSource.prototype.readHeader = function () {
        var _this = this;
        // Read the wave header.
        var maxHeaderSize = 512;
        var header = this.privSource.slice(0, maxHeaderSize);
        var headerResult = new Exports_2.Deferred();
        var processHeader = function (header) {
            var view = new DataView(header);
            var getWord = function (index) {
                return String.fromCharCode(view.getUint8(index), view.getUint8(index + 1), view.getUint8(index + 2), view.getUint8(index + 3));
            };
            // RIFF 4 bytes.
            if ("RIFF" !== getWord(0)) {
                headerResult.reject("Invalid WAV header in file, RIFF was not found");
                return;
            }
            // length, 4 bytes
            // RIFF Type & fmt 8 bytes
            if ("WAVE" !== getWord(8) || "fmt " !== getWord(12)) {
                headerResult.reject("Invalid WAV header in file, WAVEfmt was not found");
                return;
            }
            var formatSize = view.getInt32(16, true);
            var channelCount = view.getUint16(22, true);
            var sampleRate = view.getUint32(24, true);
            var bitsPerSample = view.getUint16(34, true);
            // Confirm if header is 44 bytes long.
            var pos = 36 + Math.max(formatSize - 16, 0);
            for (; getWord(pos) !== "data"; pos += 2) {
                if (pos > maxHeaderSize - 8) {
                    headerResult.reject("Invalid WAV header in file, data block was not found");
                    return;
                }
            }
            _this.privHeaderEnd = pos + 8;
            headerResult.resolve(AudioStreamFormat_1.AudioStreamFormat.getWaveFormatPCM(sampleRate, bitsPerSample, channelCount));
        };
        if (typeof window !== "undefined" && typeof Blob !== "undefined" && header instanceof Blob) {
            var reader = new FileReader();
            reader.onload = function (event) {
                var header = event.target.result;
                processHeader(header);
            };
            reader.readAsArrayBuffer(header);
        }
        else {
            var h = header;
            processHeader(h.buffer.slice(h.byteOffset, h.byteOffset + h.byteLength));
        }
        return headerResult.promise;
    };
    FileAudioSource.prototype.upload = function (audioNodeId) {
        return __awaiter(this, void 0, void 0, function () {
            var onerror, format, stream_1, chunk, processFile_1, reader, c, e_1;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        onerror = function (error) {
                            var errorMsg = "Error occurred while processing '" + _this.privFilename + "'. " + error;
                            _this.onEvent(new Exports_2.AudioStreamNodeErrorEvent(_this.privId, audioNodeId, errorMsg));
                            throw new Error(errorMsg);
                        };
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 4, , 5]);
                        return [4 /*yield*/, this.turnOn()];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.privAudioFormatPromise];
                    case 3:
                        format = _a.sent();
                        stream_1 = new Exports_2.ChunkedArrayBufferStream(format.avgBytesPerSec / 10, audioNodeId);
                        this.privStreams[audioNodeId] = stream_1;
                        chunk = this.privSource.slice(this.privHeaderEnd);
                        processFile_1 = function (buff) {
                            if (stream_1.isClosed) {
                                return; // output stream was closed (somebody called TurnOff). We're done here.
                            }
                            stream_1.writeStreamChunk({
                                buffer: buff,
                                isEnd: false,
                                timeReceived: Date.now(),
                            });
                            stream_1.close();
                        };
                        if (typeof window !== "undefined" && typeof Blob !== "undefined" && chunk instanceof Blob) {
                            reader = new FileReader();
                            reader.onerror = function (ev) { onerror(ev.toString()); };
                            reader.onload = function (event) {
                                var fileBuffer = event.target.result;
                                processFile_1(fileBuffer);
                            };
                            reader.readAsArrayBuffer(chunk);
                        }
                        else {
                            c = chunk;
                            processFile_1(c.buffer.slice(c.byteOffset, c.byteOffset + c.byteLength));
                        }
                        return [2 /*return*/, stream_1];
                    case 4:
                        e_1 = _a.sent();
                        onerror(e_1);
                        return [3 /*break*/, 5];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    return FileAudioSource;
}());
exports.FileAudioSource = FileAudioSource;



/***/ }),
/* 234 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.PcmRecorder = void 0;
var Exports_1 = __webpack_require__(4);
var PcmRecorder = /** @class */ (function () {
    function PcmRecorder(stopInputOnRelease) {
        var _this = this;
        this.record = function (context, mediaStream, outputStream) {
            var desiredSampleRate = 16000;
            var waveStreamEncoder = new Exports_1.RiffPcmEncoder(context.sampleRate, desiredSampleRate);
            var needHeader = true;
            var micInput = context.createMediaStreamSource(mediaStream);
            if (!_this.privSpeechProcessorScript) {
                var workletScript = "class SP extends AudioWorkletProcessor {\n                constructor(options) {\n                  super(options);\n                }\n                process(inputs, outputs) {\n                  const input = inputs[0];\n                  const output = [];\n                  for (let channel = 0; channel < input.length; channel += 1) {\n                    output[channel] = input[channel];\n                  }\n                  this.port.postMessage(output[0]);\n                  return true;\n                }\n              }\n              registerProcessor('speech-processor', SP);"; // tslint:disable-line:max-line-length
                var blob = new Blob([workletScript], { type: "application/javascript; charset=utf-8" });
                _this.privSpeechProcessorScript = URL.createObjectURL(blob);
            }
            var attachScriptProcessor = function () {
                var scriptNode = (function () {
                    var bufferSize = 0;
                    try {
                        return context.createScriptProcessor(bufferSize, 1, 1);
                    }
                    catch (error) {
                        // Webkit (<= version 31) requires a valid bufferSize.
                        bufferSize = 2048;
                        var audioSampleRate = context.sampleRate;
                        while (bufferSize < 16384 && audioSampleRate >= (2 * desiredSampleRate)) {
                            bufferSize <<= 1;
                            audioSampleRate >>= 1;
                        }
                        return context.createScriptProcessor(bufferSize, 1, 1);
                    }
                })();
                scriptNode.onaudioprocess = function (event) {
                    var inputFrame = event.inputBuffer.getChannelData(0);
                    if (outputStream && !outputStream.isClosed) {
                        var waveFrame = waveStreamEncoder.encode(inputFrame);
                        if (!!waveFrame) {
                            outputStream.writeStreamChunk({
                                buffer: waveFrame,
                                isEnd: false,
                                timeReceived: Date.now(),
                            });
                            needHeader = false;
                        }
                    }
                };
                micInput.connect(scriptNode);
                scriptNode.connect(context.destination);
                _this.privMediaResources = {
                    scriptProcessorNode: scriptNode,
                    source: micInput,
                    stream: mediaStream,
                };
            };
            // https://webaudio.github.io/web-audio-api/#audioworklet
            // Using AudioWorklet to improve audio quality and avoid audio glitches due to blocking the UI thread
            if (!!_this.privSpeechProcessorScript && !!context.audioWorklet) {
                context.audioWorklet
                    .addModule(_this.privSpeechProcessorScript)
                    .then(function () {
                    var workletNode = new AudioWorkletNode(context, "speech-processor");
                    workletNode.port.onmessage = function (ev) {
                        var inputFrame = ev.data;
                        if (outputStream && !outputStream.isClosed) {
                            var waveFrame = waveStreamEncoder.encode(inputFrame);
                            if (!!waveFrame) {
                                outputStream.writeStreamChunk({
                                    buffer: waveFrame,
                                    isEnd: false,
                                    timeReceived: Date.now(),
                                });
                                needHeader = false;
                            }
                        }
                    };
                    micInput.connect(workletNode);
                    workletNode.connect(context.destination);
                    _this.privMediaResources = {
                        scriptProcessorNode: workletNode,
                        source: micInput,
                        stream: mediaStream,
                    };
                })
                    .catch(function () {
                    attachScriptProcessor();
                });
            }
            else {
                try {
                    attachScriptProcessor();
                }
                catch (err) {
                    throw new Error("Unable to start audio worklet node for PCMRecorder: " + err);
                }
            }
        };
        this.releaseMediaResources = function (context) {
            if (_this.privMediaResources) {
                if (_this.privMediaResources.scriptProcessorNode) {
                    _this.privMediaResources.scriptProcessorNode.disconnect(context.destination);
                    _this.privMediaResources.scriptProcessorNode = null;
                }
                if (_this.privMediaResources.source) {
                    _this.privMediaResources.source.disconnect();
                    if (_this.privStopInputOnRelease) {
                        _this.privMediaResources.stream.getTracks().forEach(function (track) { return track.stop(); });
                    }
                    _this.privMediaResources.source = null;
                }
            }
        };
        this.privStopInputOnRelease = stopInputOnRelease;
    }
    PcmRecorder.prototype.setWorkletUrl = function (url) {
        this.privSpeechProcessorScript = url;
    };
    return PcmRecorder;
}());
exports.PcmRecorder = PcmRecorder;



/***/ }),
/* 235 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebsocketConnection = void 0;
var Exports_1 = __webpack_require__(4);
var WebsocketMessageAdapter_1 = __webpack_require__(236);
var WebsocketConnection = /** @class */ (function () {
    function WebsocketConnection(uri, queryParameters, headers, messageFormatter, proxyInfo, enableCompression, connectionId) {
        var _this = this;
        if (enableCompression === void 0) { enableCompression = false; }
        this.privIsDisposed = false;
        this.isDisposed = function () {
            return _this.privIsDisposed;
        };
        this.state = function () {
            return _this.privConnectionMessageAdapter.state;
        };
        this.open = function () {
            return _this.privConnectionMessageAdapter.open();
        };
        this.send = function (message) {
            return _this.privConnectionMessageAdapter.send(message);
        };
        this.read = function () {
            return _this.privConnectionMessageAdapter.read();
        };
        if (!uri) {
            throw new Exports_1.ArgumentNullError("uri");
        }
        if (!messageFormatter) {
            throw new Exports_1.ArgumentNullError("messageFormatter");
        }
        this.privMessageFormatter = messageFormatter;
        var queryParams = "";
        var i = 0;
        if (queryParameters) {
            for (var paramName in queryParameters) {
                if (paramName) {
                    queryParams += ((i === 0) && (uri.indexOf("?") === -1)) ? "?" : "&";
                    var val = encodeURIComponent(queryParameters[paramName]);
                    queryParams += paramName + "=" + val;
                    i++;
                }
            }
        }
        if (headers) {
            for (var headerName in headers) {
                if (headerName) {
                    queryParams += ((i === 0) && (uri.indexOf("?") === -1)) ? "?" : "&";
                    var val = encodeURIComponent(headers[headerName]);
                    queryParams += headerName + "=" + val;
                    i++;
                }
            }
        }
        this.privUri = uri + queryParams;
        this.privId = connectionId ? connectionId : Exports_1.createNoDashGuid();
        this.privConnectionMessageAdapter = new WebsocketMessageAdapter_1.WebsocketMessageAdapter(this.privUri, this.id, this.privMessageFormatter, proxyInfo, headers, enableCompression);
    }
    WebsocketConnection.prototype.dispose = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.privIsDisposed = true;
                        if (!this.privConnectionMessageAdapter) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.privConnectionMessageAdapter.close()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    Object.defineProperty(WebsocketConnection.prototype, "id", {
        get: function () {
            return this.privId;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(WebsocketConnection.prototype, "events", {
        get: function () {
            return this.privConnectionMessageAdapter.events;
        },
        enumerable: false,
        configurable: true
    });
    return WebsocketConnection;
}());
exports.WebsocketConnection = WebsocketConnection;



/***/ }),
/* 236 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebsocketMessageAdapter = void 0;
var HeaderNames_1 = __webpack_require__(55);
var Exports_1 = __webpack_require__(4);
// Node.JS specific web socket / browser support.
var ws_1 = __importDefault(__webpack_require__(237));
var CertChecks_1 = __webpack_require__(238);
var WebsocketMessageAdapter = /** @class */ (function () {
    function WebsocketMessageAdapter(uri, connectionId, messageFormatter, proxyInfo, headers, enableCompression) {
        var _this = this;
        this.open = function () {
            if (_this.privConnectionState === Exports_1.ConnectionState.Disconnected) {
                return Promise.reject("Cannot open a connection that is in " + _this.privConnectionState + " state");
            }
            if (_this.privConnectionEstablishDeferral) {
                return _this.privConnectionEstablishDeferral.promise;
            }
            _this.privConnectionEstablishDeferral = new Exports_1.Deferred();
            _this.privCertificateValidatedDeferral = new Exports_1.Deferred();
            _this.privConnectionState = Exports_1.ConnectionState.Connecting;
            try {
                if (typeof WebSocket !== "undefined" && !WebsocketMessageAdapter.forceNpmWebSocket) {
                    // Browser handles cert checks.
                    _this.privCertificateValidatedDeferral.resolve();
                    _this.privWebsocketClient = new WebSocket(_this.privUri);
                }
                else {
                    var options = { headers: _this.privHeaders, perMessageDeflate: _this.privEnableCompression };
                    // The ocsp library will handle validation for us and fail the connection if needed.
                    _this.privCertificateValidatedDeferral.resolve();
                    var checkAgent = new CertChecks_1.CertCheckAgent(_this.proxyInfo);
                    options.agent = checkAgent.GetAgent();
                    // Workaround for https://github.com/microsoft/cognitive-services-speech-sdk-js/issues/465
                    // Which is root caused by https://github.com/TooTallNate/node-agent-base/issues/61
                    var uri = new URL(_this.privUri);
                    var protocol = uri.protocol;
                    if ((protocol === null || protocol === void 0 ? void 0 : protocol.toLocaleLowerCase()) === "wss:") {
                        protocol = "https:";
                    }
                    else if ((protocol === null || protocol === void 0 ? void 0 : protocol.toLocaleLowerCase()) === "ws:") {
                        protocol = "http:";
                    }
                    options.agent.protocol = protocol;
                    _this.privWebsocketClient = new ws_1.default(_this.privUri, options);
                }
                _this.privWebsocketClient.binaryType = "arraybuffer";
                _this.privReceivingMessageQueue = new Exports_1.Queue();
                _this.privDisconnectDeferral = new Exports_1.Deferred();
                _this.privSendMessageQueue = new Exports_1.Queue();
                _this.processSendQueue().catch(function (reason) {
                    Exports_1.Events.instance.onEvent(new Exports_1.BackgroundEvent(reason));
                });
            }
            catch (error) {
                _this.privConnectionEstablishDeferral.resolve(new Exports_1.ConnectionOpenResponse(500, error));
                return _this.privConnectionEstablishDeferral.promise;
            }
            _this.onEvent(new Exports_1.ConnectionStartEvent(_this.privConnectionId, _this.privUri));
            _this.privWebsocketClient.onopen = function (e) {
                _this.privCertificateValidatedDeferral.promise.then(function () {
                    _this.privConnectionState = Exports_1.ConnectionState.Connected;
                    _this.onEvent(new Exports_1.ConnectionEstablishedEvent(_this.privConnectionId));
                    _this.privConnectionEstablishDeferral.resolve(new Exports_1.ConnectionOpenResponse(200, ""));
                }, function (error) {
                    _this.privConnectionEstablishDeferral.reject(error);
                });
            };
            _this.privWebsocketClient.onerror = function (e) {
                _this.onEvent(new Exports_1.ConnectionErrorEvent(_this.privConnectionId, e.message, e.type));
                _this.privLastErrorReceived = e.message;
            };
            _this.privWebsocketClient.onclose = function (e) {
                if (_this.privConnectionState === Exports_1.ConnectionState.Connecting) {
                    _this.privConnectionState = Exports_1.ConnectionState.Disconnected;
                    // this.onEvent(new ConnectionEstablishErrorEvent(this.connectionId, e.code, e.reason));
                    _this.privConnectionEstablishDeferral.resolve(new Exports_1.ConnectionOpenResponse(e.code, e.reason + " " + _this.privLastErrorReceived));
                }
                else {
                    _this.privConnectionState = Exports_1.ConnectionState.Disconnected;
                    _this.privWebsocketClient = null;
                    _this.onEvent(new Exports_1.ConnectionClosedEvent(_this.privConnectionId, e.code, e.reason));
                }
                _this.onClose(e.code, e.reason).catch(function (reason) {
                    Exports_1.Events.instance.onEvent(new Exports_1.BackgroundEvent(reason));
                });
            };
            _this.privWebsocketClient.onmessage = function (e) {
                var networkReceivedTime = new Date().toISOString();
                if (_this.privConnectionState === Exports_1.ConnectionState.Connected) {
                    var deferred_1 = new Exports_1.Deferred();
                    // let id = ++this.idCounter;
                    _this.privReceivingMessageQueue.enqueueFromPromise(deferred_1.promise);
                    if (e.data instanceof ArrayBuffer) {
                        var rawMessage = new Exports_1.RawWebsocketMessage(Exports_1.MessageType.Binary, e.data);
                        _this.privMessageFormatter
                            .toConnectionMessage(rawMessage)
                            .then(function (connectionMessage) {
                            _this.onEvent(new Exports_1.ConnectionMessageReceivedEvent(_this.privConnectionId, networkReceivedTime, connectionMessage));
                            deferred_1.resolve(connectionMessage);
                        }, function (error) {
                            // TODO: Events for these ?
                            deferred_1.reject("Invalid binary message format. Error: " + error);
                        });
                    }
                    else {
                        var rawMessage = new Exports_1.RawWebsocketMessage(Exports_1.MessageType.Text, e.data);
                        _this.privMessageFormatter
                            .toConnectionMessage(rawMessage)
                            .then(function (connectionMessage) {
                            _this.onEvent(new Exports_1.ConnectionMessageReceivedEvent(_this.privConnectionId, networkReceivedTime, connectionMessage));
                            deferred_1.resolve(connectionMessage);
                        }, function (error) {
                            // TODO: Events for these ?
                            deferred_1.reject("Invalid text message format. Error: " + error);
                        });
                    }
                }
            };
            return _this.privConnectionEstablishDeferral.promise;
        };
        this.send = function (message) {
            if (_this.privConnectionState !== Exports_1.ConnectionState.Connected) {
                return Promise.reject("Cannot send on connection that is in " + Exports_1.ConnectionState[_this.privConnectionState] + " state");
            }
            var messageSendStatusDeferral = new Exports_1.Deferred();
            var messageSendDeferral = new Exports_1.Deferred();
            _this.privSendMessageQueue.enqueueFromPromise(messageSendDeferral.promise);
            _this.privMessageFormatter
                .fromConnectionMessage(message)
                .then(function (rawMessage) {
                messageSendDeferral.resolve({
                    Message: message,
                    RawWebsocketMessage: rawMessage,
                    sendStatusDeferral: messageSendStatusDeferral,
                });
            }, function (error) {
                messageSendDeferral.reject("Error formatting the message. " + error);
            });
            return messageSendStatusDeferral.promise;
        };
        this.read = function () {
            if (_this.privConnectionState !== Exports_1.ConnectionState.Connected) {
                return Promise.reject("Cannot read on connection that is in " + _this.privConnectionState + " state");
            }
            return _this.privReceivingMessageQueue.dequeue();
        };
        this.close = function (reason) {
            if (_this.privWebsocketClient) {
                if (_this.privConnectionState !== Exports_1.ConnectionState.Disconnected) {
                    _this.privWebsocketClient.close(1000, reason ? reason : "Normal closure by client");
                }
            }
            else {
                return Promise.resolve();
            }
            return _this.privDisconnectDeferral.promise;
        };
        this.sendRawMessage = function (sendItem) {
            try {
                // indicates we are draining the queue and it came with no message;
                if (!sendItem) {
                    return Promise.resolve();
                }
                _this.onEvent(new Exports_1.ConnectionMessageSentEvent(_this.privConnectionId, new Date().toISOString(), sendItem.Message));
                // add a check for the ws readystate in order to stop the red console error 'WebSocket is already in CLOSING or CLOSED state' appearing
                if (_this.isWebsocketOpen) {
                    _this.privWebsocketClient.send(sendItem.RawWebsocketMessage.payload);
                }
                else {
                    return Promise.reject("websocket send error: Websocket not ready " + _this.privConnectionId + " " + sendItem.Message.id + " " + new Error().stack);
                }
                return Promise.resolve();
            }
            catch (e) {
                return Promise.reject("websocket send error: " + e);
            }
        };
        this.onEvent = function (event) {
            _this.privConnectionEvents.onEvent(event);
            Exports_1.Events.instance.onEvent(event);
        };
        if (!uri) {
            throw new Exports_1.ArgumentNullError("uri");
        }
        if (!messageFormatter) {
            throw new Exports_1.ArgumentNullError("messageFormatter");
        }
        this.proxyInfo = proxyInfo;
        this.privConnectionEvents = new Exports_1.EventSource();
        this.privConnectionId = connectionId;
        this.privMessageFormatter = messageFormatter;
        this.privConnectionState = Exports_1.ConnectionState.None;
        this.privUri = uri;
        this.privHeaders = headers;
        this.privEnableCompression = enableCompression;
        // Add the connection ID to the headers
        this.privHeaders[HeaderNames_1.HeaderNames.ConnectionId] = this.privConnectionId;
        this.privLastErrorReceived = "";
    }
    Object.defineProperty(WebsocketMessageAdapter.prototype, "state", {
        get: function () {
            return this.privConnectionState;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(WebsocketMessageAdapter.prototype, "events", {
        get: function () {
            return this.privConnectionEvents;
        },
        enumerable: false,
        configurable: true
    });
    WebsocketMessageAdapter.prototype.onClose = function (code, reason) {
        return __awaiter(this, void 0, void 0, function () {
            var closeReason;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        closeReason = "Connection closed. " + code + ": " + reason;
                        this.privConnectionState = Exports_1.ConnectionState.Disconnected;
                        this.privDisconnectDeferral.resolve();
                        return [4 /*yield*/, this.privReceivingMessageQueue.drainAndDispose(function (pendingReceiveItem) {
                                // TODO: Events for these ?
                                // Logger.instance.onEvent(new LoggingEvent(LogType.Warning, null, `Failed to process received message. Reason: ${closeReason}, Message: ${JSON.stringify(pendingReceiveItem)}`));
                            }, closeReason)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, this.privSendMessageQueue.drainAndDispose(function (pendingSendItem) {
                                pendingSendItem.sendStatusDeferral.reject(closeReason);
                            }, closeReason)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    WebsocketMessageAdapter.prototype.processSendQueue = function () {
        return __awaiter(this, void 0, void 0, function () {
            var itemToSend, sendItem, sendError_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (false) {}
                        itemToSend = this.privSendMessageQueue.dequeue();
                        return [4 /*yield*/, itemToSend];
                    case 1:
                        sendItem = _a.sent();
                        // indicates we are draining the queue and it came with no message;
                        if (!sendItem) {
                            return [2 /*return*/];
                        }
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 4, , 5]);
                        return [4 /*yield*/, this.sendRawMessage(sendItem)];
                    case 3:
                        _a.sent();
                        sendItem.sendStatusDeferral.resolve();
                        return [3 /*break*/, 5];
                    case 4:
                        sendError_1 = _a.sent();
                        sendItem.sendStatusDeferral.reject(sendError_1);
                        return [3 /*break*/, 5];
                    case 5: return [3 /*break*/, 0];
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    Object.defineProperty(WebsocketMessageAdapter.prototype, "isWebsocketOpen", {
        get: function () {
            return this.privWebsocketClient && this.privWebsocketClient.readyState === this.privWebsocketClient.OPEN;
        },
        enumerable: false,
        configurable: true
    });
    WebsocketMessageAdapter.forceNpmWebSocket = false;
    return WebsocketMessageAdapter;
}());
exports.WebsocketMessageAdapter = WebsocketMessageAdapter;



/***/ }),
/* 237 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(process, Buffer) {
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CertCheckAgent = void 0;
var tls = __importStar(__webpack_require__(240));
var parse = __importStar(__webpack_require__(241));
var ocsp = __importStar(__webpack_require__(244));
var Exports_1 = __webpack_require__(4);
var agent_base_1 = __importDefault(__webpack_require__(245));
// @ts-ignore
var async_disk_cache_1 = __importDefault(__webpack_require__(246));
var https_proxy_agent_1 = __importDefault(__webpack_require__(247));
var net = __importStar(__webpack_require__(248));
var OCSPEvents_1 = __webpack_require__(49);
var CertCheckAgent = /** @class */ (function () {
    function CertCheckAgent(proxyInfo) {
        if (!!proxyInfo) {
            this.privProxyInfo = proxyInfo;
        }
        // Initialize this here to allow tests to set the env variable before the cache is constructed.
        if (!CertCheckAgent.privDiskCache) {
            CertCheckAgent.privDiskCache = new async_disk_cache_1.default("microsoft-cognitiveservices-speech-sdk-cache", { supportBuffer: true, location: (typeof process !== "undefined" && !!process.env.SPEECH_OCSP_CACHE_ROOT) ? process.env.SPEECH_OCSP_CACHE_ROOT : undefined });
        }
    }
    // Test hook to force the disk cache to be recreated.
    CertCheckAgent.forceReinitDiskCache = function () {
        CertCheckAgent.privDiskCache = undefined;
        CertCheckAgent.privMemCache = {};
    };
    CertCheckAgent.prototype.GetAgent = function (disableStapling) {
        var agent = new agent_base_1.default.Agent(this.CreateConnection);
        if (this.privProxyInfo !== undefined &&
            this.privProxyInfo.HostName !== undefined &&
            this.privProxyInfo.Port > 0) {
            var proxyName = "privProxyInfo";
            agent[proxyName] = this.privProxyInfo;
        }
        return agent;
    };
    CertCheckAgent.GetProxyAgent = function (proxyInfo) {
        var httpProxyOptions = {
            host: proxyInfo.HostName,
            port: proxyInfo.Port,
        };
        if (!!proxyInfo.UserName) {
            httpProxyOptions.headers = {
                "Proxy-Authentication": "Basic " + new Buffer(proxyInfo.UserName + ":" + (proxyInfo.Password === undefined) ? "" : proxyInfo.Password).toString("base64"),
            };
        }
        else {
            httpProxyOptions.headers = {};
        }
        httpProxyOptions.headers.requestOCSP = "true";
        var httpProxyAgent = new https_proxy_agent_1.default(httpProxyOptions);
        return httpProxyAgent;
    };
    CertCheckAgent.OCSPCheck = function (socketPromise, proxyInfo) {
        return __awaiter(this, void 0, void 0, function () {
            var ocspRequest, stapling, resolved, socket, tlsSocket;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        resolved = false;
                        return [4 /*yield*/, socketPromise];
                    case 1:
                        socket = _a.sent();
                        socket.cork();
                        tlsSocket = socket;
                        return [2 /*return*/, new Promise(function (resolve, reject) {
                                socket.on("OCSPResponse", function (data) {
                                    if (!!data) {
                                        _this.onEvent(new Exports_1.OCSPStapleReceivedEvent());
                                        stapling = data;
                                    }
                                });
                                socket.on("error", function (error) {
                                    if (!resolved) {
                                        resolved = true;
                                        socket.destroy();
                                        reject(error);
                                    }
                                });
                                tlsSocket.on("secure", function () { return __awaiter(_this, void 0, void 0, function () {
                                    var peer, issuer, sig, cacheEntry, e_1;
                                    return __generator(this, function (_a) {
                                        switch (_a.label) {
                                            case 0:
                                                peer = tlsSocket.getPeerCertificate(true);
                                                _a.label = 1;
                                            case 1:
                                                _a.trys.push([1, 6, , 7]);
                                                return [4 /*yield*/, this.GetIssuer(peer)];
                                            case 2:
                                                issuer = _a.sent();
                                                // We always need a request to verify the response.
                                                ocspRequest = ocsp.request.generate(peer.raw, issuer.raw);
                                                sig = ocspRequest.id.toString("hex");
                                                if (!!stapling) return [3 /*break*/, 4];
                                                return [4 /*yield*/, CertCheckAgent.GetResponseFromCache(sig, ocspRequest, proxyInfo)];
                                            case 3:
                                                cacheEntry = _a.sent();
                                                stapling = cacheEntry;
                                                _a.label = 4;
                                            case 4: return [4 /*yield*/, this.VerifyOCSPResponse(stapling, ocspRequest, proxyInfo)];
                                            case 5:
                                                _a.sent();
                                                socket.uncork();
                                                resolved = true;
                                                resolve(socket);
                                                return [3 /*break*/, 7];
                                            case 6:
                                                e_1 = _a.sent();
                                                socket.destroy();
                                                resolved = true;
                                                reject(e_1);
                                                return [3 /*break*/, 7];
                                            case 7: return [2 /*return*/];
                                        }
                                    });
                                }); });
                            })];
                }
            });
        });
    };
    CertCheckAgent.GetIssuer = function (peer) {
        if (peer.issuerCertificate) {
            return Promise.resolve(peer.issuerCertificate);
        }
        return new Promise(function (resolve, reject) {
            var ocspAgent = new ocsp.Agent({});
            ocspAgent.fetchIssuer(peer, null, function (error, value) {
                if (!!error) {
                    reject(error);
                    return;
                }
                resolve(value);
            });
        });
    };
    CertCheckAgent.GetResponseFromCache = function (signature, ocspRequest, proxyInfo) {
        return __awaiter(this, void 0, void 0, function () {
            var cachedResponse, diskCacheResponse, error_1, cachedOcspResponse, tbsData, cachedStartTime, cachedNextTime, minUpdate;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        cachedResponse = CertCheckAgent.privMemCache[signature];
                        if (!!cachedResponse) {
                            this.onEvent(new Exports_1.OCSPMemoryCacheHitEvent(signature));
                        }
                        if (!!cachedResponse) return [3 /*break*/, 4];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, CertCheckAgent.privDiskCache.get(signature)];
                    case 2:
                        diskCacheResponse = _a.sent();
                        if (!!diskCacheResponse.isCached) {
                            CertCheckAgent.onEvent(new Exports_1.OCSPDiskCacheHitEvent(signature));
                            CertCheckAgent.StoreMemoryCacheEntry(signature, diskCacheResponse.value);
                            cachedResponse = diskCacheResponse.value;
                        }
                        return [3 /*break*/, 4];
                    case 3:
                        error_1 = _a.sent();
                        cachedResponse = null;
                        return [3 /*break*/, 4];
                    case 4:
                        if (!cachedResponse) {
                            return [2 /*return*/, cachedResponse];
                        }
                        try {
                            cachedOcspResponse = ocsp.utils.parseResponse(cachedResponse);
                            tbsData = cachedOcspResponse.value.tbsResponseData;
                            if (tbsData.responses.length < 1) {
                                this.onEvent(new Exports_1.OCSPCacheFetchErrorEvent(signature, "Not enough data in cached response"));
                                return [2 /*return*/];
                            }
                            cachedStartTime = tbsData.responses[0].thisUpdate;
                            cachedNextTime = tbsData.responses[0].nextUpdate;
                            if (cachedNextTime < (Date.now() + this.testTimeOffset - 60000)) {
                                // Cached entry has expired.
                                this.onEvent(new Exports_1.OCSPCacheEntryExpiredEvent(signature, cachedNextTime));
                                cachedResponse = null;
                            }
                            else {
                                minUpdate = Math.min(24 * 60 * 60 * 1000, (cachedNextTime - cachedStartTime) / 2);
                                if ((cachedNextTime - (Date.now() + this.testTimeOffset)) < minUpdate) {
                                    this.onEvent(new Exports_1.OCSPCacheEntryNeedsRefreshEvent(signature, cachedStartTime, cachedNextTime));
                                    this.UpdateCache(ocspRequest, proxyInfo).catch(function (error) {
                                        // Well, not much we can do here.
                                        _this.onEvent(new OCSPEvents_1.OCSPCacheUpdateErrorEvent(signature, error.toString()));
                                    });
                                }
                                else {
                                    this.onEvent(new Exports_1.OCSPCacheHitEvent(signature, cachedStartTime, cachedNextTime));
                                }
                            }
                        }
                        catch (error) {
                            this.onEvent(new Exports_1.OCSPCacheFetchErrorEvent(signature, error));
                            cachedResponse = null;
                        }
                        if (!cachedResponse) {
                            this.onEvent(new Exports_1.OCSPCacheMissEvent(signature));
                        }
                        return [2 /*return*/, cachedResponse];
                }
            });
        });
    };
    CertCheckAgent.VerifyOCSPResponse = function (cacheValue, ocspRequest, proxyInfo) {
        return __awaiter(this, void 0, void 0, function () {
            var ocspResponse, sig;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        ocspResponse = cacheValue;
                        sig = ocspRequest.certID.toString("hex");
                        if (!!ocspResponse) return [3 /*break*/, 2];
                        return [4 /*yield*/, CertCheckAgent.GetOCSPResponse(ocspRequest, proxyInfo)];
                    case 1:
                        ocspResponse = _a.sent();
                        _a.label = 2;
                    case 2: return [2 /*return*/, new Promise(function (resolve, reject) {
                            ocsp.verify({ request: ocspRequest, response: ocspResponse }, function (error, result) {
                                if (!!error) {
                                    CertCheckAgent.onEvent(new Exports_1.OCSPVerificationFailedEvent(ocspRequest.id.toString("hex"), error));
                                    // Bad Cached Value? One more try without the cache.
                                    if (!!cacheValue) {
                                        _this.VerifyOCSPResponse(null, ocspRequest, proxyInfo).then(function () {
                                            resolve();
                                        }, function (error) {
                                            reject(error);
                                        });
                                    }
                                    else {
                                        reject(error);
                                    }
                                }
                                else {
                                    if (!cacheValue) {
                                        CertCheckAgent.StoreCacheEntry(ocspRequest.id.toString("hex"), ocspResponse);
                                    }
                                    resolve();
                                }
                            });
                        })];
                }
            });
        });
    };
    CertCheckAgent.UpdateCache = function (req, proxyInfo) {
        return __awaiter(this, void 0, void 0, function () {
            var signature, rawResponse;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        signature = req.id.toString("hex");
                        this.onEvent(new Exports_1.OCSPCacheUpdateNeededEvent(signature));
                        return [4 /*yield*/, this.GetOCSPResponse(req, proxyInfo)];
                    case 1:
                        rawResponse = _a.sent();
                        this.StoreCacheEntry(signature, rawResponse);
                        this.onEvent(new Exports_1.OCSPCacheUpdateCompleteEvent(req.id.toString("hex")));
                        return [2 /*return*/];
                }
            });
        });
    };
    CertCheckAgent.StoreCacheEntry = function (sig, rawResponse) {
        this.StoreMemoryCacheEntry(sig, rawResponse);
        this.StoreDiskCacheEntry(sig, rawResponse);
    };
    CertCheckAgent.StoreMemoryCacheEntry = function (sig, rawResponse) {
        this.privMemCache[sig] = rawResponse;
        this.onEvent(new Exports_1.OCSPMemoryCacheStoreEvent(sig));
    };
    CertCheckAgent.StoreDiskCacheEntry = function (sig, rawResponse) {
        var _this = this;
        this.privDiskCache.set(sig, rawResponse).then(function () {
            _this.onEvent(new Exports_1.OCSPDiskCacheStoreEvent(sig));
        });
    };
    CertCheckAgent.GetOCSPResponse = function (req, proxyInfo) {
        var _this = this;
        var ocspMethod = "1.3.6.1.5.5.7.48.1";
        var options = {};
        if (!!proxyInfo) {
            var agent = CertCheckAgent.GetProxyAgent(proxyInfo);
            options.agent = agent;
        }
        return new Promise(function (resolve, reject) {
            ocsp.utils.getAuthorityInfo(req.cert, ocspMethod, function (error, uri) {
                if (error) {
                    reject(error);
                    return;
                }
                var parsedUri = parse.default(uri);
                parsedUri.path = parsedUri.pathname;
                options = __assign(__assign({}, options), parsedUri);
                ocsp.utils.getResponse(options, req.data, function (error, raw) {
                    if (error) {
                        reject(error);
                        return;
                    }
                    _this.onEvent(new Exports_1.OCSPResponseRetrievedEvent(req.certID.toString("hex")));
                    resolve(raw);
                });
            });
        });
    };
    CertCheckAgent.prototype.CreateConnection = function (request, options) {
        var enableOCSP = (typeof process !== "undefined" && process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0" && process.env.SPEECH_CONDUCT_OCSP_CHECK !== "0") && options.secureEndpoint;
        var socketPromise;
        options = __assign(__assign({}, options), {
            requestOCSP: !CertCheckAgent.forceDisableOCSPStapling,
            servername: options.host
        });
        if (!!this.privProxyInfo) {
            var httpProxyAgent = CertCheckAgent.GetProxyAgent(this.privProxyInfo);
            var baseAgent_1 = httpProxyAgent;
            socketPromise = new Promise(function (resolve, reject) {
                baseAgent_1.callback(request, options, function (error, socket) {
                    if (!!error) {
                        reject(error);
                    }
                    else {
                        resolve(socket);
                    }
                });
            });
        }
        else {
            if (!!options.secureEndpoint) {
                socketPromise = Promise.resolve(tls.connect(options));
            }
            else {
                socketPromise = Promise.resolve(net.connect(options));
            }
        }
        if (!!enableOCSP) {
            return CertCheckAgent.OCSPCheck(socketPromise, this.privProxyInfo);
        }
        else {
            return socketPromise;
        }
    };
    // Test hook to enable forcing expiration / refresh to happen.
    CertCheckAgent.testTimeOffset = 0;
    // Test hook to disable stapling for cache testing.
    CertCheckAgent.forceDisableOCSPStapling = false;
    // An in memory cache for recived responses.
    CertCheckAgent.privMemCache = {};
    CertCheckAgent.onEvent = function (event) {
        Exports_1.Events.instance.onEvent(event);
    };
    return CertCheckAgent;
}());
exports.CertCheckAgent = CertCheckAgent;


/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(239), __webpack_require__(67).Buffer))

/***/ }),
/* 239 */
/***/ (function(module, exports) {

// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };


/***/ }),
/* 240 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 241 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {

var required = __webpack_require__(242)
  , qs = __webpack_require__(243)
  , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//
  , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i
  , windowsDriveLetter = /^[a-zA-Z]:/
  , whitespace = '[\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF]'
  , left = new RegExp('^'+ whitespace +'+');

/**
 * Trim a given string.
 *
 * @param {String} str String to trim.
 * @public
 */
function trimLeft(str) {
  return (str ? str : '').toString().replace(left, '');
}

/**
 * These are the parse rules for the URL parser, it informs the parser
 * about:
 *
 * 0. The char it Needs to parse, if it's a string it should be done using
 *    indexOf, RegExp using exec and NaN means set as current value.
 * 1. The property we should set when parsing this value.
 * 2. Indication if it's backwards or forward parsing, when set as number it's
 *    the value of extra chars that should be split off.
 * 3. Inherit from location if non existing in the parser.
 * 4. `toLowerCase` the resulting value.
 */
var rules = [
  ['#', 'hash'],                        // Extract from the back.
  ['?', 'query'],                       // Extract from the back.
  function sanitize(address, url) {     // Sanitize what is left of the address
    return isSpecial(url.protocol) ? address.replace(/\\/g, '/') : address;
  },
  ['/', 'pathname'],                    // Extract from the back.
  ['@', 'auth', 1],                     // Extract from the front.
  [NaN, 'host', undefined, 1, 1],       // Set left over value.
  [/:(\d+)$/, 'port', undefined, 1],    // RegExp the back.
  [NaN, 'hostname', undefined, 1, 1]    // Set left over.
];

/**
 * These properties should not be copied or inherited from. This is only needed
 * for all non blob URL's as a blob URL does not include a hash, only the
 * origin.
 *
 * @type {Object}
 * @private
 */
var ignore = { hash: 1, query: 1 };

/**
 * The location object differs when your code is loaded through a normal page,
 * Worker or through a worker using a blob. And with the blobble begins the
 * trouble as the location object will contain the URL of the blob, not the
 * location of the page where our code is loaded in. The actual origin is
 * encoded in the `pathname` so we can thankfully generate a good "default"
 * location from it so we can generate proper relative URL's again.
 *
 * @param {Object|String} loc Optional default location object.
 * @returns {Object} lolcation object.
 * @public
 */
function lolcation(loc) {
  var globalVar;

  if (typeof window !== 'undefined') globalVar = window;
  else if (typeof global !== 'undefined') globalVar = global;
  else if (typeof self !== 'undefined') globalVar = self;
  else globalVar = {};

  var location = globalVar.location || {};
  loc = loc || location;

  var finaldestination = {}
    , type = typeof loc
    , key;

  if ('blob:' === loc.protocol) {
    finaldestination = new Url(unescape(loc.pathname), {});
  } else if ('string' === type) {
    finaldestination = new Url(loc, {});
    for (key in ignore) delete finaldestination[key];
  } else if ('object' === type) {
    for (key in loc) {
      if (key in ignore) continue;
      finaldestination[key] = loc[key];
    }

    if (finaldestination.slashes === undefined) {
      finaldestination.slashes = slashes.test(loc.href);
    }
  }

  return finaldestination;
}

/**
 * Check whether a protocol scheme is special.
 *
 * @param {String} The protocol scheme of the URL
 * @return {Boolean} `true` if the protocol scheme is special, else `false`
 * @private
 */
function isSpecial(scheme) {
  return (
    scheme === 'file:' ||
    scheme === 'ftp:' ||
    scheme === 'http:' ||
    scheme === 'https:' ||
    scheme === 'ws:' ||
    scheme === 'wss:'
  );
}

/**
 * @typedef ProtocolExtract
 * @type Object
 * @property {String} protocol Protocol matched in the URL, in lowercase.
 * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
 * @property {String} rest Rest of the URL that is not part of the protocol.
 */

/**
 * Extract protocol information from a URL with/without double slash ("//").
 *
 * @param {String} address URL we want to extract from.
 * @param {Object} location
 * @return {ProtocolExtract} Extracted information.
 * @private
 */
function extractProtocol(address, location) {
  address = trimLeft(address);
  location = location || {};

  var match = protocolre.exec(address);
  var protocol = match[1] ? match[1].toLowerCase() : '';
  var forwardSlashes = !!match[2];
  var otherSlashes = !!match[3];
  var slashesCount = 0;
  var rest;

  if (forwardSlashes) {
    if (otherSlashes) {
      rest = match[2] + match[3] + match[4];
      slashesCount = match[2].length + match[3].length;
    } else {
      rest = match[2] + match[4];
      slashesCount = match[2].length;
    }
  } else {
    if (otherSlashes) {
      rest = match[3] + match[4];
      slashesCount = match[3].length;
    } else {
      rest = match[4]
    }
  }

  if (protocol === 'file:') {
    if (slashesCount >= 2) {
      rest = rest.slice(2);
    }
  } else if (isSpecial(protocol)) {
    rest = match[4];
  } else if (protocol) {
    if (forwardSlashes) {
      rest = rest.slice(2);
    }
  } else if (slashesCount >= 2 && isSpecial(location.protocol)) {
    rest = match[4];
  }

  return {
    protocol: protocol,
    slashes: forwardSlashes || isSpecial(protocol),
    slashesCount: slashesCount,
    rest: rest
  };
}

/**
 * Resolve a relative URL pathname against a base URL pathname.
 *
 * @param {String} relative Pathname of the relative URL.
 * @param {String} base Pathname of the base URL.
 * @return {String} Resolved pathname.
 * @private
 */
function resolve(relative, base) {
  if (relative === '') return base;

  var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
    , i = path.length
    , last = path[i - 1]
    , unshift = false
    , up = 0;

  while (i--) {
    if (path[i] === '.') {
      path.splice(i, 1);
    } else if (path[i] === '..') {
      path.splice(i, 1);
      up++;
    } else if (up) {
      if (i === 0) unshift = true;
      path.splice(i, 1);
      up--;
    }
  }

  if (unshift) path.unshift('');
  if (last === '.' || last === '..') path.push('');

  return path.join('/');
}

/**
 * The actual URL instance. Instead of returning an object we've opted-in to
 * create an actual constructor as it's much more memory efficient and
 * faster and it pleases my OCD.
 *
 * It is worth noting that we should not use `URL` as class name to prevent
 * clashes with the global URL instance that got introduced in browsers.
 *
 * @constructor
 * @param {String} address URL we want to parse.
 * @param {Object|String} [location] Location defaults for relative paths.
 * @param {Boolean|Function} [parser] Parser for the query string.
 * @private
 */
function Url(address, location, parser) {
  address = trimLeft(address);

  if (!(this instanceof Url)) {
    return new Url(address, location, parser);
  }

  var relative, extracted, parse, instruction, index, key
    , instructions = rules.slice()
    , type = typeof location
    , url = this
    , i = 0;

  //
  // The following if statements allows this module two have compatibility with
  // 2 different API:
  //
  // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  //    where the boolean indicates that the query string should also be parsed.
  //
  // 2. The `URL` interface of the browser which accepts a URL, object as
  //    arguments. The supplied object will be used as default values / fall-back
  //    for relative paths.
  //
  if ('object' !== type && 'string' !== type) {
    parser = location;
    location = null;
  }

  if (parser && 'function' !== typeof parser) parser = qs.parse;

  location = lolcation(location);

  //
  // Extract protocol information before running the instructions.
  //
  extracted = extractProtocol(address || '', location);
  relative = !extracted.protocol && !extracted.slashes;
  url.slashes = extracted.slashes || relative && location.slashes;
  url.protocol = extracted.protocol || location.protocol || '';
  address = extracted.rest;

  //
  // When the authority component is absent the URL starts with a path
  // component.
  //
  if (
    extracted.protocol === 'file:' && (
      extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||
    (!extracted.slashes &&
      (extracted.protocol ||
        extracted.slashesCount < 2 ||
        !isSpecial(url.protocol)))
  ) {
    instructions[3] = [/(.*)/, 'pathname'];
  }

  for (; i < instructions.length; i++) {
    instruction = instructions[i];

    if (typeof instruction === 'function') {
      address = instruction(address, url);
      continue;
    }

    parse = instruction[0];
    key = instruction[1];

    if (parse !== parse) {
      url[key] = address;
    } else if ('string' === typeof parse) {
      if (~(index = address.indexOf(parse))) {
        if ('number' === typeof instruction[2]) {
          url[key] = address.slice(0, index);
          address = address.slice(index + instruction[2]);
        } else {
          url[key] = address.slice(index);
          address = address.slice(0, index);
        }
      }
    } else if ((index = parse.exec(address))) {
      url[key] = index[1];
      address = address.slice(0, index.index);
    }

    url[key] = url[key] || (
      relative && instruction[3] ? location[key] || '' : ''
    );

    //
    // Hostname, host and protocol should be lowercased so they can be used to
    // create a proper `origin`.
    //
    if (instruction[4]) url[key] = url[key].toLowerCase();
  }

  //
  // Also parse the supplied query string in to an object. If we're supplied
  // with a custom parser as function use that instead of the default build-in
  // parser.
  //
  if (parser) url.query = parser(url.query);

  //
  // If the URL is relative, resolve the pathname against the base URL.
  //
  if (
      relative
    && location.slashes
    && url.pathname.charAt(0) !== '/'
    && (url.pathname !== '' || location.pathname !== '')
  ) {
    url.pathname = resolve(url.pathname, location.pathname);
  }

  //
  // Default to a / for pathname if none exists. This normalizes the URL
  // to always have a /
  //
  if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {
    url.pathname = '/' + url.pathname;
  }

  //
  // We should not add port numbers if they are already the default port number
  // for a given protocol. As the host also contains the port number we're going
  // override it with the hostname which contains no port number.
  //
  if (!required(url.port, url.protocol)) {
    url.host = url.hostname;
    url.port = '';
  }

  //
  // Parse down the `auth` for the username and password.
  //
  url.username = url.password = '';
  if (url.auth) {
    instruction = url.auth.split(':');
    url.username = instruction[0] || '';
    url.password = instruction[1] || '';
  }

  url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
    ? url.protocol +'//'+ url.host
    : 'null';

  //
  // The href is just the compiled result.
  //
  url.href = url.toString();
}

/**
 * This is convenience method for changing properties in the URL instance to
 * insure that they all propagate correctly.
 *
 * @param {String} part          Property we need to adjust.
 * @param {Mixed} value          The newly assigned value.
 * @param {Boolean|Function} fn  When setting the query, it will be the function
 *                               used to parse the query.
 *                               When setting the protocol, double slash will be
 *                               removed from the final url if it is true.
 * @returns {URL} URL instance for chaining.
 * @public
 */
function set(part, value, fn) {
  var url = this;

  switch (part) {
    case 'query':
      if ('string' === typeof value && value.length) {
        value = (fn || qs.parse)(value);
      }

      url[part] = value;
      break;

    case 'port':
      url[part] = value;

      if (!required(value, url.protocol)) {
        url.host = url.hostname;
        url[part] = '';
      } else if (value) {
        url.host = url.hostname +':'+ value;
      }

      break;

    case 'hostname':
      url[part] = value;

      if (url.port) value += ':'+ url.port;
      url.host = value;
      break;

    case 'host':
      url[part] = value;

      if (/:\d+$/.test(value)) {
        value = value.split(':');
        url.port = value.pop();
        url.hostname = value.join(':');
      } else {
        url.hostname = value;
        url.port = '';
      }

      break;

    case 'protocol':
      url.protocol = value.toLowerCase();
      url.slashes = !fn;
      break;

    case 'pathname':
    case 'hash':
      if (value) {
        var char = part === 'pathname' ? '/' : '#';
        url[part] = value.charAt(0) !== char ? char + value : value;
      } else {
        url[part] = value;
      }
      break;

    default:
      url[part] = value;
  }

  for (var i = 0; i < rules.length; i++) {
    var ins = rules[i];

    if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  }

  url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
    ? url.protocol +'//'+ url.host
    : 'null';

  url.href = url.toString();

  return url;
}

/**
 * Transform the properties back in to a valid and full URL string.
 *
 * @param {Function} stringify Optional query stringify function.
 * @returns {String} Compiled version of the URL.
 * @public
 */
function toString(stringify) {
  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;

  var query
    , url = this
    , protocol = url.protocol;

  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';

  var result = protocol + (url.slashes || isSpecial(url.protocol) ? '//' : '');

  if (url.username) {
    result += url.username;
    if (url.password) result += ':'+ url.password;
    result += '@';
  }

  result += url.host + url.pathname;

  query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;

  if (url.hash) result += url.hash;

  return result;
}

Url.prototype = { set: set, toString: toString };

//
// Expose the URL parser and some additional properties that might be useful for
// others or testing.
//
Url.extractProtocol = extractProtocol;
Url.location = lolcation;
Url.trimLeft = trimLeft;
Url.qs = qs;

module.exports = Url;

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(68)))

/***/ }),
/* 242 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


/**
 * Check if we're required to add a port number.
 *
 * @see https://url.spec.whatwg.org/#default-port
 * @param {Number|String} port Port number we need to check
 * @param {String} protocol Protocol we need to check against.
 * @returns {Boolean} Is it a default port for the given protocol
 * @api private
 */
module.exports = function required(port, protocol) {
  protocol = protocol.split(':')[0];
  port = +port;

  if (!port) return false;

  switch (protocol) {
    case 'http':
    case 'ws':
    return port !== 80;

    case 'https':
    case 'wss':
    return port !== 443;

    case 'ftp':
    return port !== 21;

    case 'gopher':
    return port !== 70;

    case 'file':
    return false;
  }

  return port !== 0;
};


/***/ }),
/* 243 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var has = Object.prototype.hasOwnProperty
  , undef;

/**
 * Decode a URI encoded string.
 *
 * @param {String} input The URI encoded string.
 * @returns {String|Null} The decoded string.
 * @api private
 */
function decode(input) {
  try {
    return decodeURIComponent(input.replace(/\+/g, ' '));
  } catch (e) {
    return null;
  }
}

/**
 * Attempts to encode a given input.
 *
 * @param {String} input The string that needs to be encoded.
 * @returns {String|Null} The encoded string.
 * @api private
 */
function encode(input) {
  try {
    return encodeURIComponent(input);
  } catch (e) {
    return null;
  }
}

/**
 * Simple query string parser.
 *
 * @param {String} query The query string that needs to be parsed.
 * @returns {Object}
 * @api public
 */
function querystring(query) {
  var parser = /([^=?#&]+)=?([^&]*)/g
    , result = {}
    , part;

  while (part = parser.exec(query)) {
    var key = decode(part[1])
      , value = decode(part[2]);

    //
    // Prevent overriding of existing properties. This ensures that build-in
    // methods like `toString` or __proto__ are not overriden by malicious
    // querystrings.
    //
    // In the case if failed decoding, we want to omit the key/value pairs
    // from the result.
    //
    if (key === null || value === null || key in result) continue;
    result[key] = value;
  }

  return result;
}

/**
 * Transform a query string to an object.
 *
 * @param {Object} obj Object that should be transformed.
 * @param {String} prefix Optional prefix.
 * @returns {String}
 * @api public
 */
function querystringify(obj, prefix) {
  prefix = prefix || '';

  var pairs = []
    , value
    , key;

  //
  // Optionally prefix with a '?' if needed
  //
  if ('string' !== typeof prefix) prefix = '?';

  for (key in obj) {
    if (has.call(obj, key)) {
      value = obj[key];

      //
      // Edge cases where we actually want to encode the value to an empty
      // string instead of the stringified value.
      //
      if (!value && (value === null || value === undef || isNaN(value))) {
        value = '';
      }

      key = encode(key);
      value = encode(value);

      //
      // If we failed to encode the strings, we should bail out as we don't
      // want to add invalid strings to the query.
      //
      if (key === null || value === null) continue;
      pairs.push(key +'='+ value);
    }
  }

  return pairs.length ? prefix + pairs.join('&') : '';
}

//
// Expose the module.
//
exports.stringify = querystringify;
exports.parse = querystring;


/***/ }),
/* 244 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 245 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 246 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 247 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 248 */
/***/ (function(module, exports) {

/* (ignored) */

/***/ }),
/* 249 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReplayableAudioNode = void 0;
var ReplayableAudioNode = /** @class */ (function () {
    function ReplayableAudioNode(audioSource, bytesPerSecond) {
        var _this = this;
        this.privBuffers = [];
        this.privReplayOffset = 0;
        this.privLastShrinkOffset = 0;
        this.privBufferStartOffset = 0;
        this.privBufferSerial = 0;
        this.privBufferedBytes = 0;
        this.privReplay = false;
        this.privLastChunkAcquiredTime = 0;
        this.id = function () {
            return _this.privAudioNode.id();
        };
        this.privAudioNode = audioSource;
        this.privBytesPerSecond = bytesPerSecond;
    }
    // Reads and returns the next chunk of audio buffer.
    // If replay of existing buffers are needed, read() will first seek and replay
    // existing content, and upoin completion it will read new content from the underlying
    // audio node, saving that content into the replayable buffers.
    ReplayableAudioNode.prototype.read = function () {
        var _this = this;
        // if there is a replay request to honor.
        if (!!this.privReplay && this.privBuffers.length !== 0) {
            // Find the start point in the buffers.
            // Offsets are in 100ns increments.
            // So how many bytes do we need to seek to get the right offset?
            var offsetToSeek = this.privReplayOffset - this.privBufferStartOffset;
            var bytesToSeek = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7);
            if (0 !== (bytesToSeek % 2)) {
                bytesToSeek++;
            }
            var i = 0;
            while (i < this.privBuffers.length && bytesToSeek >= this.privBuffers[i].chunk.buffer.byteLength) {
                bytesToSeek -= this.privBuffers[i++].chunk.buffer.byteLength;
            }
            if (i < this.privBuffers.length) {
                var retVal = this.privBuffers[i].chunk.buffer.slice(bytesToSeek);
                this.privReplayOffset += (retVal.byteLength / this.privBytesPerSecond) * 1e+7;
                // If we've reached the end of the buffers, stop replaying.
                if (i === this.privBuffers.length - 1) {
                    this.privReplay = false;
                }
                return Promise.resolve({
                    buffer: retVal,
                    isEnd: false,
                    timeReceived: this.privBuffers[i].chunk.timeReceived,
                });
            }
        }
        return this.privAudioNode.read()
            .then(function (result) {
            if (result && result.buffer) {
                _this.privBuffers.push(new BufferEntry(result, _this.privBufferSerial++, _this.privBufferedBytes));
                _this.privBufferedBytes += result.buffer.byteLength;
            }
            return result;
        });
    };
    ReplayableAudioNode.prototype.detach = function () {
        this.privBuffers = undefined;
        return this.privAudioNode.detach();
    };
    ReplayableAudioNode.prototype.replay = function () {
        if (this.privBuffers && 0 !== this.privBuffers.length) {
            this.privReplay = true;
            this.privReplayOffset = this.privLastShrinkOffset;
        }
    };
    // Shrinks the existing audio buffers to start at the new offset, or at the
    // beginning of the buffer closest to the requested offset.
    // A replay request will start from the last shrink point.
    ReplayableAudioNode.prototype.shrinkBuffers = function (offset) {
        if (this.privBuffers === undefined || this.privBuffers.length === 0) {
            return;
        }
        this.privLastShrinkOffset = offset;
        // Find the start point in the buffers.
        // Offsets are in 100ns increments.
        // So how many bytes do we need to seek to get the right offset?
        var offsetToSeek = offset - this.privBufferStartOffset;
        var bytesToSeek = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7);
        var i = 0;
        while (i < this.privBuffers.length && bytesToSeek >= this.privBuffers[i].chunk.buffer.byteLength) {
            bytesToSeek -= this.privBuffers[i++].chunk.buffer.byteLength;
        }
        this.privBufferStartOffset = Math.round(offset - ((bytesToSeek / this.privBytesPerSecond) * 1e+7));
        this.privBuffers = this.privBuffers.slice(i);
    };
    // Finds the time a buffer of audio was first seen by offset.
    ReplayableAudioNode.prototype.findTimeAtOffset = function (offset) {
        if (offset < this.privBufferStartOffset || this.privBuffers === undefined) {
            return 0;
        }
        for (var _i = 0, _a = this.privBuffers; _i < _a.length; _i++) {
            var value = _a[_i];
            var startOffset = (value.byteOffset / this.privBytesPerSecond) * 1e7;
            var endOffset = startOffset + ((value.chunk.buffer.byteLength / this.privBytesPerSecond) * 1e7);
            if (offset >= startOffset && offset <= endOffset) {
                return value.chunk.timeReceived;
            }
        }
        return 0;
    };
    return ReplayableAudioNode;
}());
exports.ReplayableAudioNode = ReplayableAudioNode;
// Primary use of this class is to help debugging problems with the replay
// code. If the memory cost of alloc / dealloc gets too much, drop it and just use
// the ArrayBuffer directly.
// tslint:disable-next-line:max-classes-per-file
var BufferEntry = /** @class */ (function () {
    function BufferEntry(chunk, serial, byteOffset) {
        this.chunk = chunk;
        this.serial = serial;
        this.byteOffset = byteOffset;
    }
    return BufferEntry;
}());



/***/ }),
/* 250 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyInfo = void 0;
var Exports_1 = __webpack_require__(61);
var ProxyInfo = /** @class */ (function () {
    function ProxyInfo(proxyHostName, proxyPort, proxyUserName, proxyPassword) {
        this.privProxyHostName = proxyHostName;
        this.privProxyPort = proxyPort;
        this.privProxyUserName = proxyUserName;
        this.privProxyPassword = proxyPassword;
    }
    ProxyInfo.fromParameters = function (parameters) {
        return new ProxyInfo(parameters.getProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyHostName), parseInt(parameters.getProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyPort), 10), parameters.getProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyUserName), parameters.getProperty(Exports_1.PropertyId.SpeechServiceConnection_ProxyPassword));
    };
    ProxyInfo.fromRecognizerConfig = function (config) {
        return this.fromParameters(config.parameters);
    };
    Object.defineProperty(ProxyInfo.prototype, "HostName", {
        get: function () {
            return this.privProxyHostName;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ProxyInfo.prototype, "Port", {
        get: function () {
            return this.privProxyPort;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ProxyInfo.prototype, "UserName", {
        get: function () {
            return this.privProxyUserName;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ProxyInfo.prototype, "Password", {
        get: function () {
            return this.privProxyPassword;
        },
        enumerable: false,
        configurable: true
    });
    return ProxyInfo;
}());
exports.ProxyInfo = ProxyInfo;



/***/ }),
/* 251 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RestMessageAdapter = exports.RestRequestType = void 0;
var Exports_1 = __webpack_require__(4);
var bent_1 = __importDefault(__webpack_require__(252));
var RestRequestType;
(function (RestRequestType) {
    RestRequestType["Get"] = "GET";
    RestRequestType["Post"] = "POST";
    RestRequestType["Delete"] = "DELETE";
    RestRequestType["File"] = "file";
})(RestRequestType = exports.RestRequestType || (exports.RestRequestType = {}));
// accept rest operations via request method and return abstracted objects from server response
var RestMessageAdapter = /** @class */ (function () {
    function RestMessageAdapter(configParams) {
        if (!configParams) {
            throw new Exports_1.ArgumentNullError("configParams");
        }
        this.privHeaders = configParams.headers;
        this.privIgnoreCache = configParams.ignoreCache;
    }
    RestMessageAdapter.extractHeaderValue = function (headerKey, headers) {
        var headerValue = "";
        try {
            var arr = headers.trim().split(/[\r\n]+/);
            var headerMap_1 = {};
            arr.forEach(function (line) {
                var parts = line.split(": ");
                var header = parts.shift().toLowerCase();
                var value = parts.join(": ");
                headerMap_1[header] = value;
            });
            headerValue = headerMap_1[headerKey.toLowerCase()];
        }
        catch (e) {
            // ignore the error
        }
        return headerValue;
    };
    Object.defineProperty(RestMessageAdapter.prototype, "options", {
        set: function (configParams) {
            this.privHeaders = configParams.headers;
            this.privIgnoreCache = configParams.ignoreCache;
        },
        enumerable: false,
        configurable: true
    });
    RestMessageAdapter.prototype.setHeaders = function (key, value) {
        this.privHeaders[key] = value;
    };
    RestMessageAdapter.prototype.request = function (method, uri, queryParams, body, binaryBody) {
        var _this = this;
        if (queryParams === void 0) { queryParams = {}; }
        if (body === void 0) { body = null; }
        if (binaryBody === void 0) { binaryBody = null; }
        var responseReceivedDeferral = new Exports_1.Deferred();
        var requestCommand = method === RestRequestType.File ? "POST" : method;
        var handleRestResponse = function (data, j) {
            if (j === void 0) { j = {}; }
            var d = data;
            return {
                data: JSON.stringify(j),
                headers: JSON.stringify(data.headers),
                json: j,
                ok: data.statusCode >= 200 && data.statusCode < 300,
                status: data.statusCode,
                statusText: j.error ? j.error.message : d.statusText ? d.statusText : d.statusMessage
            };
        };
        var blobToArrayBuffer = function (blob) {
            var reader = new FileReader();
            reader.readAsArrayBuffer(blob);
            return new Promise(function (resolve) {
                reader.onloadend = function () {
                    resolve(reader.result);
                };
            });
        };
        var send = function (postData) {
            var sendRequest = bent_1.default(uri, requestCommand, _this.privHeaders, 200, 201, 202, 204, 400, 401, 402, 403, 404);
            var params = _this.queryParams(queryParams) === "" ? "" : "?" + _this.queryParams(queryParams);
            sendRequest(params, postData).then(function (data) { return __awaiter(_this, void 0, void 0, function () {
                var j, _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            if (!(method === RestRequestType.Delete || data.statusCode === 204)) return [3 /*break*/, 1];
                            // No JSON from Delete and reset (204) operations
                            responseReceivedDeferral.resolve(handleRestResponse(data));
                            return [3 /*break*/, 4];
                        case 1:
                            _b.trys.push([1, 3, , 4]);
                            return [4 /*yield*/, data.json()];
                        case 2:
                            j = _b.sent();
                            responseReceivedDeferral.resolve(handleRestResponse(data, j));
                            return [3 /*break*/, 4];
                        case 3:
                            _a = _b.sent();
                            responseReceivedDeferral.resolve(handleRestResponse(data));
                            return [3 /*break*/, 4];
                        case 4: return [2 /*return*/];
                    }
                });
            }); }).catch(function (error) {
                responseReceivedDeferral.reject(error);
            });
        };
        if (this.privIgnoreCache) {
            this.privHeaders["Cache-Control"] = "no-cache";
        }
        if (method === RestRequestType.File && binaryBody) {
            var contentType = "multipart/form-data";
            this.privHeaders["content-type"] = contentType;
            this.privHeaders["Content-Type"] = contentType;
            if (typeof (Blob) !== "undefined" && binaryBody instanceof Blob) {
                blobToArrayBuffer(binaryBody).then(function (res) {
                    send(res);
                }).catch(function (error) {
                    responseReceivedDeferral.reject(error);
                });
            }
            else {
                send(binaryBody);
            }
        }
        else {
            if (method === RestRequestType.Post && body) {
                this.privHeaders["content-type"] = "application/json";
                this.privHeaders["Content-Type"] = "application/json";
            }
            send(body);
        }
        return responseReceivedDeferral.promise;
    };
    RestMessageAdapter.prototype.withQuery = function (url, params) {
        if (params === void 0) { params = {}; }
        var queryString = this.queryParams(params);
        return queryString ? url + (url.indexOf("?") === -1 ? "?" : "&") + queryString : url;
    };
    RestMessageAdapter.prototype.queryParams = function (params) {
        if (params === void 0) { params = {}; }
        return Object.keys(params)
            .map(function (k) { return encodeURIComponent(k) + "=" + encodeURIComponent(params[k]); })
            .join("&");
    };
    return RestMessageAdapter;
}());
exports.RestMessageAdapter = RestMessageAdapter;



/***/ }),
/* 252 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/* global fetch, btoa, Headers */
const core = __webpack_require__(253)

class StatusError extends Error {
  constructor (res, ...params) {
    super(...params)

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, StatusError)
    }

    this.name = 'StatusError'
    this.message = res.statusMessage
    this.statusCode = res.status
    this.res = res
    this.json = res.json.bind(res)
    this.text = res.text.bind(res)
    this.arrayBuffer = res.arrayBuffer.bind(res)
    let buffer
    const get = () => {
      if (!buffer) buffer = this.arrayBuffer()
      return buffer
    }
    Object.defineProperty(this, 'responseBody', { get })
    // match Node.js headers object
    this.headers = {}
    for (const [key, value] of res.headers.entries()) {
      this.headers[key.toLowerCase()] = value
    }
  }
}

const mkrequest = (statusCodes, method, encoding, headers, baseurl) => async (_url, body, _headers = {}) => {
  _url = baseurl + (_url || '')
  let parsed = new URL(_url)

  if (!headers) headers = {}
  if (parsed.username) {
    headers.Authorization = 'Basic ' + btoa(parsed.username + ':' + parsed.password)
    parsed = new URL(parsed.protocol + '//' + parsed.host + parsed.pathname + parsed.search)
  }
  if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
    throw new Error(`Unknown protocol, ${parsed.protocol}`)
  }

  if (body) {
    if (body instanceof ArrayBuffer ||
      ArrayBuffer.isView(body) ||
      typeof body === 'string'
    ) {
      // noop
    } else if (typeof body === 'object') {
      body = JSON.stringify(body)
      headers['Content-Type'] = 'application/json'
    } else {
      throw new Error('Unknown body type.')
    }
  }

  _headers = new Headers({ ...(headers || {}), ..._headers })

  const resp = await fetch(parsed, { method, headers: _headers, body })
  resp.statusCode = resp.status

  if (!statusCodes.has(resp.status)) {
    throw new StatusError(resp)
  }

  if (encoding === 'json') return resp.json()
  else if (encoding === 'buffer') return resp.arrayBuffer()
  else if (encoding === 'string') return resp.text()
  else return resp
}

module.exports = core(mkrequest)


/***/ }),
/* 253 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

const encodings = new Set(['json', 'buffer', 'string'])

module.exports = mkrequest => (...args) => {
  const statusCodes = new Set()
  let method
  let encoding
  let headers
  let baseurl = ''

  args.forEach(arg => {
    if (typeof arg === 'string') {
      if (arg.toUpperCase() === arg) {
        if (method) {
          const msg = `Can't set method to ${arg}, already set to ${method}.`
          throw new Error(msg)
        } else {
          method = arg
        }
      } else if (arg.startsWith('http:') || arg.startsWith('https:')) {
        baseurl = arg
      } else {
        if (encodings.has(arg)) {
          encoding = arg
        } else {
          throw new Error(`Unknown encoding, ${arg}`)
        }
      }
    } else if (typeof arg === 'number') {
      statusCodes.add(arg)
    } else if (typeof arg === 'object') {
      if (Array.isArray(arg) || arg instanceof Set) {
        arg.forEach(code => statusCodes.add(code))
      } else {
        if (headers) {
          throw new Error('Cannot set headers twice.')
        }
        headers = arg
      }
    } else {
      throw new Error(`Unknown type: ${typeof arg}`)
    }
  })

  if (!method) method = 'GET'
  if (statusCodes.size === 0) {
    statusCodes.add(200)
  }

  return mkrequest(statusCodes, method, encoding, headers, baseurl)
}


/***/ })
/******/ ]);
//# sourceMappingURL=microsoft.cognitiveservices.speech.sdk.bundle.js.map