web-speech-cognitive-services
Version:
Polyfill Web Speech API with Cognitive Services Speech-to-Text service
27,231 lines • 1.26 MB
JavaScript
"use strict";
(() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// ../../node_modules/uuid/dist/commonjs-browser/rng.js
var require_rng = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/rng.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rng;
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
if (!getRandomValues) {
getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
if (!getRandomValues) {
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
}
}
return getRandomValues(rnds8);
}
}
});
// ../../node_modules/uuid/dist/commonjs-browser/regex.js
var require_regex = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/regex.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _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;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/validate.js
var require_validate = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/validate.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _regex = _interopRequireDefault(require_regex());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function validate(uuid) {
return typeof uuid === "string" && _regex.default.test(uuid);
}
var _default = validate;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/stringify.js
var require_stringify = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/stringify.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.unsafeStringify = unsafeStringify;
var _validate = _interopRequireDefault(require_validate());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
return 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]];
}
function stringify(arr, offset = 0) {
const uuid = unsafeStringify(arr, offset);
if (!(0, _validate.default)(uuid)) {
throw TypeError("Stringified UUID is invalid");
}
return uuid;
}
var _default = stringify;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/v1.js
var require_v1 = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/v1.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _rng = _interopRequireDefault(require_rng());
var _stringify2 = require_stringify();
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var _nodeId;
var _clockseq;
var _lastMSecs = 0;
var _lastNSecs = 0;
function v1(options, buf, offset) {
let i = buf && offset || 0;
const b = buf || new Array(16);
options = options || {};
let node = options.node || _nodeId;
let clockseq = options.clockseq !== void 0 ? options.clockseq : _clockseq;
if (node == null || clockseq == null) {
const seedBytes = options.random || (options.rng || _rng.default)();
if (node == null) {
node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];
}
if (clockseq == null) {
clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383;
}
}
let msecs = options.msecs !== void 0 ? options.msecs : Date.now();
let nsecs = options.nsecs !== void 0 ? options.nsecs : _lastNSecs + 1;
const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4;
if (dt < 0 && options.clockseq === void 0) {
clockseq = clockseq + 1 & 16383;
}
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === void 0) {
nsecs = 0;
}
if (nsecs >= 1e4) {
throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq;
msecs += 122192928e5;
const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296;
b[i++] = tl >>> 24 & 255;
b[i++] = tl >>> 16 & 255;
b[i++] = tl >>> 8 & 255;
b[i++] = tl & 255;
const tmh = msecs / 4294967296 * 1e4 & 268435455;
b[i++] = tmh >>> 8 & 255;
b[i++] = tmh & 255;
b[i++] = tmh >>> 24 & 15 | 16;
b[i++] = tmh >>> 16 & 255;
b[i++] = clockseq >>> 8 | 128;
b[i++] = clockseq & 255;
for (let n = 0; n < 6; ++n) {
b[i + n] = node[n];
}
return buf || (0, _stringify2.unsafeStringify)(b);
}
var _default = v1;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/parse.js
var require_parse = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/parse.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _validate = _interopRequireDefault(require_validate());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function parse2(uuid) {
if (!(0, _validate.default)(uuid)) {
throw TypeError("Invalid UUID");
}
let v;
const arr = new Uint8Array(16);
arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
arr[1] = v >>> 16 & 255;
arr[2] = v >>> 8 & 255;
arr[3] = v & 255;
arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
arr[5] = v & 255;
arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
arr[7] = v & 255;
arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
arr[9] = v & 255;
arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;
arr[11] = v / 4294967296 & 255;
arr[12] = v >>> 24 & 255;
arr[13] = v >>> 16 & 255;
arr[14] = v >>> 8 & 255;
arr[15] = v & 255;
return arr;
}
var _default = parse2;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/v35.js
var require_v35 = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/v35.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.URL = exports.DNS = void 0;
exports.default = v35;
var _stringify2 = require_stringify();
var _parse = _interopRequireDefault(require_parse());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function stringToBytes(str) {
str = unescape(encodeURIComponent(str));
const bytes = [];
for (let i = 0; i < str.length; ++i) {
bytes.push(str.charCodeAt(i));
}
return bytes;
}
var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
exports.DNS = DNS;
var URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
exports.URL = URL2;
function v35(name, version, hashfunc) {
function generateUUID(value, namespace, buf, offset) {
var _namespace;
if (typeof value === "string") {
value = stringToBytes(value);
}
if (typeof namespace === "string") {
namespace = (0, _parse.default)(namespace);
}
if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
}
let bytes = new Uint8Array(16 + value.length);
bytes.set(namespace);
bytes.set(value, namespace.length);
bytes = hashfunc(bytes);
bytes[6] = bytes[6] & 15 | version;
bytes[8] = bytes[8] & 63 | 128;
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = bytes[i];
}
return buf;
}
return (0, _stringify2.unsafeStringify)(bytes);
}
try {
generateUUID.name = name;
} catch (err) {
}
generateUUID.DNS = DNS;
generateUUID.URL = URL2;
return generateUUID;
}
}
});
// ../../node_modules/uuid/dist/commonjs-browser/md5.js
var require_md5 = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/md5.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function md5(bytes) {
if (typeof bytes === "string") {
const msg = unescape(encodeURIComponent(bytes));
bytes = new Uint8Array(msg.length);
for (let i = 0; i < msg.length; ++i) {
bytes[i] = msg.charCodeAt(i);
}
}
return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
}
function md5ToHexEncodedArray(input) {
const output = [];
const length32 = input.length * 32;
const hexTab = "0123456789abcdef";
for (let i = 0; i < length32; i += 8) {
const x = input[i >> 5] >>> i % 32 & 255;
const hex = parseInt(hexTab.charAt(x >>> 4 & 15) + hexTab.charAt(x & 15), 16);
output.push(hex);
}
return output;
}
function getOutputLength(inputLength8) {
return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
}
function wordsToMd5(x, len) {
x[len >> 5] |= 128 << len % 32;
x[getOutputLength(len) - 1] = len;
let a = 1732584193;
let b = -271733879;
let c = -1732584194;
let d = 271733878;
for (let i = 0; i < x.length; i += 16) {
const olda = a;
const oldb = b;
const oldc = c;
const 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];
}
function bytesToWords(input) {
if (input.length === 0) {
return [];
}
const length8 = input.length * 8;
const output = new Uint32Array(getOutputLength(length8));
for (let i = 0; i < length8; i += 8) {
output[i >> 5] |= (input[i / 8] & 255) << i % 32;
}
return output;
}
function safeAdd(x, y) {
const lsw = (x & 65535) + (y & 65535);
const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return msw << 16 | lsw & 65535;
}
function bitRotateLeft(num, cnt) {
return num << cnt | num >>> 32 - cnt;
}
function md5cmn(q, a, b, x, s, t) {
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
}
function md5ff(a, b, c, d, x, s, t) {
return md5cmn(b & c | ~b & d, a, b, x, s, t);
}
function md5gg(a, b, c, d, x, s, t) {
return md5cmn(b & d | c & ~d, a, b, x, s, t);
}
function md5hh(a, b, c, d, x, s, t) {
return md5cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5ii(a, b, c, d, x, s, t) {
return md5cmn(c ^ (b | ~d), a, b, x, s, t);
}
var _default = md5;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/v3.js
var require_v3 = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/v3.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _v = _interopRequireDefault(require_v35());
var _md = _interopRequireDefault(require_md5());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var v3 = (0, _v.default)("v3", 48, _md.default);
var _default = v3;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/native.js
var require_native = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/native.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
var _default = {
randomUUID
};
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/v4.js
var require_v4 = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/v4.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _native = _interopRequireDefault(require_native());
var _rng = _interopRequireDefault(require_rng());
var _stringify2 = require_stringify();
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function v4(options, buf, offset) {
if (_native.default.randomUUID && !buf && !options) {
return _native.default.randomUUID();
}
options = options || {};
const rnds = options.random || (options.rng || _rng.default)();
rnds[6] = rnds[6] & 15 | 64;
rnds[8] = rnds[8] & 63 | 128;
if (buf) {
offset = offset || 0;
for (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return (0, _stringify2.unsafeStringify)(rnds);
}
var _default = v4;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/sha1.js
var require_sha1 = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/sha1.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
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) {
const K = [1518500249, 1859775393, 2400959708, 3395469782];
const H = [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
if (typeof bytes === "string") {
const msg = unescape(encodeURIComponent(bytes));
bytes = [];
for (let i = 0; i < msg.length; ++i) {
bytes.push(msg.charCodeAt(i));
}
} else if (!Array.isArray(bytes)) {
bytes = Array.prototype.slice.call(bytes);
}
bytes.push(128);
const l = bytes.length / 4 + 2;
const N = Math.ceil(l / 16);
const M = new Array(N);
for (let i = 0; i < N; ++i) {
const arr = new Uint32Array(16);
for (let 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 & 4294967295;
for (let i = 0; i < N; ++i) {
const W = new Uint32Array(80);
for (let t = 0; t < 16; ++t) {
W[t] = M[i][t];
}
for (let t = 16; t < 80; ++t) {
W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
}
let a = H[0];
let b = H[1];
let c = H[2];
let d = H[3];
let e = H[4];
for (let t = 0; t < 80; ++t) {
const s = Math.floor(t / 20);
const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 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 & 255, H[0] >> 16 & 255, H[0] >> 8 & 255, H[0] & 255, H[1] >> 24 & 255, H[1] >> 16 & 255, H[1] >> 8 & 255, H[1] & 255, H[2] >> 24 & 255, H[2] >> 16 & 255, H[2] >> 8 & 255, H[2] & 255, H[3] >> 24 & 255, H[3] >> 16 & 255, H[3] >> 8 & 255, H[3] & 255, H[4] >> 24 & 255, H[4] >> 16 & 255, H[4] >> 8 & 255, H[4] & 255];
}
var _default = sha1;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/v5.js
var require_v5 = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/v5.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _v = _interopRequireDefault(require_v35());
var _sha = _interopRequireDefault(require_sha1());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var v5 = (0, _v.default)("v5", 80, _sha.default);
var _default = v5;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/nil.js
var require_nil = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/nil.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = "00000000-0000-0000-0000-000000000000";
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/version.js
var require_version = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/version.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _validate = _interopRequireDefault(require_validate());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function version(uuid) {
if (!(0, _validate.default)(uuid)) {
throw TypeError("Invalid UUID");
}
return parseInt(uuid.slice(14, 15), 16);
}
var _default = version;
exports.default = _default;
}
});
// ../../node_modules/uuid/dist/commonjs-browser/index.js
var require_commonjs_browser = __commonJS({
"../../node_modules/uuid/dist/commonjs-browser/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "NIL", {
enumerable: true,
get: function get() {
return _nil.default;
}
});
Object.defineProperty(exports, "parse", {
enumerable: true,
get: function get() {
return _parse.default;
}
});
Object.defineProperty(exports, "stringify", {
enumerable: true,
get: function get() {
return _stringify2.default;
}
});
Object.defineProperty(exports, "v1", {
enumerable: true,
get: function get() {
return _v.default;
}
});
Object.defineProperty(exports, "v3", {
enumerable: true,
get: function get() {
return _v2.default;
}
});
Object.defineProperty(exports, "v4", {
enumerable: true,
get: function get() {
return _v3.default;
}
});
Object.defineProperty(exports, "v5", {
enumerable: true,
get: function get() {
return _v4.default;
}
});
Object.defineProperty(exports, "validate", {
enumerable: true,
get: function get() {
return _validate.default;
}
});
Object.defineProperty(exports, "version", {
enumerable: true,
get: function get() {
return _version.default;
}
});
var _v = _interopRequireDefault(require_v1());
var _v2 = _interopRequireDefault(require_v3());
var _v3 = _interopRequireDefault(require_v4());
var _v4 = _interopRequireDefault(require_v5());
var _nil = _interopRequireDefault(require_nil());
var _version = _interopRequireDefault(require_version());
var _validate = _interopRequireDefault(require_validate());
var _stringify2 = _interopRequireDefault(require_stringify());
var _parse = _interopRequireDefault(require_parse());
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Guid.js
var require_Guid = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Guid.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNoDashGuid = exports.createGuid = void 0;
var uuid_1 = require_commonjs_browser();
var createGuid = () => (0, uuid_1.v4)();
exports.createGuid = createGuid;
var createNoDashGuid = () => createGuid().replace(new RegExp("-", "g"), "").toUpperCase();
exports.createNoDashGuid = createNoDashGuid;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/PlatformEvent.js
var require_PlatformEvent = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/PlatformEvent.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlatformEvent = exports.EventType = void 0;
var Guid_js_1 = require_Guid();
var EventType;
(function(EventType2) {
EventType2[EventType2["Debug"] = 0] = "Debug";
EventType2[EventType2["Info"] = 1] = "Info";
EventType2[EventType2["Warning"] = 2] = "Warning";
EventType2[EventType2["Error"] = 3] = "Error";
EventType2[EventType2["None"] = 4] = "None";
})(EventType = exports.EventType || (exports.EventType = {}));
var PlatformEvent = class {
constructor(eventName, eventType) {
this.privName = eventName;
this.privEventId = (0, Guid_js_1.createNoDashGuid)();
this.privEventTime = (/* @__PURE__ */ new Date()).toISOString();
this.privEventType = eventType;
this.privMetadata = {};
}
get name() {
return this.privName;
}
get eventId() {
return this.privEventId;
}
get eventTime() {
return this.privEventTime;
}
get eventType() {
return this.privEventType;
}
get metadata() {
return this.privMetadata;
}
};
exports.PlatformEvent = PlatformEvent;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/AudioSourceEvents.js
var require_AudioSourceEvents = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/AudioSourceEvents.js"(exports) {
"use strict";
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;
var PlatformEvent_js_1 = require_PlatformEvent();
var AudioSourceEvent2 = class extends PlatformEvent_js_1.PlatformEvent {
constructor(eventName, audioSourceId, eventType = PlatformEvent_js_1.EventType.Info) {
super(eventName, eventType);
this.privAudioSourceId = audioSourceId;
}
get audioSourceId() {
return this.privAudioSourceId;
}
};
exports.AudioSourceEvent = AudioSourceEvent2;
var AudioSourceInitializingEvent = class extends AudioSourceEvent2 {
constructor(audioSourceId) {
super("AudioSourceInitializingEvent", audioSourceId);
}
};
exports.AudioSourceInitializingEvent = AudioSourceInitializingEvent;
var AudioSourceReadyEvent = class extends AudioSourceEvent2 {
constructor(audioSourceId) {
super("AudioSourceReadyEvent", audioSourceId);
}
};
exports.AudioSourceReadyEvent = AudioSourceReadyEvent;
var AudioSourceOffEvent = class extends AudioSourceEvent2 {
constructor(audioSourceId) {
super("AudioSourceOffEvent", audioSourceId);
}
};
exports.AudioSourceOffEvent = AudioSourceOffEvent;
var AudioSourceErrorEvent = class extends AudioSourceEvent2 {
constructor(audioSourceId, error) {
super("AudioSourceErrorEvent", audioSourceId, PlatformEvent_js_1.EventType.Error);
this.privError = error;
}
get error() {
return this.privError;
}
};
exports.AudioSourceErrorEvent = AudioSourceErrorEvent;
var AudioStreamNodeEvent = class extends AudioSourceEvent2 {
constructor(eventName, audioSourceId, audioNodeId) {
super(eventName, audioSourceId);
this.privAudioNodeId = audioNodeId;
}
get audioNodeId() {
return this.privAudioNodeId;
}
};
exports.AudioStreamNodeEvent = AudioStreamNodeEvent;
var AudioStreamNodeAttachingEvent = class extends AudioStreamNodeEvent {
constructor(audioSourceId, audioNodeId) {
super("AudioStreamNodeAttachingEvent", audioSourceId, audioNodeId);
}
};
exports.AudioStreamNodeAttachingEvent = AudioStreamNodeAttachingEvent;
var AudioStreamNodeAttachedEvent = class extends AudioStreamNodeEvent {
constructor(audioSourceId, audioNodeId) {
super("AudioStreamNodeAttachedEvent", audioSourceId, audioNodeId);
}
};
exports.AudioStreamNodeAttachedEvent = AudioStreamNodeAttachedEvent;
var AudioStreamNodeDetachedEvent = class extends AudioStreamNodeEvent {
constructor(audioSourceId, audioNodeId) {
super("AudioStreamNodeDetachedEvent", audioSourceId, audioNodeId);
}
};
exports.AudioStreamNodeDetachedEvent = AudioStreamNodeDetachedEvent;
var AudioStreamNodeErrorEvent = class extends AudioStreamNodeEvent {
constructor(audioSourceId, audioNodeId, error) {
super("AudioStreamNodeErrorEvent", audioSourceId, audioNodeId);
this.privError = error;
}
get error() {
return this.privError;
}
};
exports.AudioStreamNodeErrorEvent = AudioStreamNodeErrorEvent;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/ConnectionEvents.js
var require_ConnectionEvents = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/ConnectionEvents.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionRedirectEvent = exports.ConnectionMessageSentEvent = exports.ConnectionMessageReceivedEvent = exports.ConnectionEstablishErrorEvent = exports.ConnectionErrorEvent = exports.ConnectionClosedEvent = exports.ConnectionEstablishedEvent = exports.ConnectionStartEvent = exports.ConnectionEvent = exports.ServiceEvent = void 0;
var PlatformEvent_js_1 = require_PlatformEvent();
var ServiceEvent = class extends PlatformEvent_js_1.PlatformEvent {
constructor(eventName, jsonstring, eventType = PlatformEvent_js_1.EventType.Info) {
super(eventName, eventType);
this.privJsonResult = jsonstring;
}
get jsonString() {
return this.privJsonResult;
}
};
exports.ServiceEvent = ServiceEvent;
var ConnectionEvent = class extends PlatformEvent_js_1.PlatformEvent {
constructor(eventName, connectionId, eventType = PlatformEvent_js_1.EventType.Info) {
super(eventName, eventType);
this.privConnectionId = connectionId;
}
get connectionId() {
return this.privConnectionId;
}
};
exports.ConnectionEvent = ConnectionEvent;
var ConnectionStartEvent = class extends ConnectionEvent {
constructor(connectionId, uri, headers) {
super("ConnectionStartEvent", connectionId);
this.privUri = uri;
this.privHeaders = headers;
}
get uri() {
return this.privUri;
}
get headers() {
return this.privHeaders;
}
};
exports.ConnectionStartEvent = ConnectionStartEvent;
var ConnectionEstablishedEvent = class extends ConnectionEvent {
constructor(connectionId) {
super("ConnectionEstablishedEvent", connectionId);
}
};
exports.ConnectionEstablishedEvent = ConnectionEstablishedEvent;
var ConnectionClosedEvent = class extends ConnectionEvent {
constructor(connectionId, statusCode, reason) {
super("ConnectionClosedEvent", connectionId, PlatformEvent_js_1.EventType.Debug);
this.privReason = reason;
this.privStatusCode = statusCode;
}
get reason() {
return this.privReason;
}
get statusCode() {
return this.privStatusCode;
}
};
exports.ConnectionClosedEvent = ConnectionClosedEvent;
var ConnectionErrorEvent = class extends ConnectionEvent {
constructor(connectionId, message, type) {
super("ConnectionErrorEvent", connectionId, PlatformEvent_js_1.EventType.Debug);
this.privMessage = message;
this.privType = type;
}
get message() {
return this.privMessage;
}
get type() {
return this.privType;
}
};
exports.ConnectionErrorEvent = ConnectionErrorEvent;
var ConnectionEstablishErrorEvent = class extends ConnectionEvent {
constructor(connectionId, statuscode, reason) {
super("ConnectionEstablishErrorEvent", connectionId, PlatformEvent_js_1.EventType.Error);
this.privStatusCode = statuscode;
this.privReason = reason;
}
get reason() {
return this.privReason;
}
get statusCode() {
return this.privStatusCode;
}
};
exports.ConnectionEstablishErrorEvent = ConnectionEstablishErrorEvent;
var ConnectionMessageReceivedEvent = class extends ConnectionEvent {
constructor(connectionId, networkReceivedTimeISO, message) {
super("ConnectionMessageReceivedEvent", connectionId);
this.privNetworkReceivedTime = networkReceivedTimeISO;
this.privMessage = message;
}
get networkReceivedTime() {
return this.privNetworkReceivedTime;
}
get message() {
return this.privMessage;
}
};
exports.ConnectionMessageReceivedEvent = ConnectionMessageReceivedEvent;
var ConnectionMessageSentEvent = class extends ConnectionEvent {
constructor(connectionId, networkSentTimeISO, message) {
super("ConnectionMessageSentEvent", connectionId);
this.privNetworkSentTime = networkSentTimeISO;
this.privMessage = message;
}
get networkSentTime() {
return this.privNetworkSentTime;
}
get message() {
return this.privMessage;
}
};
exports.ConnectionMessageSentEvent = ConnectionMessageSentEvent;
var ConnectionRedirectEvent = class extends ConnectionEvent {
constructor(connectionId, redirectUrl, originalUrl, context) {
super("ConnectionRedirectEvent", connectionId, PlatformEvent_js_1.EventType.Info);
this.privRedirectUrl = redirectUrl;
this.privOriginalUrl = originalUrl;
this.privContext = context;
}
get redirectUrl() {
return this.privRedirectUrl;
}
get originalUrl() {
return this.privOriginalUrl;
}
get context() {
return this.privContext;
}
};
exports.ConnectionRedirectEvent = ConnectionRedirectEvent;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Error.js
var require_Error = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Error.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjectDisposedError = exports.InvalidOperationError = exports.ArgumentNullError = void 0;
var ArgumentNullError = class extends Error {
/**
* Creates an instance of ArgumentNullError.
*
* @param {string} argumentName - Name of the argument that is null
*
* @memberOf ArgumentNullError
*/
constructor(argumentName) {
super(argumentName);
this.name = "ArgumentNull";
this.message = argumentName;
}
};
exports.ArgumentNullError = ArgumentNullError;
var InvalidOperationError = class extends Error {
/**
* Creates an instance of InvalidOperationError.
*
* @param {string} error - The error
*
* @memberOf InvalidOperationError
*/
constructor(error) {
super(error);
this.name = "InvalidOperation";
this.message = error;
}
};
exports.InvalidOperationError = InvalidOperationError;
var ObjectDisposedError = class extends Error {
/**
* Creates an instance of ObjectDisposedError.
*
* @param {string} objectName - The object that is disposed
* @param {string} error - The error
*
* @memberOf ObjectDisposedError
*/
constructor(objectName, error) {
super(error);
this.name = objectName + "ObjectDisposed";
this.message = error;
}
};
exports.ObjectDisposedError = ObjectDisposedError;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/ConnectionMessage.js
var require_ConnectionMessage = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/ConnectionMessage.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionMessage = exports.MessageType = void 0;
var Error_js_1 = require_Error();
var Guid_js_1 = require_Guid();
var MessageType;
(function(MessageType2) {
MessageType2[MessageType2["Text"] = 0] = "Text";
MessageType2[MessageType2["Binary"] = 1] = "Binary";
})(MessageType = exports.MessageType || (exports.MessageType = {}));
var ConnectionMessage = class {
constructor(messageType, body, headers, id) {
this.privBody = null;
if (messageType === MessageType.Text && body && !(typeof body === "string")) {
throw new Error_js_1.InvalidOperationError("Payload must be a string");
}
if (messageType === MessageType.Binary && body && !(body instanceof ArrayBuffer)) {
throw new Error_js_1.InvalidOperationError("Payload must be ArrayBuffer");
}
this.privMessageType = messageType;
this.privBody = body;
this.privHeaders = headers ? headers : {};
this.privId = id ? id : (0, Guid_js_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;
}
}
get messageType() {
return this.privMessageType;
}
get headers() {
return this.privHeaders;
}
get body() {
return this.privBody;
}
get textBody() {
if (this.privMessageType === MessageType.Binary) {
throw new Error_js_1.InvalidOperationError("Not supported for binary message");
}
return this.privBody;
}
get binaryBody() {
if (this.privMessageType === MessageType.Text) {
throw new Error_js_1.InvalidOperationError("Not supported for text message");
}
return this.privBody;
}
get id() {
return this.privId;
}
};
exports.ConnectionMessage = ConnectionMessage;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/ConnectionOpenResponse.js
var require_ConnectionOpenResponse = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/ConnectionOpenResponse.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionOpenResponse = void 0;
var ConnectionOpenResponse = class {
constructor(statusCode, reason) {
this.privStatusCode = statusCode;
this.privReason = reason;
}
get statusCode() {
return this.privStatusCode;
}
get reason() {
return this.privReason;
}
};
exports.ConnectionOpenResponse = ConnectionOpenResponse;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/DeferralMap.js
var require_DeferralMap = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/DeferralMap.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeferralMap = void 0;
var DeferralMap = class {
constructor() {
this.privMap = {};
}
add(id, deferral) {
this.privMap[id] = deferral;
}
getId(id) {
return this.privMap[id];
}
complete(id, result) {
try {
this.privMap[id].resolve(result);
} catch (error) {
this.privMap[id].reject(error);
} finally {
this.privMap[id] = void 0;
}
}
};
exports.DeferralMap = DeferralMap;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/DialogEvents.js
var require_DialogEvents = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/DialogEvents.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SendingAgentContextMessageEvent = exports.DialogEvent = void 0;
var PlatformEvent_js_1 = require_PlatformEvent();
var DialogEvent = class extends PlatformEvent_js_1.PlatformEvent {
constructor(eventName, eventType = PlatformEvent_js_1.EventType.Info) {
super(eventName, eventType);
}
};
exports.DialogEvent = DialogEvent;
var SendingAgentContextMessageEvent = class extends DialogEvent {
constructor(agentConfig) {
super("SendingAgentContextMessageEvent");
this.privAgentConfig = agentConfig;
}
get agentConfig() {
return this.privAgentConfig;
}
};
exports.SendingAgentContextMessageEvent = SendingAgentContextMessageEvent;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/EventSource.js
var require_EventSource = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/EventSource.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventSource = void 0;
var Error_js_1 = require_Error();
var Guid_js_1 = require_Guid();
var EventSource = class {
constructor(metadata) {
this.privEventListeners = {};
this.privIsDisposed = false;
this.privConsoleListener = void 0;
this.privMetadata = metadata;
}
onEvent(event) {
if (this.isDisposed()) {
throw new Error_js_1.ObjectDisposedError("EventSource");
}
if (this.metadata) {
for (const paramName in this.metadata) {
if (paramName) {
if (event.metadata) {
if (!event.metadata[paramName]) {
event.metadata[paramName] = this.metadata[paramName];
}
}
}
}
}
for (const eventId in this.privEventListeners) {
if (eventId && this.privEventListeners[eventId]) {
this.privEventListeners[eventId](event);
}
}
}
attach(onEventCallback) {
const id = (0, Guid_js_1.createNoDashGuid)();
this.privEventListeners[id] = onEventCallback;
return {
detach: () => {
delete this.privEventListeners[id];
return Promise.resolve();
}
};
}
attachListener(listener) {
return this.attach((e) => listener.onEvent(e));
}
attachConsoleListener(listener) {
if (!!this.privConsoleListener) {
void this.privConsoleListener.detach();
}
this.privConsoleListener = this.attach((e) => listener.onEvent(e));
return this.privConsoleListener;
}
isDisposed() {
return this.privIsDisposed;
}
dispose() {
this.privEventListeners = null;
this.privIsDisposed = true;
}
get metadata() {
return this.privMetadata;
}
};
exports.EventSource = EventSource;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Events.js
var require_Events = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Events.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Events = void 0;
var Error_js_1 = require_Error();
var EventSource_js_1 = require_EventSource();
var Events = class _Events {
static setEventSource(eventSource) {
if (!eventSource) {
throw new Error_js_1.ArgumentNullError("eventSource");
}
_Events.privInstance = eventSource;
}
static get instance() {
return _Events.privInstance;
}
};
exports.Events = Events;
Events.privInstance = new EventSource_js_1.EventSource();
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IAudioSource.js
var require_IAudioSource = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IAudioSource.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IConnection.js
var require_IConnection = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IConnection.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionState = void 0;
var ConnectionState;
(function(ConnectionState2) {
ConnectionState2[ConnectionState2["None"] = 0] = "None";
ConnectionState2[ConnectionState2["Connected"] = 1] = "Connected";
ConnectionState2[ConnectionState2["Connecting"] = 2] = "Connecting";
ConnectionState2[ConnectionState2["Disconnected"] = 3] = "Disconnected";
})(ConnectionState = exports.ConnectionState || (exports.ConnectionState = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IDetachable.js
var require_IDetachable = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IDetachable.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IDictionary.js
var require_IDictionary = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IDictionary.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IDisposable.js
var require_IDisposable = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IDisposable.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IEventListener.js
var require_IEventListener = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IEventListener.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IEventSource.js
var require_IEventSource = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IEventSource.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IErrorMessages.js
var require_IErrorMessages = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IErrorMessages.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/ITimer.js
var require_ITimer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/ITimer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IWebsocketMessageFormatter.js
var require_IWebsocketMessageFormatter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IWebsocketMessageFormatter.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/List.js
var require_List = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/List.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.List = void 0;
var Error_js_1 = require_Error();
var List = class _List {
constructor(list) {
this.privSubscriptionIdCounter = 0;
this.privAddSubscriptions = {};
this.privRemoveSubscriptions = {};
this.privDisposedSubscriptions = {};
this.privDisposeReason = null;
this.privList = [];
if (list) {
for (const item of list) {
this.privList.push(item);
}
}
}
get(itemIndex) {
this.throwIfDisposed();
return this.privList[itemIndex];
}
first() {
return this.get(0);
}
last() {
return this.get(this.length() - 1);
}
add(item) {
this.throwIfDisposed();
this.insertAt(this.privList.length, item);
}
insertAt(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);
}
removeFirst() {
this.throwIfDisposed();
return this.removeAt(0);
}
removeLast() {
this.throwIfDisposed();
return this.removeAt(this.length() - 1);
}
removeAt(index) {
this.throwIfDisposed();
return this.remove(index, 1)[0];
}
remove(index, count) {
this.throwIfDisposed();
const removedElements = this.privList.splice(index, count);
this.triggerSubscriptions(this.privRemoveSubscriptions);
return removedElements;
}
clear() {
this.throwIfDisposed();
this.remove(0, this.length());
}
length() {
this.throwIfDisposed();
return this.privList.length;
}
onAdded(addedCallback) {
this.throwIfDisposed();
const subscriptionId = this.privSubscriptionIdCounter++;
this.privAddSubscriptions[subscriptionId] = addedCallback;
return {
detach: () => {
delete this.privAddSubscriptions[subscriptionId];
return Promise.resolve();
}
};
}
onRemoved(removedCallback) {
this.throwIfDisposed();
const subscriptionId = this.privSubscriptionIdCounter++;
this.privRemoveSubscriptions[subscriptionId] = removedCallback;
return {
detach: () => {
delete this.privRemoveSubscriptions[subscriptionId];
return Promise.resolve();
}
};
}
onDisposed(disposedCallback) {
this.throwIfDisposed();
const subscriptionId = this.privSubscriptionIdCounter++;
this.privDisposedSubscriptions[subscriptionId] = disposedCallback;
return {
detach: () => {
delete this.privDisposedSubscriptions[subscriptionId];
return Promise.resolve();
}
};
}
join(seperator) {
this.throwIfDisposed();
return this.privList.join(seperator);
}
toArray() {
const cloneCopy = Array();
this.privList.forEach((val) => {
cloneCopy.push(val);
});
return cloneCopy;
}
any(callback) {
this.throwIfDisposed();
if (callback) {
return this.where(callback).length() > 0;
} else {
return this.length() > 0;
}
}
all(callback) {
this.throwIfDisposed();
return this.where(callback).length() === this.length();
}
forEach(callback) {
this.throwIfDisposed();
for (let i = 0; i < this.length(); i++) {
callback(this.privList[i], i);
}
}
select(callback) {
this.throwIfDisposed();
const selectList = [];
for (let i = 0; i < this.privList.length; i++) {
selectList.push(callback(this.privList[i], i));
}
return new _List(selectList);
}
where(callback) {
this.throwIfDisposed();
const filteredList = new _List();
for (let i = 0; i < this.privList.length; i++) {
if (callback(this.privList[i], i)) {
filteredList.add(this.privList[i]);
}
}
return filteredList;
}
orderBy(compareFn) {
this.throwIfDisposed();
const clonedArray = this.toArray();
const orderedArray = clonedArray.sort(compareFn);
return new _List(orderedArray);
}
orderByDesc(compareFn) {
this.throwIfDisposed();
return this.orderBy((a, b) => compareFn(b, a));
}
clone() {
this.throwIfDisposed();
return new _List(this.toArray());
}
concat(list) {
this.throwIfDisposed();
return new _List(this.privList.concat(list.toArray()));
}
concatArray(array2) {
this.throwIfDisposed();
return new _List(this.privList.concat(array2));
}
isDisposed() {
return this.privList == null;
}
dispose(reason) {
if (!this.isDisposed()) {
this.privDisposeReason = reason;
this.privList = null;
this.privAddSubscriptions = null;
this.privRemoveSubscriptions = null;
this.triggerSubscriptions(this.privDisposedSubscriptions);
}
}
throwIfDisposed() {
if (this.isDisposed()) {
throw new Error_js_1.ObjectDisposedError("List", this.privDisposeReason);
}
}
triggerSubscriptions(subscriptions) {
if (subscriptions) {
for (const subscriptionId in subscriptions) {
if (subscriptionId) {
subscriptions[subscriptionId]();
}
}
}
}
};
exports.List = List;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Promise.js
var require_Promise = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Promise.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.marshalPromiseToCallbacks = exports.Sink = exports.Deferred = exports.PromiseResultEventSource = exports.PromiseResult = exports.PromiseState = void 0;
var PromiseState;
(function(PromiseState2) {
PromiseState2[PromiseState2["None"] = 0] = "None";
PromiseState2[PromiseState2["Resolved"] = 1] = "Resolved";
PromiseState2[PromiseState2["Rejected"] = 2] = "Rejected";
})(PromiseState = exports.PromiseState || (exports.PromiseState = {}));
var PromiseResult = class {
constructor(promiseResultEventSource) {
this.throwIfError = () => {
if (this.isError) {
throw this.error;
}
};
promiseResultEventSource.on((result) => {
if (!this.privIsCompleted) {
this.privIsCompleted = true;
this.privIsError = false;
this.privResult = result;
}
}, (error) => {
if (!this.privIsCompleted) {
this.privIsCompleted = true;
this.privIsError = true;
this.privError = error;
}
});
}
get isCompleted() {
return this.privIsCompleted;
}
get isError() {
return this.privIsError;
}
get error() {
return this.privError;
}
get result() {
return this.privResult;
}
};
exports.PromiseResult = PromiseResult;
var PromiseResultEventSource = class {
constructor() {
this.setResult = (result) => {
this.privOnSetResult(result);
};
this.setError = (error) => {
this.privOnSetError(error);
};
this.on = (onSetResult, onSetError) => {
this.privOnSetResult = onSetResult;
this.privOnSetError = onSetError;
};
}
};
exports.PromiseResultEventSource = PromiseResultEventSource;
var Deferred = class {
constructor() {
this.resolve = (result) => {
this.privResolve(result);
return this;
};
this.reject = (error) => {
this.privReject(error);
return this;
};
this.privPromise = new Promise((resolve, reject) => {
this.privResolve = resolve;
this.privReject = reject;
});
}
get promise() {
return this.privPromise;
}
};
exports.Deferred = Deferred;
var Sink = class {
constructor() {
this.privState = PromiseState.None;
this.privPromiseResult = null;
this.privPromiseResultEvents = null;
this.privSuccessHandlers = [];
this.privErrorHandlers = [];
this.privPromiseResultEvents = new PromiseResultEventSource();
this.privPromiseResult = new PromiseResult(this.privPromiseResultEvents);
}
get state() {
return this.privState;
}
get result() {
return this.privPromiseResult;
}
resolve(result) {
if (this.privState !== PromiseState.None) {
throw new Error("'Cannot resolve a completed promise'");
}
this.privState = PromiseState.Resolved;
this.privPromiseResultEvents.setResult(result);
for (let i = 0; i < this.privSuccessHandlers.length; i++) {
this.executeSuccessCallback(result, this.privSuccessHandlers[i], this.privErrorHandlers[i]);
}
this.detachHandlers();
}
reject(error) {
if (this.privState !== PromiseState.None) {
throw new Error("'Cannot reject a completed promise'");
}
this.privState = PromiseState.Rejected;
this.privPromiseResultEvents.setError(error);
for (const errorHandler of this.privErrorHandlers) {
this.executeErrorCallback(error, errorHandler);
}
this.detachHandlers();
}
on(successCallback, errorCallback) {
if (successCallback == null) {
successCallback = () => {
};
}
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();
}
}
executeSuccessCallback(result, successCallback, errorCallback) {
try {
successCallback(result);
} catch (e) {
this.executeErrorCallback(`'Unhandled callback error: ${e}'`, errorCallback);
}
}
executeErrorCallback(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}'`);
}
}
detachHandlers() {
this.privErrorHandlers = [];
this.privSuccessHandlers = [];
}
};
exports.Sink = Sink;
function marshalPromiseToCallbacks(promise, cb, err) {
promise.then((val) => {
try {
if (!!cb) {
cb(val);
}
} catch (error) {
if (!!err) {
try {
if (error instanceof Error) {
const typedError = error;
err(typedError.name + ": " + typedError.message);
} else {
err(error);
}
} catch (error2) {
}
}
}
}, (error) => {
if (!!err) {
try {
if (error instanceof Error) {
const typedError = error;
err(typedError.name + ": " + typedError.message);
} else {
err(error);
}
} catch (error2) {
}
}
});
}
exports.marshalPromiseToCallbacks = marshalPromiseToCallbacks;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Queue.js
var require_Queue = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Queue.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Queue = void 0;
var Error_js_1 = require_Error();
var List_js_1 = require_List();
var Promise_js_1 = require_Promise();
var SubscriberType;
(function(SubscriberType2) {
SubscriberType2[SubscriberType2["Dequeue"] = 0] = "Dequeue";
SubscriberType2[SubscriberType2["Peek"] = 1] = "Peek";
})(SubscriberType || (SubscriberType = {}));
var Queue = class {
constructor(list) {
this.privPromiseStore = new List_js_1.List();
this.privIsDrainInProgress = false;
this.privIsDisposing = false;
this.privDisposeReason = null;
this.privList = list ? list : new List_js_1.List();
this.privDetachables = [];
this.privSubscribers = new List_js_1.List();
this.privDetachables.push(this.privList.onAdded(() => this.drain()));
}
enqueue(item) {
this.throwIfDispose();
this.enqueueFromPromise(new Promise((resolve) => resolve(item)));
}
enqueueFromPromise(promise) {
this.throwIfDispose();
promise.then((val) => {
this.privList.add(val);
}, () => {
});
}
dequeue() {
this.throwIfDispose();
const deferredSubscriber = new Promise_js_1.Deferred();
if (this.privSubscribers) {
this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Dequeue });
this.drain();
}
return deferredSubscriber.promise;
}
peek() {
this.throwIfDispose();
const deferredSubscriber = new Promise_js_1.Deferred();
const subs = this.privSubscribers;
if (subs) {
this.privSubscribers.add({ deferral: deferredSubscriber, type: SubscriberType.Peek });
this.drain();
}
return deferredSubscriber.promise;
}
length() {
this.throwIfDispose();
return this.privList.length();
}
isDisposed() {
return this.privSubscribers == null;
}
async drainAndDispose(pendingItemProcessor, reason) {
if (!this.isDisposed() && !this.privIsDisposing) {
this.privDisposeReason = reason;
this.privIsDisposing = true;
const subs = this.privSubscribers;
if (subs) {
while (subs.length() > 0) {
const subscriber = subs.removeFirst();
subscriber.deferral.resolve(void 0);
}
if (this.privSubscribers === subs) {
this.privSubscribers = subs;
}
}
for (const detachable of this.privDetachables) {
await detachable.detach();
}
if (this.privPromiseStore.length() > 0 && pendingItemProcessor) {
const promiseArray = [];
this.privPromiseStore.toArray().forEach((wrapper) => {
promiseArray.push(wrapper);
});
return Promise.all(promiseArray).finally(() => {
this.privSubscribers = null;
this.privList.forEach((item) => {
pendingItemProcessor(item);
});
this.privList = null;
return;
}).then();
} else {
this.privSubscribers = null;
this.privList = null;
}
}
}
async dispose(reason) {
await this.drainAndDispose(null, reason);
}
drain() {
if (!this.privIsDrainInProgress && !this.privIsDisposing) {
this.privIsDrainInProgress = true;
const subs = this.privSubscribers;
const lists = this.privList;
if (subs && lists) {
while (lists.length() > 0 && subs.length() > 0 && !this.privIsDisposing) {
const subscriber = subs.removeFirst();
if (subscriber.type === SubscriberType.Peek) {
subscriber.deferral.resolve(lists.first());
} else {
const dequeuedItem = lists.removeFirst();
subscriber.deferral.resolve(dequeuedItem);
}
}
if (this.privSubscribers === subs) {
this.privSubscribers = subs;
}
if (this.privList === lists) {
this.privList = lists;
}
}
this.privIsDrainInProgress = false;
}
}
throwIfDispose() {
if (this.isDisposed()) {
if (this.privDisposeReason) {
throw new Error_js_1.InvalidOperationError(this.privDisposeReason);
}
throw new Error_js_1.ObjectDisposedError("Queue");
} else if (this.privIsDisposing) {
throw new Error_js_1.InvalidOperationError("Queue disposing");
}
}
};
exports.Queue = Queue;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/RawWebsocketMessage.js
var require_RawWebsocketMessage = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/RawWebsocketMessage.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RawWebsocketMessage = void 0;
var ConnectionMessage_js_1 = require_ConnectionMessage();
var Error_js_1 = require_Error();
var Guid_js_1 = require_Guid();
var RawWebsocketMessage = class {
constructor(messageType, payload, id) {
this.privPayload = null;
if (!payload) {
throw new Error_js_1.ArgumentNullError("payload");
}
if (messageType === ConnectionMessage_js_1.MessageType.Binary && Object.getPrototypeOf(payload).constructor.name !== "ArrayBuffer") {
throw new Error_js_1.InvalidOperationError("Payload must be ArrayBuffer");
}
if (messageType === ConnectionMessage_js_1.MessageType.Text && !(typeof payload === "string")) {
throw new Error_js_1.InvalidOperationError("Payload must be a string");
}
this.privMessageType = messageType;
this.privPayload = payload;
this.privId = id ? id : (0, Guid_js_1.createNoDashGuid)();
}
get messageType() {
return this.privMessageType;
}
get payload() {
return this.privPayload;
}
get textContent() {
if (this.privMessageType === ConnectionMessage_js_1.MessageType.Binary) {
throw new Error_js_1.InvalidOperationError("Not supported for binary message");
}
return this.privPayload;
}
get binaryContent() {
if (this.privMessageType === ConnectionMessage_js_1.MessageType.Text) {
throw new Error_js_1.InvalidOperationError("Not supported for text message");
}
return this.privPayload;
}
get id() {
return this.privId;
}
};
exports.RawWebsocketMessage = RawWebsocketMessage;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/RiffPcmEncoder.js
var require_RiffPcmEncoder = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/RiffPcmEncoder.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RiffPcmEncoder = void 0;
var RiffPcmEncoder = class {
constructor(actualSampleRate, desiredSampleRate) {
this.privActualSampleRate = actualSampleRate;
this.privDesiredSampleRate = desiredSampleRate;
}
encode(actualAudioFrame) {
const audioFrame = this.downSampleAudioFrame(actualAudioFrame, this.privActualSampleRate, this.privDesiredSampleRate);
if (!audioFrame) {
return null;
}
const audioLength = audioFrame.length * 2;
const buffer = new ArrayBuffer(audioLength);
const view = new DataView(buffer);
this.floatTo16BitPCM(view, 0, audioFrame);
return buffer;
}
setString(view, offset, str) {
for (let i = 0; i < str.length; i++) {
view.setUint8(offset + i, str.charCodeAt(i));
}
}
floatTo16BitPCM(view, offset, input) {
for (let i = 0; i < input.length; i++, offset += 2) {
const s = Math.max(-1, Math.min(1, input[i]));
view.setInt16(offset, s < 0 ? s * 32768 : s * 32767, true);
}
}
downSampleAudioFrame(srcFrame, srcRate, dstRate) {
if (!srcFrame) {
return null;
}
if (dstRate === srcRate || dstRate > srcRate) {
return srcFrame;
}
const ratio = srcRate / dstRate;
const dstLength = Math.round(srcFrame.length / ratio);
const dstFrame = new Float32Array(dstLength);
let srcOffset = 0;
let dstOffset = 0;
while (dstOffset < dstLength) {
const nextSrcOffset = Math.round((dstOffset + 1) * ratio);
let accum = 0;
let count = 0;
while (srcOffset < nextSrcOffset && srcOffset < srcFrame.length) {
accum += srcFrame[srcOffset++];
count++;
}
dstFrame[dstOffset++] = accum / count;
}
return dstFrame;
}
};
exports.RiffPcmEncoder = RiffPcmEncoder;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Stream.js
var require_Stream = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Stream.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Stream = void 0;
var Error_js_1 = require_Error();
var Guid_js_1 = require_Guid();
var Queue_js_1 = require_Queue();
var Stream = class {
constructor(streamId) {
this.privIsWriteEnded = false;
this.privIsReadEnded = false;
this.privId = streamId ? streamId : (0, Guid_js_1.createNoDashGuid)();
this.privReaderQueue = new Queue_js_1.Queue();
}
get isClosed() {
return this.privIsWriteEnded;
}
get isReadEnded() {
return this.privIsReadEnded;
}
get id() {
return this.privId;
}
close() {
if (!this.privIsWriteEnded) {
this.writeStreamChunk({
buffer: null,
isEnd: true,
timeReceived: Date.now()
});
this.privIsWriteEnded = true;
}
}
writeStreamChunk(streamChunk) {
this.throwIfClosed();
if (!this.privReaderQueue.isDisposed()) {
try {
this.privReaderQueue.enqueue(streamChunk);
} catch (e) {
}
}
}
read() {
if (this.privIsReadEnded) {
throw new Error_js_1.InvalidOperationError("Stream read has already finished");
}
return this.privReaderQueue.dequeue().then(async (streamChunk) => {
if (streamChunk === void 0 || streamChunk.isEnd) {
await this.privReaderQueue.dispose("End of stream reached");
}
return streamChunk;
});
}
readEnded() {
if (!this.privIsReadEnded) {
this.privIsReadEnded = true;
this.privReaderQueue = new Queue_js_1.Queue();
}
}
throwIfClosed() {
if (this.privIsWriteEnded) {
throw new Error_js_1.InvalidOperationError("Stream closed");
}
}
};
exports.Stream = Stream;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/TranslationStatus.js
var require_TranslationStatus = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/TranslationStatus.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationStatus = void 0;
var TranslationStatus;
(function(TranslationStatus2) {
TranslationStatus2[TranslationStatus2["Success"] = 0] = "Success";
TranslationStatus2[TranslationStatus2["Error"] = 1] = "Error";
})(TranslationStatus = exports.TranslationStatus || (exports.TranslationStatus = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/ChunkedArrayBufferStream.js
var require_ChunkedArrayBufferStream = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/ChunkedArrayBufferStream.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ChunkedArrayBufferStream = void 0;
var Exports_js_1 = require_Exports();
var ChunkedArrayBufferStream = class extends Exports_js_1.Stream {
constructor(targetChunkSize, streamId) {
super(streamId);
this.privTargetChunkSize = Math.round(targetChunkSize);
this.privNextBufferReadyBytes = 0;
}
writeStreamChunk(chunk) {
if (chunk.isEnd || 0 === this.privNextBufferReadyBytes && chunk.buffer.byteLength === this.privTargetChunkSize) {
super.writeStreamChunk(chunk);
return;
}
let bytesCopiedFromBuffer = 0;
while (bytesCopiedFromBuffer < chunk.buffer.byteLength) {
if (void 0 === this.privNextBufferToWrite) {
this.privNextBufferToWrite = new ArrayBuffer(this.privTargetChunkSize);
this.privNextBufferStartTime = chunk.timeReceived;
}
const bytesToCopy = Math.min(chunk.buffer.byteLength - bytesCopiedFromBuffer, this.privTargetChunkSize - this.privNextBufferReadyBytes);
const targetView = new Uint8Array(this.privNextBufferToWrite);
const sourceView = new Uint8Array(chunk.buffer.slice(bytesCopiedFromBuffer, bytesToCopy + bytesCopiedFromBuffer));
targetView.set(sourceView, this.privNextBufferReadyBytes);
this.privNextBufferReadyBytes += bytesToCopy;
bytesCopiedFromBuffer += bytesToCopy;
if (this.privNextBufferReadyBytes === this.privTargetChunkSize) {
super.writeStreamChunk({
buffer: this.privNextBufferToWrite,
isEnd: false,
timeReceived: this.privNextBufferStartTime
});
this.privNextBufferReadyBytes = 0;
this.privNextBufferToWrite = void 0;
}
}
}
close() {
if (0 !== this.privNextBufferReadyBytes && !this.isClosed) {
super.writeStreamChunk({
buffer: this.privNextBufferToWrite.slice(0, this.privNextBufferReadyBytes),
isEnd: false,
timeReceived: this.privNextBufferStartTime
});
}
super.close();
}
};
exports.ChunkedArrayBufferStream = ChunkedArrayBufferStream;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IAudioDestination.js
var require_IAudioDestination = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/IAudioDestination.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Timeout.js
var require_Timeout = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Timeout.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timeout = void 0;
var Timeout = class _Timeout {
static load() {
const scheduledTimeoutFunctions = /* @__PURE__ */ new Map([[0, () => {
}]]);
const unhandledRequests = /* @__PURE__ */ new Map();
const workerScript = `!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})}})}]);`;
const workerUrl = "data:text/javascript;base64," + btoa(workerScript);
const worker = new Worker(workerUrl);
worker.addEventListener("message", ({ data }) => {
if (_Timeout.isCallNotification(data)) {
const { params: { timerId } } = data;
const idOrFunc = scheduledTimeoutFunctions.get(timerId);
if (typeof idOrFunc === "number") {
const unhandledTimerId = unhandledRequests.get(idOrFunc);
if (unhandledTimerId === void 0 || unhandledTimerId !== timerId) {
throw new Error("The timer is in an undefined state.");
}
} else if (typeof idOrFunc !== "undefined") {
idOrFunc();
scheduledTimeoutFunctions.delete(timerId);
} else {
throw new Error("The timer is in an undefined state.");
}
} else if (_Timeout.isClearResponse(data)) {
const { id } = data;
const unhandledTimerId = unhandledRequests.get(id);
if (unhandledTimerId === void 0) {
throw new Error("The timer is in an undefined state.");
}
unhandledRequests.delete(id);
scheduledTimeoutFunctions.delete(unhandledTimerId);
} else {
const { error: { message } } = data;
throw new Error(message);
}
});
const clearTimeout2 = (timerId) => {
const id = Math.random();
unhandledRequests.set(id, timerId);
scheduledTimeoutFunctions.set(timerId, id);
worker.postMessage({
id,
method: "clear",
params: { timerId }
});
};
const setTimeout2 = (func, delay) => {
const timerId = Math.random();
scheduledTimeoutFunctions.set(timerId, func);
worker.postMessage({
id: null,
method: "set",
params: {
delay,
now: performance.now(),
timerId
}
});
return timerId;
};
return {
clearTimeout: clearTimeout2,
setTimeout: setTimeout2
};
}
static loadWorkerTimers() {
return () => {
if (_Timeout.workerTimers !== null) {
return _Timeout.workerTimers;
}
_Timeout.workerTimers = _Timeout.load();
return _Timeout.workerTimers;
};
}
static isCallNotification(message) {
return message.method !== void 0 && message.method === "call";
}
static isClearResponse(message) {
return message.error === null && typeof message.id === "number";
}
};
exports.Timeout = Timeout;
Timeout.workerTimers = null;
Timeout.clearTimeout = (timerId) => Timeout.timers().clearTimeout(timerId);
Timeout.setTimeout = (func, delay) => Timeout.timers().setTimeout(func, delay);
Timeout.timers = Timeout.loadWorkerTimers();
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/OCSPEvents.js
var require_OCSPEvents = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/OCSPEvents.js"(exports) {
"use strict";
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;
var PlatformEvent_js_1 = require_PlatformEvent();
var OCSPEvent = class extends PlatformEvent_js_1.PlatformEvent {
constructor(eventName, eventType, signature) {
super(eventName, eventType);
this.privSignature = signature;
}
};
exports.OCSPEvent = OCSPEvent;
var OCSPMemoryCacheHitEvent = class extends OCSPEvent {
constructor(signature) {
super("OCSPMemoryCacheHitEvent", PlatformEvent_js_1.EventType.Debug, signature);
}
};
exports.OCSPMemoryCacheHitEvent = OCSPMemoryCacheHitEvent;
var OCSPCacheMissEvent = class extends OCSPEvent {
constructor(signature) {
super("OCSPCacheMissEvent", PlatformEvent_js_1.EventType.Debug, signature);
}
};
exports.OCSPCacheMissEvent = OCSPCacheMissEvent;
var OCSPDiskCacheHitEvent = class extends OCSPEvent {
constructor(signature) {
super("OCSPDiskCacheHitEvent", PlatformEvent_js_1.EventType.Debug, signature);
}
};
exports.OCSPDiskCacheHitEvent = OCSPDiskCacheHitEvent;
var OCSPCacheUpdateNeededEvent = class extends OCSPEvent {
constructor(signature) {
super("OCSPCacheUpdateNeededEvent", PlatformEvent_js_1.EventType.Debug, signature);
}
};
exports.OCSPCacheUpdateNeededEvent = OCSPCacheUpdateNeededEvent;
var OCSPMemoryCacheStoreEvent = class extends OCSPEvent {
constructor(signature) {
super("OCSPMemoryCacheStoreEvent", PlatformEvent_js_1.EventType.Debug, signature);
}
};
exports.OCSPMemoryCacheStoreEvent = OCSPMemoryCacheStoreEvent;
var OCSPDiskCacheStoreEvent = class extends OCSPEvent {
constructor(signature) {
super("OCSPDiskCacheStoreEvent", PlatformEvent_js_1.EventType.Debug, signature);
}
};
exports.OCSPDiskCacheStoreEvent = OCSPDiskCacheStoreEvent;
var OCSPCacheUpdateCompleteEvent = class extends OCSPEvent {
constructor(signature) {
super("OCSPCacheUpdateCompleteEvent", PlatformEvent_js_1.EventType.Debug, signature);
}
};
exports.OCSPCacheUpdateCompleteEvent = OCSPCacheUpdateCompleteEvent;
var OCSPStapleReceivedEvent = class extends OCSPEvent {
constructor() {
super("OCSPStapleReceivedEvent", PlatformEvent_js_1.EventType.Debug, "");
}
};
exports.OCSPStapleReceivedEvent = OCSPStapleReceivedEvent;
var OCSPWSUpgradeStartedEvent = class extends OCSPEvent {
constructor(serialNumber) {
super("OCSPWSUpgradeStartedEvent", PlatformEvent_js_1.EventType.Debug, serialNumber);
}
};
exports.OCSPWSUpgradeStartedEvent = OCSPWSUpgradeStartedEvent;
var OCSPCacheEntryExpiredEvent = class extends OCSPEvent {
constructor(serialNumber, expireTime) {
super("OCSPCacheEntryExpiredEvent", PlatformEvent_js_1.EventType.Debug, serialNumber);
this.privExpireTime = expireTime;
}
};
exports.OCSPCacheEntryExpiredEvent = OCSPCacheEntryExpiredEvent;
var OCSPCacheEntryNeedsRefreshEvent = class extends OCSPEvent {
constructor(serialNumber, startTime, expireTime) {
super("OCSPCacheEntryNeedsRefreshEvent", PlatformEvent_js_1.EventType.Debug, serialNumber);
this.privExpireTime = expireTime;
this.privStartTime = startTime;
}
};
exports.OCSPCacheEntryNeedsRefreshEvent = OCSPCacheEntryNeedsRefreshEvent;
var OCSPCacheHitEvent = class extends OCSPEvent {
constructor(serialNumber, startTime, expireTime) {
super("OCSPCacheHitEvent", PlatformEvent_js_1.EventType.Debug, serialNumber);
this.privExpireTime = expireTime;
this.privExpireTimeString = new Date(expireTime).toLocaleDateString();
this.privStartTime = startTime;
this.privStartTimeString = new Date(startTime).toLocaleTimeString();
}
};
exports.OCSPCacheHitEvent = OCSPCacheHitEvent;
var OCSPVerificationFailedEvent = class extends OCSPEvent {
constructor(serialNumber, error) {
super("OCSPVerificationFailedEvent", PlatformEvent_js_1.EventType.Debug, serialNumber);
this.privError = error;
}
};
exports.OCSPVerificationFailedEvent = OCSPVerificationFailedEvent;
var OCSPCacheFetchErrorEvent = class extends OCSPEvent {
constructor(serialNumber, error) {
super("OCSPCacheFetchErrorEvent", PlatformEvent_js_1.EventType.Debug, serialNumber);
this.privError = error;
}
};
exports.OCSPCacheFetchErrorEvent = OCSPCacheFetchErrorEvent;
var OCSPResponseRetrievedEvent = class extends OCSPEvent {
constructor(serialNumber) {
super("OCSPResponseRetrievedEvent", PlatformEvent_js_1.EventType.Debug, serialNumber);
}
};
exports.OCSPResponseRetrievedEvent = OCSPResponseRetrievedEvent;
var OCSPCacheUpdateErrorEvent = class extends OCSPEvent {
constructor(serialNumber, error) {
super("OCSPCacheUpdateErrorEvent", PlatformEvent_js_1.EventType.Debug, serialNumber);
this.privError = error;
}
};
exports.OCSPCacheUpdateErrorEvent = OCSPCacheUpdateErrorEvent;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/BackgroundError.js
var require_BackgroundError = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/BackgroundError.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BackgroundEvent = void 0;
var Exports_js_1 = require_Exports();
var BackgroundEvent = class extends Exports_js_1.PlatformEvent {
constructor(error) {
super("BackgroundEvent", Exports_js_1.EventType.Error);
this.privError = error;
}
get error() {
return this.privError;
}
};
exports.BackgroundEvent = BackgroundEvent;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Exports.js
var require_Exports = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/Exports.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() {
return m[k];
} });
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationStatus = void 0;
__exportStar(require_AudioSourceEvents(), exports);
__exportStar(require_ConnectionEvents(), exports);
__exportStar(require_ConnectionMessage(), exports);
__exportStar(require_ConnectionOpenResponse(), exports);
__exportStar(require_DeferralMap(), exports);
__exportStar(require_DialogEvents(), exports);
__exportStar(require_Error(), exports);
__exportStar(require_Events(), exports);
__exportStar(require_EventSource(), exports);
__exportStar(require_Guid(), exports);
__exportStar(require_IAudioSource(), exports);
__exportStar(require_IConnection(), exports);
__exportStar(require_IDetachable(), exports);
__exportStar(require_IDictionary(), exports);
__exportStar(require_IDisposable(), exports);
__exportStar(require_IEventListener(), exports);
__exportStar(require_IEventSource(), exports);
__exportStar(require_IErrorMessages(), exports);
__exportStar(require_ITimer(), exports);
__exportStar(require_IWebsocketMessageFormatter(), exports);
__exportStar(require_List(), exports);
__exportStar(require_PlatformEvent(), exports);
__exportStar(require_Promise(), exports);
__exportStar(require_Queue(), exports);
__exportStar(require_RawWebsocketMessage(), exports);
__exportStar(require_RiffPcmEncoder(), exports);
__exportStar(require_Stream(), exports);
var TranslationStatus_js_1 = require_TranslationStatus();
Object.defineProperty(exports, "TranslationStatus", { enumerable: true, get: function() {
return TranslationStatus_js_1.TranslationStatus;
} });
__exportStar(require_ChunkedArrayBufferStream(), exports);
__exportStar(require_IAudioDestination(), exports);
__exportStar(require_Timeout(), exports);
__exportStar(require_OCSPEvents(), exports);
__exportStar(require_BackgroundError(), exports);
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/HeaderNames.js
var require_HeaderNames = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/HeaderNames.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HeaderNames = void 0;
var HeaderNames = class {
};
exports.HeaderNames = HeaderNames;
HeaderNames.AuthKey = "Ocp-Apim-Subscription-Key";
HeaderNames.Authorization = "Authorization";
HeaderNames.SpIDAuthKey = "Apim-Subscription-Id";
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";
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/IAuthentication.js
var require_IAuthentication = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/IAuthentication.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthInfo = void 0;
var AuthInfo = class {
constructor(headerName, token) {
this.privHeaderName = headerName;
this.privToken = token;
}
get headerName() {
return this.privHeaderName;
}
get token() {
return this.privToken;
}
};
exports.AuthInfo = AuthInfo;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/CognitiveSubscriptionKeyAuthentication.js
var require_CognitiveSubscriptionKeyAuthentication = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/CognitiveSubscriptionKeyAuthentication.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CognitiveSubscriptionKeyAuthentication = void 0;
var Exports_js_1 = require_Exports();
var HeaderNames_js_1 = require_HeaderNames();
var IAuthentication_js_1 = require_IAuthentication();
var CognitiveSubscriptionKeyAuthentication = class {
/**
* Creates and initializes an instance of the CognitiveSubscriptionKeyAuthentication class.
* @constructor
* @param {string} subscriptionKey - The subscription key
*/
constructor(subscriptionKey) {
if (!subscriptionKey) {
throw new Exports_js_1.ArgumentNullError("subscriptionKey");
}
this.privAuthInfo = new IAuthentication_js_1.AuthInfo(HeaderNames_js_1.HeaderNames.AuthKey, subscriptionKey);
}
/**
* Fetches the subscription key.
* @member
* @function
* @public
* @param {string} authFetchEventId - The id to fetch.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fetch(authFetchEventId) {
return Promise.resolve(this.privAuthInfo);
}
/**
* Fetches the subscription key.
* @member
* @function
* @public
* @param {string} authFetchEventId - The id to fetch.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
fetchOnExpiry(authFetchEventId) {
return Promise.resolve(this.privAuthInfo);
}
};
exports.CognitiveSubscriptionKeyAuthentication = CognitiveSubscriptionKeyAuthentication;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/CognitiveTokenAuthentication.js
var require_CognitiveTokenAuthentication = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/CognitiveTokenAuthentication.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CognitiveTokenAuthentication = void 0;
var Exports_js_1 = require_Exports();
var IAuthentication_js_1 = require_IAuthentication();
var HeaderNames_js_1 = require_HeaderNames();
var CognitiveTokenAuthentication = class _CognitiveTokenAuthentication {
constructor(fetchCallback, fetchOnExpiryCallback) {
if (!fetchCallback) {
throw new Exports_js_1.ArgumentNullError("fetchCallback");
}
if (!fetchOnExpiryCallback) {
throw new Exports_js_1.ArgumentNullError("fetchOnExpiryCallback");
}
this.privFetchCallback = fetchCallback;
this.privFetchOnExpiryCallback = fetchOnExpiryCallback;
}
fetch(authFetchEventId) {
return this.privFetchCallback(authFetchEventId).then((token) => new IAuthentication_js_1.AuthInfo(HeaderNames_js_1.HeaderNames.Authorization, token === void 0 ? void 0 : _CognitiveTokenAuthentication.privTokenPrefix + token));
}
fetchOnExpiry(authFetchEventId) {
return this.privFetchOnExpiryCallback(authFetchEventId).then((token) => new IAuthentication_js_1.AuthInfo(HeaderNames_js_1.HeaderNames.Authorization, token === void 0 ? void 0 : _CognitiveTokenAuthentication.privTokenPrefix + token));
}
};
exports.CognitiveTokenAuthentication = CognitiveTokenAuthentication;
CognitiveTokenAuthentication.privTokenPrefix = "Bearer ";
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/IConnectionFactory.js
var require_IConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/IConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ISynthesisConnectionFactory.js
var require_ISynthesisConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ISynthesisConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// (disabled):fs
var require_fs = __commonJS({
"(disabled):fs"() {
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/LogLevel.js
var require_LogLevel = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/LogLevel.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LogLevel = void 0;
var Exports_js_1 = require_Exports();
Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function() {
return Exports_js_1.EventType;
} });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Contracts.js
var require_Contracts = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Contracts.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Contracts = void 0;
var Contracts = class _Contracts {
static throwIfNullOrUndefined(param, name) {
if (param === void 0 || param === null) {
throw new Error("throwIfNullOrUndefined:" + name);
}
}
static throwIfNull(param, name) {
if (param === null) {
throw new Error("throwIfNull:" + name);
}
}
static throwIfNullOrWhitespace(param, name) {
_Contracts.throwIfNullOrUndefined(param, name);
if (("" + param).trim().length < 1) {
throw new Error("throwIfNullOrWhitespace:" + name);
}
}
static throwIfNullOrTooLong(param, name, maxLength) {
_Contracts.throwIfNullOrUndefined(param, name);
if (("" + param).length > maxLength) {
throw new Error("throwIfNullOrTooLong:" + name + " (more than " + maxLength.toString() + " characters)");
}
}
static throwIfNullOrTooShort(param, name, minLength) {
_Contracts.throwIfNullOrUndefined(param, name);
if (("" + param).length < minLength) {
throw new Error("throwIfNullOrTooShort:" + name + " (less than " + minLength.toString() + " characters)");
}
}
static throwIfDisposed(isDisposed) {
if (isDisposed) {
throw new Error("the object is already disposed");
}
}
static throwIfArrayEmptyOrWhitespace(array2, name) {
_Contracts.throwIfNullOrUndefined(array2, name);
if (array2.length === 0) {
throw new Error("throwIfArrayEmptyOrWhitespace:" + name);
}
for (const item of array2) {
_Contracts.throwIfNullOrWhitespace(item, name);
}
}
static throwIfFileDoesNotExist(param, name) {
_Contracts.throwIfNullOrWhitespace(param, name);
}
static throwIfNotUndefined(param, name) {
if (param !== void 0) {
throw new Error("throwIfNotUndefined:" + name);
}
}
static throwIfNumberOutOfRange(value, name, rangeStart, rangeEnd) {
_Contracts.throwIfNullOrUndefined(value, name);
if (value < rangeStart || value > rangeEnd) {
throw new Error("throwIfNumberOutOfRange:" + name + " (must be between " + rangeStart.toString() + " and " + rangeEnd.toString() + ")");
}
}
};
exports.Contracts = Contracts;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/ConsoleLoggingListener.js
var require_ConsoleLoggingListener = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/ConsoleLoggingListener.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() {
return m[k];
} });
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConsoleLoggingListener = void 0;
var fs = __importStar(require_fs());
var LogLevel_js_1 = require_LogLevel();
var Contracts_js_1 = require_Contracts();
var ConsoleLoggingListener = class {
constructor(logLevelFilter = LogLevel_js_1.LogLevel.None) {
this.privLogPath = void 0;
this.privEnableConsoleOutput = true;
this.privLogLevelFilter = logLevelFilter;
}
set logPath(path) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(fs.openSync, "\nFile System access not available");
this.privLogPath = path;
}
set enableConsoleOutput(enableOutput) {
this.privEnableConsoleOutput = enableOutput;
}
onEvent(event) {
if (event.eventType >= this.privLogLevelFilter) {
const log = this.toString(event);
if (!!this.logCallback) {
this.logCallback(log);
}
if (!!this.privLogPath) {
fs.writeFileSync(this.privLogPath, log + "\n", { flag: "a+" });
}
if (this.privEnableConsoleOutput) {
switch (event.eventType) {
case LogLevel_js_1.LogLevel.Debug:
console.debug(log);
break;
case LogLevel_js_1.LogLevel.Info:
console.info(log);
break;
case LogLevel_js_1.LogLevel.Warning:
console.warn(log);
break;
case LogLevel_js_1.LogLevel.Error:
console.error(log);
break;
default:
console.log(log);
break;
}
}
}
}
toString(event) {
const logFragments = [
`${event.eventTime}`,
`${event.name}`
];
const e = event;
for (const prop in e) {
if (prop && event.hasOwnProperty(prop) && prop !== "eventTime" && prop !== "eventType" && prop !== "eventId" && prop !== "name" && prop !== "constructor") {
const value = e[prop];
let valueToLog = "<NULL>";
if (value !== void 0 && value !== null) {
if (typeof value === "number" || typeof value === "string") {
valueToLog = value.toString();
} else {
valueToLog = JSON.stringify(value);
}
}
logFragments.push(`${prop}: ${valueToLog}`);
}
}
return logFragments.join(" | ");
}
};
exports.ConsoleLoggingListener = ConsoleLoggingListener;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/IRecorder.js
var require_IRecorder = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/IRecorder.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioStreamFormat.js
var require_AudioStreamFormat = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioStreamFormat.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AudioStreamFormatImpl = exports.AudioStreamFormat = exports.AudioFormatTag = void 0;
var AudioFormatTag;
(function(AudioFormatTag2) {
AudioFormatTag2[AudioFormatTag2["PCM"] = 1] = "PCM";
AudioFormatTag2[AudioFormatTag2["MuLaw"] = 2] = "MuLaw";
AudioFormatTag2[AudioFormatTag2["Siren"] = 3] = "Siren";
AudioFormatTag2[AudioFormatTag2["MP3"] = 4] = "MP3";
AudioFormatTag2[AudioFormatTag2["SILKSkype"] = 5] = "SILKSkype";
AudioFormatTag2[AudioFormatTag2["OGG_OPUS"] = 6] = "OGG_OPUS";
AudioFormatTag2[AudioFormatTag2["WEBM_OPUS"] = 7] = "WEBM_OPUS";
AudioFormatTag2[AudioFormatTag2["ALaw"] = 8] = "ALaw";
AudioFormatTag2[AudioFormatTag2["FLAC"] = 9] = "FLAC";
AudioFormatTag2[AudioFormatTag2["OPUS"] = 10] = "OPUS";
AudioFormatTag2[AudioFormatTag2["AMR_WB"] = 11] = "AMR_WB";
AudioFormatTag2[AudioFormatTag2["G722"] = 12] = "G722";
})(AudioFormatTag = exports.AudioFormatTag || (exports.AudioFormatTag = {}));
var AudioStreamFormat = class {
/**
* 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.
*/
static getDefaultInputFormat() {
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.
*/
static getWaveFormat(samplesPerSecond, bitsPerSample, channels, format2) {
return new AudioStreamFormatImpl(samplesPerSecond, bitsPerSample, channels, format2);
}
/**
* 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.
*/
static getWaveFormatPCM(samplesPerSecond, bitsPerSample, channels) {
return new AudioStreamFormatImpl(samplesPerSecond, bitsPerSample, channels);
}
};
exports.AudioStreamFormat = AudioStreamFormat;
var AudioStreamFormatImpl = class _AudioStreamFormatImpl extends AudioStreamFormat {
/**
* 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).
*/
constructor(samplesPerSec = 16e3, bitsPerSample = 16, channels = 1, format2 = AudioFormatTag.PCM) {
super();
let isWavFormat = true;
switch (format2) {
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);
const view = new DataView(this.privHeader);
this.setString(view, 0, "RIFF");
view.setUint32(4, 0, true);
this.setString(view, 8, "WAVEfmt ");
view.setUint32(16, 16, true);
view.setUint16(20, this.formatTag, true);
view.setUint16(22, this.channels, true);
view.setUint32(24, this.samplesPerSec, true);
view.setUint32(28, this.avgBytesPerSec, true);
view.setUint16(32, this.channels * (this.bitsPerSample / 8), true);
view.setUint16(34, this.bitsPerSample, true);
this.setString(view, 36, "data");
view.setUint32(40, 0, true);
}
}
/**
* Retrieves the default input format.
* @member AudioStreamFormatImpl.getDefaultInputFormat
* @function
* @public
* @returns {AudioStreamFormatImpl} The default input format.
*/
static getDefaultInputFormat() {
return new _AudioStreamFormatImpl();
}
/**
* Creates an audio context appropriate to current browser
* @member AudioStreamFormatImpl.getAudioContext
* @function
* @public
* @returns {AudioContext} An audio context instance
*/
/* eslint-disable */
static getAudioContext(sampleRate) {
const AudioContext2 = window.AudioContext || window.webkitAudioContext || false;
if (!!AudioContext2) {
if (sampleRate !== void 0 && navigator.mediaDevices.getSupportedConstraints().sampleRate) {
return new AudioContext2({ sampleRate });
} else {
return new AudioContext2();
}
} else {
throw new Error("Browser does not support Web Audio API (AudioContext is not available).");
}
}
/* eslint-enable */
/**
* Closes the configuration object.
* @member AudioStreamFormatImpl.prototype.close
* @function
* @public
*/
close() {
return;
}
get header() {
return this.privHeader;
}
setString(view, offset, str) {
for (let i = 0; i < str.length; i++) {
view.setUint8(offset + i, str.charCodeAt(i));
}
}
};
exports.AudioStreamFormatImpl = AudioStreamFormatImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/MicAudioSource.js
var require_MicAudioSource = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/MicAudioSource.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MicAudioSource = exports.AudioWorkletSourceURLPropertyName = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var AudioStreamFormat_js_1 = require_AudioStreamFormat();
exports.AudioWorkletSourceURLPropertyName = "MICROPHONE-WorkletSourceUrl";
var MicAudioSource = class _MicAudioSource {
constructor(privRecorder, deviceId, audioSourceId, mediaStream) {
this.privRecorder = privRecorder;
this.deviceId = deviceId;
this.privStreams = {};
this.privOutputChunkSize = _MicAudioSource.AUDIOFORMAT.avgBytesPerSec / 10;
this.privId = audioSourceId ? audioSourceId : (0, Exports_js_2.createNoDashGuid)();
this.privEvents = new Exports_js_2.EventSource();
this.privMediaStream = mediaStream || null;
this.privIsClosing = false;
}
get format() {
return Promise.resolve(_MicAudioSource.AUDIOFORMAT);
}
turnOn() {
if (this.privInitializeDeferral) {
return this.privInitializeDeferral.promise;
}
this.privInitializeDeferral = new Exports_js_2.Deferred();
try {
this.createAudioContext();
} catch (error) {
if (error instanceof Error) {
const typedError = error;
this.privInitializeDeferral.reject(typedError.name + ": " + typedError.message);
} else {
this.privInitializeDeferral.reject(error);
}
return this.privInitializeDeferral.promise;
}
const nav = window.navigator;
let getUserMedia = (
// eslint-disable-next-line
nav.getUserMedia || nav.webkitGetUserMedia || nav.mozGetUserMedia || nav.msGetUserMedia
);
if (!!nav.mediaDevices) {
getUserMedia = (constraints, successCallback, errorCallback) => {
nav.mediaDevices.getUserMedia(constraints).then(successCallback).catch(errorCallback);
};
}
if (!getUserMedia) {
const errorMsg = "Browser does not support getUserMedia.";
this.privInitializeDeferral.reject(errorMsg);
this.onEvent(new Exports_js_2.AudioSourceErrorEvent(errorMsg, ""));
} else {
const next = () => {
this.onEvent(new Exports_js_2.AudioSourceInitializingEvent(this.privId));
if (this.privMediaStream && this.privMediaStream.active) {
this.onEvent(new Exports_js_2.AudioSourceReadyEvent(this.privId));
this.privInitializeDeferral.resolve();
} else {
getUserMedia({ audio: this.deviceId ? { deviceId: this.deviceId } : true, video: false }, (mediaStream) => {
this.privMediaStream = mediaStream;
this.onEvent(new Exports_js_2.AudioSourceReadyEvent(this.privId));
this.privInitializeDeferral.resolve();
}, (error) => {
const errorMsg = `Error occurred during microphone initialization: ${error}`;
this.privInitializeDeferral.reject(errorMsg);
this.onEvent(new Exports_js_2.AudioSourceErrorEvent(this.privId, errorMsg));
});
}
};
if (this.privContext.state === "suspended") {
this.privContext.resume().then(next).catch((reason) => {
this.privInitializeDeferral.reject(`Failed to initialize audio context: ${reason}`);
});
} else {
next();
}
}
return this.privInitializeDeferral.promise;
}
id() {
return this.privId;
}
attach(audioNodeId) {
this.onEvent(new Exports_js_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId));
return this.listen(audioNodeId).then((stream) => {
this.onEvent(new Exports_js_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId));
return {
detach: async () => {
stream.readEnded();
delete this.privStreams[audioNodeId];
this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
return this.turnOff();
},
id: () => audioNodeId,
read: () => stream.read()
};
});
}
detach(audioNodeId) {
if (audioNodeId && this.privStreams[audioNodeId]) {
this.privStreams[audioNodeId].close();
delete this.privStreams[audioNodeId];
this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
}
}
async turnOff() {
for (const streamId in this.privStreams) {
if (streamId) {
const stream = this.privStreams[streamId];
if (stream) {
stream.close();
}
}
}
this.onEvent(new Exports_js_2.AudioSourceOffEvent(this.privId));
if (this.privInitializeDeferral) {
await this.privInitializeDeferral;
this.privInitializeDeferral = null;
}
await this.destroyAudioContext();
return;
}
get events() {
return this.privEvents;
}
get deviceInfo() {
return this.getMicrophoneLabel().then((label) => ({
bitspersample: _MicAudioSource.AUDIOFORMAT.bitsPerSample,
channelcount: _MicAudioSource.AUDIOFORMAT.channels,
connectivity: Exports_js_1.connectivity.Unknown,
manufacturer: "Speech SDK",
model: label,
samplerate: _MicAudioSource.AUDIOFORMAT.samplesPerSec,
type: Exports_js_1.type.Microphones
}));
}
setProperty(name, value) {
if (name === exports.AudioWorkletSourceURLPropertyName) {
this.privRecorder.setWorkletUrl(value);
} else {
throw new Error("Property '" + name + "' is not supported on Microphone.");
}
}
getMicrophoneLabel() {
const defaultMicrophoneName = "microphone";
if (this.privMicrophoneLabel !== void 0) {
return Promise.resolve(this.privMicrophoneLabel);
}
if (this.privMediaStream === void 0 || !this.privMediaStream.active) {
return Promise.resolve(defaultMicrophoneName);
}
this.privMicrophoneLabel = defaultMicrophoneName;
const microphoneDeviceId = this.privMediaStream.getTracks()[0].getSettings().deviceId;
if (void 0 === microphoneDeviceId) {
return Promise.resolve(this.privMicrophoneLabel);
}
const deferred = new Exports_js_2.Deferred();
navigator.mediaDevices.enumerateDevices().then((devices) => {
for (const device of devices) {
if (device.deviceId === microphoneDeviceId) {
this.privMicrophoneLabel = device.label;
break;
}
}
deferred.resolve(this.privMicrophoneLabel);
}, () => deferred.resolve(this.privMicrophoneLabel));
return deferred.promise;
}
async listen(audioNodeId) {
await this.turnOn();
const stream = new Exports_js_2.ChunkedArrayBufferStream(this.privOutputChunkSize, audioNodeId);
this.privStreams[audioNodeId] = stream;
try {
this.privRecorder.record(this.privContext, this.privMediaStream, stream);
} catch (error) {
this.onEvent(new Exports_js_2.AudioStreamNodeErrorEvent(this.privId, audioNodeId, error));
throw error;
}
const result = stream;
return result;
}
onEvent(event) {
this.privEvents.onEvent(event);
Exports_js_2.Events.instance.onEvent(event);
}
createAudioContext() {
if (!!this.privContext) {
return;
}
this.privContext = AudioStreamFormat_js_1.AudioStreamFormatImpl.getAudioContext(_MicAudioSource.AUDIOFORMAT.samplesPerSec);
}
async destroyAudioContext() {
if (!this.privContext) {
return;
}
this.privRecorder.releaseMediaResources(this.privContext);
let hasClose = false;
if ("close" in this.privContext) {
hasClose = true;
}
if (hasClose) {
if (!this.privIsClosing) {
this.privIsClosing = true;
await this.privContext.close();
this.privContext = null;
this.privIsClosing = false;
}
} else if (null !== this.privContext && this.privContext.state === "running") {
await this.privContext.suspend();
}
}
};
exports.MicAudioSource = MicAudioSource;
MicAudioSource.AUDIOFORMAT = AudioStreamFormat_js_1.AudioStreamFormat.getDefaultInputFormat();
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/FileAudioSource.js
var require_FileAudioSource = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/FileAudioSource.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileAudioSource = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var AudioStreamFormat_js_1 = require_AudioStreamFormat();
var FileAudioSource = class {
constructor(file, filename, audioSourceId) {
this.privStreams = {};
this.privHeaderEnd = 44;
this.privId = audioSourceId ? audioSourceId : (0, Exports_js_2.createNoDashGuid)();
this.privEvents = new Exports_js_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";
}
this.privAudioFormatPromise = this.readHeader();
}
get format() {
return this.privAudioFormatPromise;
}
turnOn() {
if (this.privFilename.lastIndexOf(".wav") !== this.privFilename.length - 4) {
const errorMsg = this.privFilename + " is not supported. Only WAVE files are allowed at the moment.";
this.onEvent(new Exports_js_2.AudioSourceErrorEvent(errorMsg, ""));
return Promise.reject(errorMsg);
}
this.onEvent(new Exports_js_2.AudioSourceInitializingEvent(this.privId));
this.onEvent(new Exports_js_2.AudioSourceReadyEvent(this.privId));
return;
}
id() {
return this.privId;
}
async attach(audioNodeId) {
this.onEvent(new Exports_js_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId));
const stream = await this.upload(audioNodeId);
this.onEvent(new Exports_js_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId));
return Promise.resolve({
detach: async () => {
stream.readEnded();
delete this.privStreams[audioNodeId];
this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
await this.turnOff();
},
id: () => audioNodeId,
read: () => stream.read()
});
}
detach(audioNodeId) {
if (audioNodeId && this.privStreams[audioNodeId]) {
this.privStreams[audioNodeId].close();
delete this.privStreams[audioNodeId];
this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
}
}
turnOff() {
for (const streamId in this.privStreams) {
if (streamId) {
const stream = this.privStreams[streamId];
if (stream && !stream.isClosed) {
stream.close();
}
}
}
this.onEvent(new Exports_js_2.AudioSourceOffEvent(this.privId));
return Promise.resolve();
}
get events() {
return this.privEvents;
}
get deviceInfo() {
return this.privAudioFormatPromise.then((result) => Promise.resolve({
bitspersample: result.bitsPerSample,
channelcount: result.channels,
connectivity: Exports_js_1.connectivity.Unknown,
manufacturer: "Speech SDK",
model: "File",
samplerate: result.samplesPerSec,
type: Exports_js_1.type.File
}));
}
readHeader() {
const maxHeaderSize = 4296;
const header = this.privSource.slice(0, maxHeaderSize);
const headerResult = new Exports_js_2.Deferred();
const processHeader = (header2) => {
const view = new DataView(header2);
const getWord = (index) => String.fromCharCode(view.getUint8(index), view.getUint8(index + 1), view.getUint8(index + 2), view.getUint8(index + 3));
if ("RIFF" !== getWord(0)) {
headerResult.reject("Invalid WAV header in file, RIFF was not found");
return;
}
if ("WAVE" !== getWord(8) || "fmt " !== getWord(12)) {
headerResult.reject("Invalid WAV header in file, WAVEfmt was not found");
return;
}
const formatSize = view.getInt32(16, true);
const channelCount = view.getUint16(22, true);
const sampleRate = view.getUint32(24, true);
const bitsPerSample = view.getUint16(34, true);
let 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_js_1.AudioStreamFormat.getWaveFormatPCM(sampleRate, bitsPerSample, channelCount));
};
if (typeof window !== "undefined" && typeof Blob !== "undefined" && header instanceof Blob) {
const reader = new FileReader();
reader.onload = (event) => {
const header2 = event.target.result;
processHeader(header2);
};
reader.readAsArrayBuffer(header);
} else {
const h = header;
processHeader(h.buffer.slice(h.byteOffset, h.byteOffset + h.byteLength));
}
return headerResult.promise;
}
async upload(audioNodeId) {
const onerror = (error) => {
const errorMsg = `Error occurred while processing '${this.privFilename}'. ${error}`;
this.onEvent(new Exports_js_2.AudioStreamNodeErrorEvent(this.privId, audioNodeId, errorMsg));
throw new Error(errorMsg);
};
try {
await this.turnOn();
const format2 = await this.privAudioFormatPromise;
const stream = new Exports_js_2.ChunkedArrayBufferStream(format2.avgBytesPerSec / 10, audioNodeId);
this.privStreams[audioNodeId] = stream;
const chunk = this.privSource.slice(this.privHeaderEnd);
const processFile = (buff) => {
if (stream.isClosed) {
return;
}
stream.writeStreamChunk({
buffer: buff,
isEnd: false,
timeReceived: Date.now()
});
stream.close();
};
if (typeof window !== "undefined" && typeof Blob !== "undefined" && chunk instanceof Blob) {
const reader = new FileReader();
reader.onerror = (ev) => onerror(ev.toString());
reader.onload = (event) => {
const fileBuffer = event.target.result;
processFile(fileBuffer);
};
reader.readAsArrayBuffer(chunk);
} else {
const c = chunk;
processFile(c.buffer.slice(c.byteOffset, c.byteOffset + c.byteLength));
}
return stream;
} catch (e) {
onerror(e);
}
}
onEvent(event) {
this.privEvents.onEvent(event);
Exports_js_2.Events.instance.onEvent(event);
}
};
exports.FileAudioSource = FileAudioSource;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/PCMRecorder.js
var require_PCMRecorder = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/PCMRecorder.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PcmRecorder = void 0;
var Exports_1 = require_Exports();
var PcmRecorder = class {
constructor(stopInputOnRelease) {
this.privStopInputOnRelease = stopInputOnRelease;
}
record(context, mediaStream, outputStream) {
const desiredSampleRate = 16e3;
const waveStreamEncoder = new Exports_1.RiffPcmEncoder(context.sampleRate, desiredSampleRate);
const micInput = context.createMediaStreamSource(mediaStream);
const attachScriptProcessor = () => {
const scriptNode = (() => {
let bufferSize = 0;
try {
return context.createScriptProcessor(bufferSize, 1, 1);
} catch (error) {
bufferSize = 2048;
let audioSampleRate = context.sampleRate;
while (bufferSize < 16384 && audioSampleRate >= 2 * desiredSampleRate) {
bufferSize <<= 1;
audioSampleRate >>= 1;
}
return context.createScriptProcessor(bufferSize, 1, 1);
}
})();
scriptNode.onaudioprocess = (event) => {
const inputFrame = event.inputBuffer.getChannelData(0);
if (outputStream && !outputStream.isClosed) {
const waveFrame = waveStreamEncoder.encode(inputFrame);
if (!!waveFrame) {
outputStream.writeStreamChunk({
buffer: waveFrame,
isEnd: false,
timeReceived: Date.now()
});
}
}
};
micInput.connect(scriptNode);
scriptNode.connect(context.destination);
this.privMediaResources = {
scriptProcessorNode: scriptNode,
source: micInput,
stream: mediaStream
};
};
const skipAudioWorklet = !!this.privSpeechProcessorScript && this.privSpeechProcessorScript.toLowerCase() === "ignore";
if (!!context.audioWorklet && !skipAudioWorklet) {
if (!this.privSpeechProcessorScript) {
const workletScript = `class SP extends AudioWorkletProcessor {
constructor(options) {
super(options);
}
process(inputs, outputs) {
const input = inputs[0];
const output = [];
for (let channel = 0; channel < input.length; channel += 1) {
output[channel] = input[channel];
}
this.port.postMessage(output[0]);
return true;
}
}
registerProcessor('speech-processor', SP);`;
const blob = new Blob([workletScript], { type: "application/javascript; charset=utf-8" });
this.privSpeechProcessorScript = URL.createObjectURL(blob);
}
context.audioWorklet.addModule(this.privSpeechProcessorScript).then(() => {
const workletNode = new AudioWorkletNode(context, "speech-processor");
workletNode.port.onmessage = (ev) => {
const inputFrame = ev.data;
if (outputStream && !outputStream.isClosed) {
const waveFrame = waveStreamEncoder.encode(inputFrame);
if (!!waveFrame) {
outputStream.writeStreamChunk({
buffer: waveFrame,
isEnd: false,
timeReceived: Date.now()
});
}
}
};
micInput.connect(workletNode);
workletNode.connect(context.destination);
this.privMediaResources = {
scriptProcessorNode: workletNode,
source: micInput,
stream: mediaStream
};
}).catch(() => {
attachScriptProcessor();
});
} else {
try {
attachScriptProcessor();
} catch (err) {
throw new Error(`Unable to start audio worklet node for PCMRecorder: ${err}`);
}
}
}
releaseMediaResources(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((track) => track.stop());
}
this.privMediaResources.source = null;
}
}
}
setWorkletUrl(url) {
this.privSpeechProcessorScript = url;
}
};
exports.PcmRecorder = PcmRecorder;
}
});
// (disabled):net
var require_net = __commonJS({
"(disabled):net"() {
}
});
// (disabled):tls
var require_tls = __commonJS({
"(disabled):tls"() {
}
});
// (disabled):../../node_modules/agent-base/dist/src/index.js
var require_src = __commonJS({
"(disabled):../../node_modules/agent-base/dist/src/index.js"() {
}
});
// (disabled):../../node_modules/microsoft-cognitiveservices-speech-sdk/node_modules/https-proxy-agent/index.js
var require_https_proxy_agent = __commonJS({
"(disabled):../../node_modules/microsoft-cognitiveservices-speech-sdk/node_modules/https-proxy-agent/index.js"() {
}
});
// (disabled):../../node_modules/ws/browser.js
var require_browser = __commonJS({
"(disabled):../../node_modules/ws/browser.js"() {
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/WebsocketMessageAdapter.js
var require_WebsocketMessageAdapter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/WebsocketMessageAdapter.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() {
return m[k];
} });
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __importDefault = exports && exports.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebsocketMessageAdapter = void 0;
var net = __importStar(require_net());
var tls = __importStar(require_tls());
var agent_base_1 = __importDefault(require_src());
var https_proxy_agent_1 = __importDefault(require_https_proxy_agent());
var ws_1 = __importDefault(require_browser());
var HeaderNames_js_1 = require_HeaderNames();
var Exports_js_1 = require_Exports();
var WebsocketMessageAdapter = class _WebsocketMessageAdapter {
constructor(uri, connectionId, messageFormatter, proxyInfo, headers, enableCompression) {
if (!uri) {
throw new Exports_js_1.ArgumentNullError("uri");
}
if (!messageFormatter) {
throw new Exports_js_1.ArgumentNullError("messageFormatter");
}
this.proxyInfo = proxyInfo;
this.privConnectionEvents = new Exports_js_1.EventSource();
this.privConnectionId = connectionId;
this.privMessageFormatter = messageFormatter;
this.privConnectionState = Exports_js_1.ConnectionState.None;
this.privUri = uri;
this.privHeaders = headers;
this.privEnableCompression = enableCompression;
this.privHeaders[HeaderNames_js_1.HeaderNames.ConnectionId] = this.privConnectionId;
this.privHeaders.connectionId = this.privConnectionId;
this.privLastErrorReceived = "";
}
get state() {
return this.privConnectionState;
}
open() {
if (this.privConnectionState === Exports_js_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_js_1.Deferred();
this.privCertificateValidatedDeferral = new Exports_js_1.Deferred();
this.privConnectionState = Exports_js_1.ConnectionState.Connecting;
try {
if (typeof WebSocket !== "undefined" && !_WebsocketMessageAdapter.forceNpmWebSocket) {
this.privCertificateValidatedDeferral.resolve();
this.privWebsocketClient = new WebSocket(this.privUri);
} else {
const uri = new URL(this.privUri);
let protocol = uri.protocol;
if (protocol?.toLocaleLowerCase() === "wss:") {
protocol = "https:";
} else if (protocol?.toLocaleLowerCase() === "ws:") {
protocol = "http:";
}
const options = { headers: this.privHeaders, perMessageDeflate: this.privEnableCompression, followRedirects: protocol.toLocaleLowerCase() === "https:" };
this.privCertificateValidatedDeferral.resolve();
options.agent = this.getAgent();
options.agent.protocol = protocol;
this.privWebsocketClient = new ws_1.default(this.privUri, options);
this.privWebsocketClient.on("redirect", (redirectUrl) => {
const event = new Exports_js_1.ConnectionRedirectEvent(this.privConnectionId, redirectUrl, this.privUri, `Getting redirect URL from endpoint ${this.privUri} with redirect URL '${redirectUrl}'`);
Exports_js_1.Events.instance.onEvent(event);
});
}
this.privWebsocketClient.binaryType = "arraybuffer";
this.privReceivingMessageQueue = new Exports_js_1.Queue();
this.privDisconnectDeferral = new Exports_js_1.Deferred();
this.privSendMessageQueue = new Exports_js_1.Queue();
this.processSendQueue().catch((reason) => {
Exports_js_1.Events.instance.onEvent(new Exports_js_1.BackgroundEvent(reason));
});
} catch (error) {
this.privConnectionEstablishDeferral.resolve(new Exports_js_1.ConnectionOpenResponse(500, error));
return this.privConnectionEstablishDeferral.promise;
}
this.onEvent(new Exports_js_1.ConnectionStartEvent(this.privConnectionId, this.privUri));
this.privWebsocketClient.onopen = () => {
this.privCertificateValidatedDeferral.promise.then(() => {
this.privConnectionState = Exports_js_1.ConnectionState.Connected;
this.onEvent(new Exports_js_1.ConnectionEstablishedEvent(this.privConnectionId));
this.privConnectionEstablishDeferral.resolve(new Exports_js_1.ConnectionOpenResponse(200, ""));
}, (error) => {
this.privConnectionEstablishDeferral.reject(error);
});
};
this.privWebsocketClient.onerror = (e) => {
this.onEvent(new Exports_js_1.ConnectionErrorEvent(this.privConnectionId, e.message, e.type));
this.privLastErrorReceived = e.message;
};
this.privWebsocketClient.onclose = (e) => {
if (this.privConnectionState === Exports_js_1.ConnectionState.Connecting) {
this.privConnectionState = Exports_js_1.ConnectionState.Disconnected;
this.privConnectionEstablishDeferral.resolve(new Exports_js_1.ConnectionOpenResponse(e.code, e.reason + " " + this.privLastErrorReceived));
} else {
this.privConnectionState = Exports_js_1.ConnectionState.Disconnected;
this.privWebsocketClient = null;
this.onEvent(new Exports_js_1.ConnectionClosedEvent(this.privConnectionId, e.code, e.reason));
}
this.onClose(e.code, e.reason).catch((reason) => {
Exports_js_1.Events.instance.onEvent(new Exports_js_1.BackgroundEvent(reason));
});
};
this.privWebsocketClient.onmessage = (e) => {
const networkReceivedTime = (/* @__PURE__ */ new Date()).toISOString();
if (this.privConnectionState === Exports_js_1.ConnectionState.Connected) {
const deferred = new Exports_js_1.Deferred();
this.privReceivingMessageQueue.enqueueFromPromise(deferred.promise);
if (e.data instanceof ArrayBuffer) {
const rawMessage = new Exports_js_1.RawWebsocketMessage(Exports_js_1.MessageType.Binary, e.data);
this.privMessageFormatter.toConnectionMessage(rawMessage).then((connectionMessage) => {
this.onEvent(new Exports_js_1.ConnectionMessageReceivedEvent(this.privConnectionId, networkReceivedTime, connectionMessage));
deferred.resolve(connectionMessage);
}, (error) => {
deferred.reject(`Invalid binary message format. Error: ${error}`);
});
} else {
const rawMessage = new Exports_js_1.RawWebsocketMessage(Exports_js_1.MessageType.Text, e.data);
this.privMessageFormatter.toConnectionMessage(rawMessage).then((connectionMessage) => {
this.onEvent(new Exports_js_1.ConnectionMessageReceivedEvent(this.privConnectionId, networkReceivedTime, connectionMessage));
deferred.resolve(connectionMessage);
}, (error) => {
deferred.reject(`Invalid text message format. Error: ${error}`);
});
}
}
};
return this.privConnectionEstablishDeferral.promise;
}
send(message) {
if (this.privConnectionState !== Exports_js_1.ConnectionState.Connected) {
return Promise.reject(`Cannot send on connection that is in ${Exports_js_1.ConnectionState[this.privConnectionState]} state`);
}
const messageSendStatusDeferral = new Exports_js_1.Deferred();
const messageSendDeferral = new Exports_js_1.Deferred();
this.privSendMessageQueue.enqueueFromPromise(messageSendDeferral.promise);
this.privMessageFormatter.fromConnectionMessage(message).then((rawMessage) => {
messageSendDeferral.resolve({
Message: message,
RawWebsocketMessage: rawMessage,
sendStatusDeferral: messageSendStatusDeferral
});
}, (error) => {
messageSendDeferral.reject(`Error formatting the message. ${error}`);
});
return messageSendStatusDeferral.promise;
}
read() {
if (this.privConnectionState !== Exports_js_1.ConnectionState.Connected) {
return Promise.reject(`Cannot read on connection that is in ${this.privConnectionState} state`);
}
return this.privReceivingMessageQueue.dequeue();
}
close(reason) {
if (this.privWebsocketClient) {
if (this.privConnectionState !== Exports_js_1.ConnectionState.Disconnected) {
this.privWebsocketClient.close(1e3, reason ? reason : "Normal closure by client");
}
} else {
return Promise.resolve();
}
return this.privDisconnectDeferral.promise;
}
get events() {
return this.privConnectionEvents;
}
sendRawMessage(sendItem) {
try {
if (!sendItem) {
return Promise.resolve();
}
this.onEvent(new Exports_js_1.ConnectionMessageSentEvent(this.privConnectionId, (/* @__PURE__ */ new Date()).toISOString(), sendItem.Message));
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}`);
}
}
async onClose(code, reason) {
const closeReason = `Connection closed. ${code}: ${reason}`;
this.privConnectionState = Exports_js_1.ConnectionState.Disconnected;
this.privDisconnectDeferral.resolve();
await this.privReceivingMessageQueue.drainAndDispose(() => {
}, closeReason);
await this.privSendMessageQueue.drainAndDispose((pendingSendItem) => {
pendingSendItem.sendStatusDeferral.reject(closeReason);
}, closeReason);
}
async processSendQueue() {
while (true) {
const itemToSend = this.privSendMessageQueue.dequeue();
const sendItem = await itemToSend;
if (!sendItem) {
return;
}
try {
await this.sendRawMessage(sendItem);
sendItem.sendStatusDeferral.resolve();
} catch (sendError) {
sendItem.sendStatusDeferral.reject(sendError);
}
}
}
onEvent(event) {
this.privConnectionEvents.onEvent(event);
Exports_js_1.Events.instance.onEvent(event);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getAgent() {
const agent = new agent_base_1.default.Agent(this.createConnection);
if (this.proxyInfo !== void 0 && this.proxyInfo.HostName !== void 0 && this.proxyInfo.Port > 0) {
agent.proxyInfo = this.proxyInfo;
}
return agent;
}
static GetProxyAgent(proxyInfo) {
const httpProxyOptions = {
host: proxyInfo.HostName,
port: proxyInfo.Port
};
if (!!proxyInfo.UserName) {
httpProxyOptions.headers = {
"Proxy-Authentication": "Basic " + Buffer.from(`${proxyInfo.UserName}:${proxyInfo.Password === void 0 ? "" : proxyInfo.Password}`).toString("base64")
};
} else {
httpProxyOptions.headers = {};
}
httpProxyOptions.headers.requestOCSP = "true";
const httpProxyAgent = new https_proxy_agent_1.default(httpProxyOptions);
return httpProxyAgent;
}
createConnection(request, options) {
let socketPromise;
options = {
...options,
...{
requestOCSP: true,
servername: options.host
}
};
if (!!this.proxyInfo) {
const httpProxyAgent = _WebsocketMessageAdapter.GetProxyAgent(this.proxyInfo);
const baseAgent = httpProxyAgent;
socketPromise = new Promise((resolve, reject) => {
baseAgent.callback(request, options, (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));
}
}
return socketPromise;
}
get isWebsocketOpen() {
return this.privWebsocketClient && this.privWebsocketClient.readyState === this.privWebsocketClient.OPEN;
}
};
exports.WebsocketMessageAdapter = WebsocketMessageAdapter;
WebsocketMessageAdapter.forceNpmWebSocket = false;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/WebsocketConnection.js
var require_WebsocketConnection = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/WebsocketConnection.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebsocketConnection = void 0;
var Exports_js_1 = require_Exports();
var WebsocketMessageAdapter_js_1 = require_WebsocketMessageAdapter();
var WebsocketConnection = class {
constructor(uri, queryParameters, headers, messageFormatter, proxyInfo, enableCompression = false, connectionId) {
this.privIsDisposed = false;
if (!uri) {
throw new Exports_js_1.ArgumentNullError("uri");
}
if (!messageFormatter) {
throw new Exports_js_1.ArgumentNullError("messageFormatter");
}
this.privMessageFormatter = messageFormatter;
let queryParams = "";
let i = 0;
if (queryParameters) {
for (const paramName in queryParameters) {
if (paramName) {
queryParams += i === 0 && uri.indexOf("?") === -1 ? "?" : "&";
const key = encodeURIComponent(paramName);
queryParams += key;
let val = queryParameters[paramName];
if (val) {
val = encodeURIComponent(val);
queryParams += `=${val}`;
}
i++;
}
}
}
if (headers) {
for (const headerName in headers) {
if (headerName) {
queryParams += i === 0 && uri.indexOf("?") === -1 ? "?" : "&";
const val = encodeURIComponent(headers[headerName]);
queryParams += `${headerName}=${val}`;
i++;
}
}
}
this.privUri = uri + queryParams;
this.privId = connectionId ? connectionId : (0, Exports_js_1.createNoDashGuid)();
this.privConnectionMessageAdapter = new WebsocketMessageAdapter_js_1.WebsocketMessageAdapter(this.privUri, this.id, this.privMessageFormatter, proxyInfo, headers, enableCompression);
}
async dispose() {
this.privIsDisposed = true;
if (this.privConnectionMessageAdapter) {
await this.privConnectionMessageAdapter.close();
}
}
isDisposed() {
return this.privIsDisposed;
}
get id() {
return this.privId;
}
get uri() {
return this.privUri;
}
state() {
return this.privConnectionMessageAdapter.state;
}
open() {
return this.privConnectionMessageAdapter.open();
}
send(message) {
return this.privConnectionMessageAdapter.send(message);
}
read() {
return this.privConnectionMessageAdapter.read();
}
get events() {
return this.privConnectionMessageAdapter.events;
}
};
exports.WebsocketConnection = WebsocketConnection;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/ReplayableAudioNode.js
var require_ReplayableAudioNode = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/ReplayableAudioNode.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReplayableAudioNode = void 0;
var ReplayableAudioNode = class {
constructor(audioSource, bytesPerSecond) {
this.privBuffers = [];
this.privReplayOffset = 0;
this.privLastShrinkOffset = 0;
this.privBufferStartOffset = 0;
this.privBufferSerial = 0;
this.privBufferedBytes = 0;
this.privReplay = false;
this.privLastChunkAcquiredTime = 0;
this.privAudioNode = audioSource;
this.privBytesPerSecond = bytesPerSecond;
}
id() {
return this.privAudioNode.id();
}
// 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.
read() {
if (!!this.privReplay && this.privBuffers.length !== 0) {
const offsetToSeek = this.privReplayOffset - this.privBufferStartOffset;
let bytesToSeek = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7);
if (0 !== bytesToSeek % 2) {
bytesToSeek++;
}
let 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) {
const retVal = this.privBuffers[i].chunk.buffer.slice(bytesToSeek);
this.privReplayOffset += retVal.byteLength / this.privBytesPerSecond * 1e7;
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((result) => {
if (result && result.buffer && this.privBuffers) {
this.privBuffers.push(new BufferEntry(result, this.privBufferSerial++, this.privBufferedBytes));
this.privBufferedBytes += result.buffer.byteLength;
}
return result;
});
}
detach() {
this.privBuffers = void 0;
return this.privAudioNode.detach();
}
replay() {
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.
shrinkBuffers(offset) {
if (this.privBuffers === void 0 || this.privBuffers.length === 0) {
return;
}
this.privLastShrinkOffset = offset;
const offsetToSeek = offset - this.privBufferStartOffset;
let bytesToSeek = Math.round(offsetToSeek * this.privBytesPerSecond * 1e-7);
let 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 * 1e7);
this.privBuffers = this.privBuffers.slice(i);
}
// Finds the time a buffer of audio was first seen by offset.
findTimeAtOffset(offset) {
if (offset < this.privBufferStartOffset || this.privBuffers === void 0) {
return 0;
}
for (const value of this.privBuffers) {
const startOffset = value.byteOffset / this.privBytesPerSecond * 1e7;
const endOffset = startOffset + value.chunk.buffer.byteLength / this.privBytesPerSecond * 1e7;
if (offset >= startOffset && offset <= endOffset) {
return value.chunk.timeReceived;
}
}
return 0;
}
};
exports.ReplayableAudioNode = ReplayableAudioNode;
var BufferEntry = class {
constructor(chunk, serial, byteOffset) {
this.chunk = chunk;
this.serial = serial;
this.byteOffset = byteOffset;
}
};
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioFileWriter.js
var require_AudioFileWriter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioFileWriter.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() {
return m[k];
} });
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.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(require_fs());
var Contracts_js_1 = require_Contracts();
var AudioFileWriter = class {
constructor(filename) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(fs.openSync, "\nFile System access not available, please use Push or PullAudioOutputStream");
this.privFd = fs.openSync(filename, "w");
}
set format(format2) {
Contracts_js_1.Contracts.throwIfNotUndefined(this.privAudioFormat, "format is already set");
this.privAudioFormat = format2;
let headerOffset = 0;
if (this.privAudioFormat.hasHeader) {
headerOffset = this.privAudioFormat.header.byteLength;
}
if (this.privFd !== void 0) {
this.privWriteStream = fs.createWriteStream("", { fd: this.privFd, start: headerOffset, autoClose: false });
}
}
write(buffer) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privAudioFormat, "must set format before writing.");
if (this.privWriteStream !== void 0) {
this.privWriteStream.write(new Uint8Array(buffer.slice(0)));
}
}
close() {
if (this.privFd !== void 0) {
this.privWriteStream.on("finish", () => {
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 = void 0;
});
this.privWriteStream.end();
}
}
id() {
return this.privId;
}
};
exports.AudioFileWriter = AudioFileWriter;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioInputStream.js
var require_AudioInputStream = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioInputStream.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PullAudioInputStreamImpl = exports.PullAudioInputStream = exports.PushAudioInputStreamImpl = exports.PushAudioInputStream = exports.AudioInputStream = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var Guid_js_1 = require_Guid();
var Exports_js_3 = require_Exports3();
var AudioStreamFormat_js_1 = require_AudioStreamFormat();
var AudioInputStream = class {
/**
* Creates and initializes an instance.
* @constructor
*/
constructor() {
return;
}
/**
* 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.
*/
static createPushStream(format2) {
return PushAudioInputStream.create(format2);
}
/**
* 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.
*/
static createPullStream(callback, format2) {
return PullAudioInputStream.create(callback, format2);
}
};
exports.AudioInputStream = AudioInputStream;
var PushAudioInputStream = class extends AudioInputStream {
/**
* 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.
*/
static create(format2) {
return new PushAudioInputStreamImpl(format2);
}
};
exports.PushAudioInputStream = PushAudioInputStream;
var PushAudioInputStreamImpl = class extends PushAudioInputStream {
/**
* Creates and initalizes an instance with the given values.
* @constructor
* @param {AudioStreamFormat} format - The audio stream format.
*/
constructor(format2) {
super();
if (format2 === void 0) {
this.privFormat = AudioStreamFormat_js_1.AudioStreamFormatImpl.getDefaultInputFormat();
} else {
this.privFormat = format2;
}
this.privEvents = new Exports_js_2.EventSource();
this.privId = (0, Guid_js_1.createNoDashGuid)();
this.privStream = new Exports_js_2.ChunkedArrayBufferStream(this.privFormat.avgBytesPerSec / 10);
}
/**
* Format information for the audio
*/
get format() {
return Promise.resolve(this.privFormat);
}
/**
* 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.
*/
write(dataBuffer) {
this.privStream.writeStreamChunk({
buffer: dataBuffer,
isEnd: false,
timeReceived: Date.now()
});
}
/**
* Closes the stream.
* @member PushAudioInputStreamImpl.prototype.close
* @function
* @public
*/
close() {
this.privStream.close();
}
id() {
return this.privId;
}
turnOn() {
this.onEvent(new Exports_js_2.AudioSourceInitializingEvent(this.privId));
this.onEvent(new Exports_js_2.AudioSourceReadyEvent(this.privId));
return;
}
async attach(audioNodeId) {
this.onEvent(new Exports_js_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId));
await this.turnOn();
const stream = this.privStream;
this.onEvent(new Exports_js_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId));
return {
detach: async () => {
this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
return this.turnOff();
},
id: () => audioNodeId,
read: () => stream.read()
};
}
detach(audioNodeId) {
this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
}
turnOff() {
return;
}
get events() {
return this.privEvents;
}
get deviceInfo() {
return Promise.resolve({
bitspersample: this.privFormat.bitsPerSample,
channelcount: this.privFormat.channels,
connectivity: Exports_js_1.connectivity.Unknown,
manufacturer: "Speech SDK",
model: "PushStream",
samplerate: this.privFormat.samplesPerSec,
type: Exports_js_1.type.Stream
});
}
onEvent(event) {
this.privEvents.onEvent(event);
Exports_js_2.Events.instance.onEvent(event);
}
toBuffer(arrayBuffer) {
const buf = Buffer.alloc(arrayBuffer.byteLength);
const view = new Uint8Array(arrayBuffer);
for (let i = 0; i < buf.length; ++i) {
buf[i] = view[i];
}
return buf;
}
};
exports.PushAudioInputStreamImpl = PushAudioInputStreamImpl;
var PullAudioInputStream = class extends AudioInputStream {
/**
* Creates and initializes and instance.
* @constructor
*/
constructor() {
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).
* @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.
*/
static create(callback, format2) {
return new PullAudioInputStreamImpl(callback, format2);
}
};
exports.PullAudioInputStream = PullAudioInputStream;
var PullAudioInputStreamImpl = class extends PullAudioInputStream {
/**
* 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).
*/
constructor(callback, format2) {
super();
if (void 0 === format2) {
this.privFormat = Exports_js_3.AudioStreamFormat.getDefaultInputFormat();
} else {
this.privFormat = format2;
}
this.privEvents = new Exports_js_2.EventSource();
this.privId = (0, Guid_js_1.createNoDashGuid)();
this.privCallback = callback;
this.privIsClosed = false;
this.privBufferSize = this.privFormat.avgBytesPerSec / 10;
}
/**
* Format information for the audio
*/
get format() {
return Promise.resolve(this.privFormat);
}
/**
* Closes the stream.
* @member PullAudioInputStreamImpl.prototype.close
* @function
* @public
*/
close() {
this.privIsClosed = true;
this.privCallback.close();
}
id() {
return this.privId;
}
turnOn() {
this.onEvent(new Exports_js_2.AudioSourceInitializingEvent(this.privId));
this.onEvent(new Exports_js_2.AudioSourceReadyEvent(this.privId));
return;
}
async attach(audioNodeId) {
this.onEvent(new Exports_js_2.AudioStreamNodeAttachingEvent(this.privId, audioNodeId));
await this.turnOn();
this.onEvent(new Exports_js_2.AudioStreamNodeAttachedEvent(this.privId, audioNodeId));
return {
detach: () => {
this.privCallback.close();
this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
return this.turnOff();
},
id: () => audioNodeId,
read: () => {
let totalBytes = 0;
let transmitBuff;
while (totalBytes < this.privBufferSize) {
const readBuff = new ArrayBuffer(this.privBufferSize - totalBytes);
const pulledBytes = this.privCallback.read(readBuff);
if (void 0 === transmitBuff) {
transmitBuff = readBuff;
} else {
const intView = new Int8Array(transmitBuff);
intView.set(new Int8Array(readBuff), totalBytes);
}
if (0 === pulledBytes) {
break;
}
totalBytes += pulledBytes;
}
return Promise.resolve({
buffer: transmitBuff.slice(0, totalBytes),
isEnd: this.privIsClosed || totalBytes === 0,
timeReceived: Date.now()
});
}
};
}
detach(audioNodeId) {
this.onEvent(new Exports_js_2.AudioStreamNodeDetachedEvent(this.privId, audioNodeId));
}
turnOff() {
return;
}
get events() {
return this.privEvents;
}
get deviceInfo() {
return Promise.resolve({
bitspersample: this.privFormat.bitsPerSample,
channelcount: this.privFormat.channels,
connectivity: Exports_js_1.connectivity.Unknown,
manufacturer: "Speech SDK",
model: "PullStream",
samplerate: this.privFormat.samplesPerSec,
type: Exports_js_1.type.Stream
});
}
onEvent(event) {
this.privEvents.onEvent(event);
Exports_js_2.Events.instance.onEvent(event);
}
};
exports.PullAudioInputStreamImpl = PullAudioInputStreamImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisOutputFormat.js
var require_SpeechSynthesisOutputFormat = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisOutputFormat.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisOutputFormat = void 0;
var SpeechSynthesisOutputFormat;
(function(SpeechSynthesisOutputFormat2) {
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Raw8Khz8BitMonoMULaw"] = 0] = "Raw8Khz8BitMonoMULaw";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Riff16Khz16KbpsMonoSiren"] = 1] = "Riff16Khz16KbpsMonoSiren";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio16Khz16KbpsMonoSiren"] = 2] = "Audio16Khz16KbpsMonoSiren";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio16Khz32KBitRateMonoMp3"] = 3] = "Audio16Khz32KBitRateMonoMp3";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio16Khz128KBitRateMonoMp3"] = 4] = "Audio16Khz128KBitRateMonoMp3";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio16Khz64KBitRateMonoMp3"] = 5] = "Audio16Khz64KBitRateMonoMp3";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio24Khz48KBitRateMonoMp3"] = 6] = "Audio24Khz48KBitRateMonoMp3";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio24Khz96KBitRateMonoMp3"] = 7] = "Audio24Khz96KBitRateMonoMp3";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio24Khz160KBitRateMonoMp3"] = 8] = "Audio24Khz160KBitRateMonoMp3";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Raw16Khz16BitMonoTrueSilk"] = 9] = "Raw16Khz16BitMonoTrueSilk";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Riff16Khz16BitMonoPcm"] = 10] = "Riff16Khz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Riff8Khz16BitMonoPcm"] = 11] = "Riff8Khz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Riff24Khz16BitMonoPcm"] = 12] = "Riff24Khz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Riff8Khz8BitMonoMULaw"] = 13] = "Riff8Khz8BitMonoMULaw";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Raw16Khz16BitMonoPcm"] = 14] = "Raw16Khz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Raw24Khz16BitMonoPcm"] = 15] = "Raw24Khz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Raw8Khz16BitMonoPcm"] = 16] = "Raw8Khz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Ogg16Khz16BitMonoOpus"] = 17] = "Ogg16Khz16BitMonoOpus";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Ogg24Khz16BitMonoOpus"] = 18] = "Ogg24Khz16BitMonoOpus";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Raw48Khz16BitMonoPcm"] = 19] = "Raw48Khz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Riff48Khz16BitMonoPcm"] = 20] = "Riff48Khz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio48Khz96KBitRateMonoMp3"] = 21] = "Audio48Khz96KBitRateMonoMp3";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio48Khz192KBitRateMonoMp3"] = 22] = "Audio48Khz192KBitRateMonoMp3";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Ogg48Khz16BitMonoOpus"] = 23] = "Ogg48Khz16BitMonoOpus";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Webm16Khz16BitMonoOpus"] = 24] = "Webm16Khz16BitMonoOpus";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Webm24Khz16BitMonoOpus"] = 25] = "Webm24Khz16BitMonoOpus";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Raw24Khz16BitMonoTrueSilk"] = 26] = "Raw24Khz16BitMonoTrueSilk";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Raw8Khz8BitMonoALaw"] = 27] = "Raw8Khz8BitMonoALaw";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Riff8Khz8BitMonoALaw"] = 28] = "Riff8Khz8BitMonoALaw";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Webm24Khz16Bit24KbpsMonoOpus"] = 29] = "Webm24Khz16Bit24KbpsMonoOpus";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio16Khz16Bit32KbpsMonoOpus"] = 30] = "Audio16Khz16Bit32KbpsMonoOpus";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio24Khz16Bit48KbpsMonoOpus"] = 31] = "Audio24Khz16Bit48KbpsMonoOpus";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Audio24Khz16Bit24KbpsMonoOpus"] = 32] = "Audio24Khz16Bit24KbpsMonoOpus";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Raw22050Hz16BitMonoPcm"] = 33] = "Raw22050Hz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Riff22050Hz16BitMonoPcm"] = 34] = "Riff22050Hz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Raw44100Hz16BitMonoPcm"] = 35] = "Raw44100Hz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["Riff44100Hz16BitMonoPcm"] = 36] = "Riff44100Hz16BitMonoPcm";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["AmrWb16000Hz"] = 37] = "AmrWb16000Hz";
SpeechSynthesisOutputFormat2[SpeechSynthesisOutputFormat2["G72216Khz64Kbps"] = 38] = "G72216Khz64Kbps";
})(SpeechSynthesisOutputFormat = exports.SpeechSynthesisOutputFormat || (exports.SpeechSynthesisOutputFormat = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioOutputFormat.js
var require_AudioOutputFormat = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioOutputFormat.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AudioOutputFormatImpl = void 0;
var SpeechSynthesisOutputFormat_js_1 = require_SpeechSynthesisOutputFormat();
var AudioStreamFormat_js_1 = require_AudioStreamFormat();
var AudioOutputFormatImpl = class _AudioOutputFormatImpl extends AudioStreamFormat_js_1.AudioStreamFormatImpl {
/**
* 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.
*/
constructor(formatTag, channels, samplesPerSec, avgBytesPerSec, blockAlign, bitsPerSample, audioFormatString, requestAudioFormatString, hasHeader) {
super(samplesPerSec, bitsPerSample, channels, formatTag);
this.formatTag = formatTag;
this.avgBytesPerSec = avgBytesPerSec;
this.blockAlign = blockAlign;
this.priAudioFormatString = audioFormatString;
this.priRequestAudioFormatString = requestAudioFormatString;
this.priHasHeader = hasHeader;
}
static fromSpeechSynthesisOutputFormat(speechSynthesisOutputFormat) {
if (speechSynthesisOutputFormat === void 0) {
return _AudioOutputFormatImpl.getDefaultOutputFormat();
}
return _AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(_AudioOutputFormatImpl.SpeechSynthesisOutputFormatToString[speechSynthesisOutputFormat]);
}
static fromSpeechSynthesisOutputFormatString(speechSynthesisOutputFormatString) {
switch (speechSynthesisOutputFormatString) {
case "raw-8khz-8bit-mono-mulaw":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MuLaw, 1, 8e3, 8e3, 1, 8, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "riff-16khz-16kbps-mono-siren":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.Siren, 1, 16e3, 2e3, 40, 0, speechSynthesisOutputFormatString, "audio-16khz-16kbps-mono-siren", true);
case "audio-16khz-16kbps-mono-siren":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.Siren, 1, 16e3, 2e3, 40, 0, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-16khz-32kbitrate-mono-mp3":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 16e3, 32 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-16khz-128kbitrate-mono-mp3":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 16e3, 128 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-16khz-64kbitrate-mono-mp3":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 16e3, 64 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-24khz-48kbitrate-mono-mp3":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 24e3, 48 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-24khz-96kbitrate-mono-mp3":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 24e3, 96 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-24khz-160kbitrate-mono-mp3":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 24e3, 160 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "raw-16khz-16bit-mono-truesilk":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.SILKSkype, 1, 16e3, 32e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "riff-8khz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 8e3, 16e3, 2, 16, speechSynthesisOutputFormatString, "raw-8khz-16bit-mono-pcm", true);
case "riff-24khz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 24e3, 48e3, 2, 16, speechSynthesisOutputFormatString, "raw-24khz-16bit-mono-pcm", true);
case "riff-8khz-8bit-mono-mulaw":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MuLaw, 1, 8e3, 8e3, 1, 8, speechSynthesisOutputFormatString, "raw-8khz-8bit-mono-mulaw", true);
case "raw-16khz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 16e3, 32e3, 2, 16, speechSynthesisOutputFormatString, "raw-16khz-16bit-mono-pcm", false);
case "raw-24khz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 24e3, 48e3, 2, 16, speechSynthesisOutputFormatString, "raw-24khz-16bit-mono-pcm", false);
case "raw-8khz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 8e3, 16e3, 2, 16, speechSynthesisOutputFormatString, "raw-8khz-16bit-mono-pcm", false);
case "ogg-16khz-16bit-mono-opus":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OGG_OPUS, 1, 16e3, 8192, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "ogg-24khz-16bit-mono-opus":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OGG_OPUS, 1, 24e3, 8192, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "raw-48khz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 48e3, 96e3, 2, 16, speechSynthesisOutputFormatString, "raw-48khz-16bit-mono-pcm", false);
case "riff-48khz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 48e3, 96e3, 2, 16, speechSynthesisOutputFormatString, "raw-48khz-16bit-mono-pcm", true);
case "audio-48khz-96kbitrate-mono-mp3":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 48e3, 96 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-48khz-192kbitrate-mono-mp3":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.MP3, 1, 48e3, 192 << 7, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "ogg-48khz-16bit-mono-opus":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OGG_OPUS, 1, 48e3, 12e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "webm-16khz-16bit-mono-opus":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.WEBM_OPUS, 1, 16e3, 4e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "webm-24khz-16bit-mono-opus":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.WEBM_OPUS, 1, 24e3, 6e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "webm-24khz-16bit-24kbps-mono-opus":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.WEBM_OPUS, 1, 24e3, 3e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-16khz-16bit-32kbps-mono-opus":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OPUS, 1, 16e3, 4e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-24khz-16bit-48kbps-mono-opus":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OPUS, 1, 24e3, 6e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-24khz-16bit-24kbps-mono-opus":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.OPUS, 1, 24e3, 3e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-24khz-16bit-mono-flac":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.FLAC, 1, 24e3, 24e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "audio-48khz-16bit-mono-flac":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.FLAC, 1, 48e3, 3e4, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "raw-24khz-16bit-mono-truesilk":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.SILKSkype, 1, 24e3, 48e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "raw-8khz-8bit-mono-alaw":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.ALaw, 1, 8e3, 8e3, 1, 8, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "riff-8khz-8bit-mono-alaw":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.ALaw, 1, 8e3, 8e3, 1, 8, speechSynthesisOutputFormatString, "raw-8khz-8bit-mono-alaw", true);
case "raw-22050hz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 22050, 44100, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "riff-22050hz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 22050, 44100, 2, 16, speechSynthesisOutputFormatString, "raw-22050hz-16bit-mono-pcm", true);
case "raw-44100hz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 44100, 88200, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "riff-44100hz-16bit-mono-pcm":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 44100, 88200, 2, 16, speechSynthesisOutputFormatString, "raw-44100hz-16bit-mono-pcm", true);
case "amr-wb-16000h":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.AMR_WB, 1, 16e3, 3052, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "g722-16khz-64kbps":
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.G722, 1, 16e3, 8e3, 2, 16, speechSynthesisOutputFormatString, speechSynthesisOutputFormatString, false);
case "riff-16khz-16bit-mono-pcm":
default:
return new _AudioOutputFormatImpl(AudioStreamFormat_js_1.AudioFormatTag.PCM, 1, 16e3, 32e3, 2, 16, "riff-16khz-16bit-mono-pcm", "raw-16khz-16bit-mono-pcm", true);
}
}
static getDefaultOutputFormat() {
return _AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(typeof window !== "undefined" ? "audio-24khz-48kbitrate-mono-mp3" : "riff-16khz-16bit-mono-pcm");
}
/**
* Specifies if this audio output format has a header
* @boolean AudioOutputFormatImpl.prototype.hasHeader
* @function
* @public
*/
get hasHeader() {
return this.priHasHeader;
}
/**
* Specifies the header of this format
* @ArrayBuffer AudioOutputFormatImpl.prototype.header
* @function
* @public
*/
get header() {
if (this.hasHeader) {
return this.privHeader;
}
return void 0;
}
/**
* Updates the header based on the audio length
* @member AudioOutputFormatImpl.updateHeader
* @function
* @public
* @param {number} audioLength - the audio length
*/
updateHeader(audioLength) {
if (this.priHasHeader) {
const view = new DataView(this.privHeader);
view.setUint32(4, audioLength + this.privHeader.byteLength - 8, true);
view.setUint32(40, audioLength, true);
}
}
/**
* Specifies the audio format string to be sent to the service
* @string AudioOutputFormatImpl.prototype.requestAudioFormatString
* @function
* @public
*/
get requestAudioFormatString() {
return this.priRequestAudioFormatString;
}
/**
* Adds audio header
* @param audio the raw audio without header
* @returns the audio with header if applicable
*/
addHeader(audio) {
if (!this.hasHeader) {
return audio;
}
this.updateHeader(audio.byteLength);
const tmp = new Uint8Array(audio.byteLength + this.header.byteLength);
tmp.set(new Uint8Array(this.header), 0);
tmp.set(new Uint8Array(audio), this.header.byteLength);
return tmp.buffer;
}
};
exports.AudioOutputFormatImpl = AudioOutputFormatImpl;
AudioOutputFormatImpl.SpeechSynthesisOutputFormatToString = {
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoMULaw]: "raw-8khz-8bit-mono-mulaw",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff16Khz16KbpsMonoSiren]: "riff-16khz-16kbps-mono-siren",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio16Khz16KbpsMonoSiren]: "audio-16khz-16kbps-mono-siren",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio16Khz32KBitRateMonoMp3]: "audio-16khz-32kbitrate-mono-mp3",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio16Khz128KBitRateMonoMp3]: "audio-16khz-128kbitrate-mono-mp3",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio16Khz64KBitRateMonoMp3]: "audio-16khz-64kbitrate-mono-mp3",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio24Khz48KBitRateMonoMp3]: "audio-24khz-48kbitrate-mono-mp3",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio24Khz96KBitRateMonoMp3]: "audio-24khz-96kbitrate-mono-mp3",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3]: "audio-24khz-160kbitrate-mono-mp3",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoTrueSilk]: "raw-16khz-16bit-mono-truesilk",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff16Khz16BitMonoPcm]: "riff-16khz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff8Khz16BitMonoPcm]: "riff-8khz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm]: "riff-24khz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoMULaw]: "riff-8khz-8bit-mono-mulaw",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm]: "raw-16khz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoPcm]: "raw-24khz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw8Khz16BitMonoPcm]: "raw-8khz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Ogg16Khz16BitMonoOpus]: "ogg-16khz-16bit-mono-opus",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Ogg24Khz16BitMonoOpus]: "ogg-24khz-16bit-mono-opus",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw48Khz16BitMonoPcm]: "raw-48khz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff48Khz16BitMonoPcm]: "riff-48khz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio48Khz96KBitRateMonoMp3]: "audio-48khz-96kbitrate-mono-mp3",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3]: "audio-48khz-192kbitrate-mono-mp3",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Ogg48Khz16BitMonoOpus]: "ogg-48khz-16bit-mono-opus",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Webm16Khz16BitMonoOpus]: "webm-16khz-16bit-mono-opus",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Webm24Khz16BitMonoOpus]: "webm-24khz-16bit-mono-opus",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Webm24Khz16Bit24KbpsMonoOpus]: "webm-24khz-16bit-24kbps-mono-opus",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw24Khz16BitMonoTrueSilk]: "raw-24khz-16bit-mono-truesilk",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw8Khz8BitMonoALaw]: "raw-8khz-8bit-mono-alaw",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff8Khz8BitMonoALaw]: "riff-8khz-8bit-mono-alaw",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio16Khz16Bit32KbpsMonoOpus]: "audio-16khz-16bit-32kbps-mono-opus",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio24Khz16Bit48KbpsMonoOpus]: "audio-24khz-16bit-48kbps-mono-opus",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Audio24Khz16Bit24KbpsMonoOpus]: "audio-24khz-16bit-24kbps-mono-opus",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw22050Hz16BitMonoPcm]: "raw-22050hz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff22050Hz16BitMonoPcm]: "riff-22050hz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Raw44100Hz16BitMonoPcm]: "raw-44100hz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.Riff44100Hz16BitMonoPcm]: "riff-44100hz-16bit-mono-pcm",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.AmrWb16000Hz]: "amr-wb-16000hz",
[SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat.G72216Khz64Kbps]: "g722-16khz-64kbps"
};
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioOutputStream.js
var require_AudioOutputStream = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioOutputStream.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PushAudioOutputStreamImpl = exports.PushAudioOutputStream = exports.PullAudioOutputStreamImpl = exports.PullAudioOutputStream = exports.AudioOutputStream = void 0;
var Exports_js_1 = require_Exports();
var Contracts_js_1 = require_Contracts();
var AudioOutputFormat_js_1 = require_AudioOutputFormat();
var AudioOutputStream = class {
/**
* Creates and initializes an instance.
* @constructor
*/
constructor() {
return;
}
/**
* Creates a memory backed PullAudioOutputStream with the specified audio format.
* @member AudioOutputStream.createPullStream
* @function
* @public
* @returns {PullAudioOutputStream} The audio output stream being created.
*/
static createPullStream() {
return PullAudioOutputStream.create();
}
};
exports.AudioOutputStream = AudioOutputStream;
var PullAudioOutputStream = class extends AudioOutputStream {
/**
* Creates a memory backed PullAudioOutputStream with the specified audio format.
* @member PullAudioOutputStream.create
* @function
* @public
* @returns {PullAudioOutputStream} The push audio output stream being created.
*/
static create() {
return new PullAudioOutputStreamImpl();
}
};
exports.PullAudioOutputStream = PullAudioOutputStream;
var PullAudioOutputStreamImpl = class extends PullAudioOutputStream {
/**
* Creates and initializes an instance with the given values.
* @constructor
*/
constructor() {
super();
this.privId = (0, Exports_js_1.createNoDashGuid)();
this.privStream = new Exports_js_1.Stream();
}
/**
* Sets the format information to the stream. For internal use only.
* @param {AudioStreamFormat} format - the format to be set.
*/
set format(format2) {
if (format2 === void 0 || format2 === null) {
this.privFormat = AudioOutputFormat_js_1.AudioOutputFormatImpl.getDefaultOutputFormat();
}
this.privFormat = format2;
}
/**
* Format information for the audio
*/
get format() {
return this.privFormat;
}
/**
* Checks if the stream is closed
* @member PullAudioOutputStreamImpl.prototype.isClosed
* @property
* @public
*/
get isClosed() {
return this.privStream.isClosed;
}
/**
* Gets the id of the stream
* @member PullAudioOutputStreamImpl.prototype.id
* @property
* @public
*/
id() {
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.
*/
async read(dataBuffer) {
const intView = new Int8Array(dataBuffer);
let totalBytes = 0;
if (this.privLastChunkView !== void 0) {
if (this.privLastChunkView.length > dataBuffer.byteLength) {
intView.set(this.privLastChunkView.slice(0, dataBuffer.byteLength));
this.privLastChunkView = this.privLastChunkView.slice(dataBuffer.byteLength);
return Promise.resolve(dataBuffer.byteLength);
}
intView.set(this.privLastChunkView);
totalBytes = this.privLastChunkView.length;
this.privLastChunkView = void 0;
}
while (totalBytes < dataBuffer.byteLength && !this.privStream.isReadEnded) {
const chunk = await this.privStream.read();
if (chunk !== void 0 && !chunk.isEnd) {
let tmpBuffer;
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;
} else {
this.privStream.readEnded();
}
}
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.
*/
write(dataBuffer) {
Contracts_js_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
*/
close() {
this.privStream.close();
}
};
exports.PullAudioOutputStreamImpl = PullAudioOutputStreamImpl;
var PushAudioOutputStream = class extends AudioOutputStream {
/**
* Creates and initializes and instance.
* @constructor
*/
constructor() {
super();
}
/**
* 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.
*/
static create(callback) {
return new PushAudioOutputStreamImpl(callback);
}
};
exports.PushAudioOutputStream = PushAudioOutputStream;
var PushAudioOutputStreamImpl = class extends PushAudioOutputStream {
/**
* 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
*/
constructor(callback) {
super();
this.privId = (0, Exports_js_1.createNoDashGuid)();
this.privCallback = callback;
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
set format(format2) {
}
write(buffer) {
if (!!this.privCallback.write) {
this.privCallback.write(buffer);
}
}
close() {
if (!!this.privCallback.close) {
this.privCallback.close();
}
}
id() {
return this.privId;
}
};
exports.PushAudioOutputStreamImpl = PushAudioOutputStreamImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioConfig.js
var require_AudioConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/AudioConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AudioOutputConfigImpl = exports.AudioConfigImpl = exports.AudioConfig = void 0;
var Exports_js_1 = require_Exports4();
var Contracts_js_1 = require_Contracts();
var Exports_js_2 = require_Exports3();
var AudioFileWriter_js_1 = require_AudioFileWriter();
var AudioInputStream_js_1 = require_AudioInputStream();
var AudioOutputStream_js_1 = require_AudioOutputStream();
var AudioConfig3 = class _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.
*/
static fromDefaultMicrophoneInput() {
const pcmRecorder = new Exports_js_1.PcmRecorder(true);
return new AudioConfigImpl(new Exports_js_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.
*/
static fromMicrophoneInput(deviceId) {
const pcmRecorder = new Exports_js_1.PcmRecorder(true);
return new AudioConfigImpl(new Exports_js_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.
*/
static fromWavFileInput(file, name = "unnamedBuffer.wav") {
return new AudioConfigImpl(new Exports_js_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.
*/
static fromStreamInput(audioStream) {
if (audioStream instanceof Exports_js_2.PullAudioInputStreamCallback) {
return new AudioConfigImpl(new AudioInputStream_js_1.PullAudioInputStreamImpl(audioStream));
}
if (audioStream instanceof Exports_js_2.AudioInputStream) {
return new AudioConfigImpl(audioStream);
}
if (typeof MediaStream !== "undefined" && audioStream instanceof MediaStream) {
const pcmRecorder = new Exports_js_1.PcmRecorder(false);
return new AudioConfigImpl(new Exports_js_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
*/
static fromDefaultSpeakerOutput() {
return new AudioOutputConfigImpl(new Exports_js_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
*/
static fromSpeakerOutput(player) {
if (player === void 0) {
return _AudioConfig.fromDefaultSpeakerOutput();
}
if (player instanceof Exports_js_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
*/
static fromAudioFileOutput(filename) {
return new AudioOutputConfigImpl(new AudioFileWriter_js_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
*/
static fromStreamOutput(audioStream) {
if (audioStream instanceof Exports_js_2.PushAudioOutputStreamCallback) {
return new AudioOutputConfigImpl(new AudioOutputStream_js_1.PushAudioOutputStreamImpl(audioStream));
}
if (audioStream instanceof Exports_js_2.PushAudioOutputStream) {
return new AudioOutputConfigImpl(audioStream);
}
if (audioStream instanceof Exports_js_2.PullAudioOutputStream) {
return new AudioOutputConfigImpl(audioStream);
}
throw new Error("Not Supported Type");
}
};
exports.AudioConfig = AudioConfig3;
var AudioConfigImpl = class extends AudioConfig3 {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {IAudioSource} source - An audio source.
*/
constructor(source) {
super();
this.privSource = source;
}
/**
* Format information for the audio
*/
get format() {
return this.privSource.format;
}
/**
* @member AudioConfigImpl.prototype.close
* @function
* @public
*/
close(cb, err) {
this.privSource.turnOff().then(() => {
if (!!cb) {
cb();
}
}, (error) => {
if (!!err) {
err(error);
}
});
}
/**
* @member AudioConfigImpl.prototype.id
* @function
* @public
*/
id() {
return this.privSource.id();
}
/**
* @member AudioConfigImpl.prototype.turnOn
* @function
* @public
* @returns {Promise<void>} A promise.
*/
turnOn() {
return this.privSource.turnOn();
}
/**
* @member AudioConfigImpl.prototype.attach
* @function
* @public
* @param {string} audioNodeId - The audio node id.
* @returns {Promise<IAudioStreamNode>} A promise.
*/
attach(audioNodeId) {
return this.privSource.attach(audioNodeId);
}
/**
* @member AudioConfigImpl.prototype.detach
* @function
* @public
* @param {string} audioNodeId - The audio node id.
*/
detach(audioNodeId) {
return this.privSource.detach(audioNodeId);
}
/**
* @member AudioConfigImpl.prototype.turnOff
* @function
* @public
* @returns {Promise<void>} A promise.
*/
turnOff() {
return this.privSource.turnOff();
}
/**
* @member AudioConfigImpl.prototype.events
* @function
* @public
* @returns {EventSource<AudioSourceEvent>} An event source for audio events.
*/
get events() {
return this.privSource.events;
}
setProperty(name, value) {
Contracts_js_1.Contracts.throwIfNull(value, "value");
if (void 0 !== this.privSource.setProperty) {
this.privSource.setProperty(name, value);
} else {
throw new Error("This AudioConfig instance does not support setting properties.");
}
}
getProperty(name, def) {
if (void 0 !== this.privSource.getProperty) {
return this.privSource.getProperty(name, def);
} else {
throw new Error("This AudioConfig instance does not support getting properties.");
}
return def;
}
get deviceInfo() {
return this.privSource.deviceInfo;
}
};
exports.AudioConfigImpl = AudioConfigImpl;
var AudioOutputConfigImpl = class extends AudioConfig3 {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {IAudioDestination} destination - An audio destination.
*/
constructor(destination) {
super();
this.privDestination = destination;
}
set format(format2) {
this.privDestination.format = format2;
}
write(buffer) {
this.privDestination.write(buffer);
}
close() {
this.privDestination.close();
}
id() {
return this.privDestination.id();
}
setProperty() {
throw new Error("This AudioConfig instance does not support setting properties.");
}
getProperty() {
throw new Error("This AudioConfig instance does not support getting properties.");
}
};
exports.AudioOutputConfigImpl = AudioOutputConfigImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CancellationReason.js
var require_CancellationReason = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CancellationReason.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancellationReason = void 0;
var CancellationReason;
(function(CancellationReason2) {
CancellationReason2[CancellationReason2["Error"] = 0] = "Error";
CancellationReason2[CancellationReason2["EndOfStream"] = 1] = "EndOfStream";
})(CancellationReason = exports.CancellationReason || (exports.CancellationReason = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/PullAudioInputStreamCallback.js
var require_PullAudioInputStreamCallback = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/PullAudioInputStreamCallback.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PullAudioInputStreamCallback = void 0;
var PullAudioInputStreamCallback = class {
};
exports.PullAudioInputStreamCallback = PullAudioInputStreamCallback;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/PushAudioOutputStreamCallback.js
var require_PushAudioOutputStreamCallback = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/PushAudioOutputStreamCallback.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PushAudioOutputStreamCallback = void 0;
var PushAudioOutputStreamCallback = class {
};
exports.PushAudioOutputStreamCallback = PushAudioOutputStreamCallback;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/KeywordRecognitionModel.js
var require_KeywordRecognitionModel = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/KeywordRecognitionModel.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeywordRecognitionModel = void 0;
var Contracts_js_1 = require_Contracts();
var KeywordRecognitionModel = class {
/**
* Create and initializes a new instance.
* @constructor
*/
constructor() {
this.privDisposed = false;
return;
}
/**
* 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.
*/
static fromFile(fileName) {
Contracts_js_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.
*/
static fromStream(file) {
Contracts_js_1.Contracts.throwIfNull(file, "file");
throw new Error("Not yet implemented.");
}
/**
* Dispose of associated resources.
* @member KeywordRecognitionModel.prototype.close
* @function
* @public
*/
close() {
if (this.privDisposed) {
return;
}
this.privDisposed = true;
}
};
exports.KeywordRecognitionModel = KeywordRecognitionModel;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SessionEventArgs.js
var require_SessionEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SessionEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionEventArgs = void 0;
var SessionEventArgs = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {string} sessionId - The session id.
*/
constructor(sessionId) {
this.privSessionId = sessionId;
}
/**
* Represents the session identifier.
* @member SessionEventArgs.prototype.sessionId
* @function
* @public
* @returns {string} Represents the session identifier.
*/
get sessionId() {
return this.privSessionId;
}
};
exports.SessionEventArgs = SessionEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/RecognitionEventArgs.js
var require_RecognitionEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/RecognitionEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecognitionEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var RecognitionEventArgs = class extends Exports_js_1.SessionEventArgs {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {number} offset - The offset.
* @param {string} sessionId - The session id.
*/
constructor(offset, sessionId) {
super(sessionId);
this.privOffset = offset;
}
/**
* Represents the message offset
* @member RecognitionEventArgs.prototype.offset
* @function
* @public
*/
get offset() {
return this.privOffset;
}
};
exports.RecognitionEventArgs = RecognitionEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/OutputFormat.js
var require_OutputFormat = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/OutputFormat.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OutputFormat = void 0;
var OutputFormat3;
(function(OutputFormat4) {
OutputFormat4[OutputFormat4["Simple"] = 0] = "Simple";
OutputFormat4[OutputFormat4["Detailed"] = 1] = "Detailed";
})(OutputFormat3 = exports.OutputFormat || (exports.OutputFormat = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/IntentRecognitionEventArgs.js
var require_IntentRecognitionEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/IntentRecognitionEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentRecognitionEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var IntentRecognitionEventArgs = class extends Exports_js_1.RecognitionEventArgs {
/**
* 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.
*/
constructor(result, offset, sessionId) {
super(offset, sessionId);
this.privResult = result;
}
/**
* Represents the intent recognition result.
* @member IntentRecognitionEventArgs.prototype.result
* @function
* @public
* @returns {IntentRecognitionResult} Represents the intent recognition result.
*/
get result() {
return this.privResult;
}
};
exports.IntentRecognitionEventArgs = IntentRecognitionEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/RecognitionResult.js
var require_RecognitionResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/RecognitionResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecognitionResult = void 0;
var RecognitionResult = class {
/**
* 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.
*/
constructor(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;
}
/**
* Specifies the result identifier.
* @member RecognitionResult.prototype.resultId
* @function
* @public
* @returns {string} Specifies the result identifier.
*/
get resultId() {
return this.privResultId;
}
/**
* Specifies status of the result.
* @member RecognitionResult.prototype.reason
* @function
* @public
* @returns {ResultReason} Specifies status of the result.
*/
get reason() {
return this.privReason;
}
/**
* Presents the recognized text in the result.
* @member RecognitionResult.prototype.text
* @function
* @public
* @returns {string} Presents the recognized text in the result.
*/
get text() {
return this.privText;
}
/**
* 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 duration() {
return this.privDuration;
}
/**
* 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 offset() {
return this.privOffset;
}
/**
* Primary Language detected.
* @member RecognitionResult.prototype.language
* @function
* @public
* @returns {string} language detected.
*/
get language() {
return this.privLanguage;
}
/**
* Primary Language detection confidence (Unknown, Low, Medium, High).
* @member RecognitionResult.prototype.languageDetectionConfidence
* @function
* @public
* @returns {string} detection confidence strength.
*/
get languageDetectionConfidence() {
return this.privLanguageDetectionConfidence;
}
/**
* 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 errorDetails() {
return this.privErrorDetails;
}
/**
* 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 json() {
return this.privJson;
}
/**
* 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 properties() {
return this.privProperties;
}
};
exports.RecognitionResult = RecognitionResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechRecognitionResult.js
var require_SpeechRecognitionResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechRecognitionResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechRecognitionResult = void 0;
var Exports_js_1 = require_Exports3();
var SpeechRecognitionResult2 = class extends Exports_js_1.RecognitionResult {
/**
* 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.
*/
constructor(resultId, reason, text, duration, offset, language, languageDetectionConfidence, speakerId, errorDetails, json, properties) {
super(resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties);
this.privSpeakerId = speakerId;
}
/**
* speaker id from conversation transcription/id scenarios
* @member SpeechRecognitionResult.prototype.speakerId
* @function
* @public
* @returns {string} id of speaker in given result
*/
get speakerId() {
return this.privSpeakerId;
}
};
exports.SpeechRecognitionResult = SpeechRecognitionResult2;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/IntentRecognitionResult.js
var require_IntentRecognitionResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/IntentRecognitionResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentRecognitionResult = void 0;
var Exports_js_1 = require_Exports3();
var IntentRecognitionResult = class extends Exports_js_1.SpeechRecognitionResult {
/**
* 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.
*/
constructor(intentId, resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties) {
super(resultId, reason, text, duration, offset, language, languageDetectionConfidence, void 0, errorDetails, json, properties);
this.privIntentId = 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 intentId() {
return this.privIntentId;
}
};
exports.IntentRecognitionResult = IntentRecognitionResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/LanguageUnderstandingModel.js
var require_LanguageUnderstandingModel = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/LanguageUnderstandingModel.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LanguageUnderstandingModelImpl = exports.LanguageUnderstandingModel = void 0;
var Contracts_js_1 = require_Contracts();
var LanguageUnderstandingModel = class {
/**
* Creates and initializes a new instance
* @constructor
*/
constructor() {
return;
}
/**
* 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.
*/
static fromEndpoint(uri) {
Contracts_js_1.Contracts.throwIfNull(uri, "uri");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(uri.hostname, "uri");
const langModelImp = new LanguageUnderstandingModelImpl();
const firstDot = uri.host.indexOf(".");
if (-1 === firstDot) {
throw new Error("Could not determine region from endpoint");
}
langModelImp.region = uri.host.substr(0, firstDot);
const lastSegment = uri.pathname.lastIndexOf("/") + 1;
if (-1 === lastSegment) {
throw new Error("Could not determine appId from endpoint");
}
langModelImp.appId = uri.pathname.substr(lastSegment);
langModelImp.subscriptionKey = uri.searchParams.get("subscription-key");
if (void 0 === 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.
*/
static fromAppId(appId) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(appId, "appId");
const 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.
*/
static fromSubscription(subscriptionKey, appId, region) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(appId, "appId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region");
const langModelImp = new LanguageUnderstandingModelImpl();
langModelImp.appId = appId;
langModelImp.region = region;
langModelImp.subscriptionKey = subscriptionKey;
return langModelImp;
}
};
exports.LanguageUnderstandingModel = LanguageUnderstandingModel;
var LanguageUnderstandingModelImpl = class extends LanguageUnderstandingModel {
};
exports.LanguageUnderstandingModelImpl = LanguageUnderstandingModelImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechRecognitionEventArgs.js
var require_SpeechRecognitionEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechRecognitionEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MeetingTranscriptionEventArgs = exports.ConversationTranscriptionEventArgs = exports.SpeechRecognitionEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var SpeechRecognitionEventArgs = class extends Exports_js_1.RecognitionEventArgs {
/**
* 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.
*/
constructor(result, offset, sessionId) {
super(offset, sessionId);
this.privResult = result;
}
/**
* Specifies the recognition result.
* @member SpeechRecognitionEventArgs.prototype.result
* @function
* @public
* @returns {SpeechRecognitionResult} the recognition result.
*/
get result() {
return this.privResult;
}
};
exports.SpeechRecognitionEventArgs = SpeechRecognitionEventArgs;
var ConversationTranscriptionEventArgs = class extends Exports_js_1.RecognitionEventArgs {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {ConversationTranscriptionResult} result - The conversation transcription result.
* @param {number} offset - The offset.
* @param {string} sessionId - The session id.
*/
constructor(result, offset, sessionId) {
super(offset, sessionId);
this.privResult = result;
}
/**
* Specifies the transcription result.
* @member ConversationTranscription1EventArgs.prototype.result
* @function
* @public
* @returns {ConversationTranscriptionResult} the recognition result.
*/
get result() {
return this.privResult;
}
};
exports.ConversationTranscriptionEventArgs = ConversationTranscriptionEventArgs;
var MeetingTranscriptionEventArgs = class extends SpeechRecognitionEventArgs {
};
exports.MeetingTranscriptionEventArgs = MeetingTranscriptionEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CancellationEventArgsBase.js
var require_CancellationEventArgsBase = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CancellationEventArgsBase.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancellationEventArgsBase = void 0;
var Exports_js_1 = require_Exports3();
var CancellationEventArgsBase = class extends Exports_js_1.RecognitionEventArgs {
/**
* 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.
*/
constructor(reason, errorDetails, errorCode, offset, sessionId) {
super(offset, sessionId);
this.privReason = reason;
this.privErrorDetails = errorDetails;
this.privErrorCode = errorCode;
}
/**
* The reason the recognition was canceled.
* @member CancellationEventArgsBase.prototype.reason
* @function
* @public
* @returns {CancellationReason} Specifies the reason canceled.
*/
get reason() {
return this.privReason;
}
/**
* The error code in case of an unsuccessful operation.
* @return An error code that represents the error reason.
*/
get errorCode() {
return this.privErrorCode;
}
/**
* 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 errorDetails() {
return this.privErrorDetails;
}
};
exports.CancellationEventArgsBase = CancellationEventArgsBase;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechRecognitionCanceledEventArgs.js
var require_SpeechRecognitionCanceledEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechRecognitionCanceledEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechRecognitionCanceledEventArgs = void 0;
var CancellationEventArgsBase_js_1 = require_CancellationEventArgsBase();
var SpeechRecognitionCanceledEventArgs = class extends CancellationEventArgsBase_js_1.CancellationEventArgsBase {
};
exports.SpeechRecognitionCanceledEventArgs = SpeechRecognitionCanceledEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationRecognitionEventArgs.js
var require_TranslationRecognitionEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationRecognitionEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationRecognitionEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var TranslationRecognitionEventArgs = class extends Exports_js_1.RecognitionEventArgs {
/**
* 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.
*/
constructor(result, offset, sessionId) {
super(offset, sessionId);
this.privResult = result;
}
/**
* Specifies the recognition result.
* @member TranslationRecognitionEventArgs.prototype.result
* @function
* @public
* @returns {TranslationRecognitionResult} the recognition result.
*/
get result() {
return this.privResult;
}
};
exports.TranslationRecognitionEventArgs = TranslationRecognitionEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationSynthesisEventArgs.js
var require_TranslationSynthesisEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationSynthesisEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationSynthesisEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var TranslationSynthesisEventArgs = class extends Exports_js_1.SessionEventArgs {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {TranslationSynthesisResult} result - The translation synthesis result.
* @param {string} sessionId - The session id.
*/
constructor(result, sessionId) {
super(sessionId);
this.privResult = result;
}
/**
* Specifies the translation synthesis result.
* @member TranslationSynthesisEventArgs.prototype.result
* @function
* @public
* @returns {TranslationSynthesisResult} Specifies the translation synthesis result.
*/
get result() {
return this.privResult;
}
};
exports.TranslationSynthesisEventArgs = TranslationSynthesisEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationRecognitionResult.js
var require_TranslationRecognitionResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationRecognitionResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationRecognitionResult = void 0;
var Exports_js_1 = require_Exports3();
var TranslationRecognitionResult = class _TranslationRecognitionResult extends Exports_js_1.SpeechRecognitionResult {
/**
* 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} 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.
*/
constructor(translations, resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties) {
super(resultId, reason, text, duration, offset, language, languageDetectionConfidence, void 0, errorDetails, json, properties);
this.privTranslations = translations;
}
static fromSpeechRecognitionResult(result) {
return new _TranslationRecognitionResult(void 0, result.resultId, result.reason, result.text, result.duration, result.offset, result.language, result.languageDetectionConfidence, result.errorDetails, result.json, result.properties);
}
/**
* 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 translations() {
return this.privTranslations;
}
};
exports.TranslationRecognitionResult = TranslationRecognitionResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationSynthesisResult.js
var require_TranslationSynthesisResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationSynthesisResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationSynthesisResult = void 0;
var TranslationSynthesisResult = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {ResultReason} reason - The synthesis reason.
* @param {ArrayBuffer} audio - The audio data.
*/
constructor(reason, audio) {
this.privReason = reason;
this.privAudio = audio;
}
/**
* Translated text in the target language.
* @member TranslationSynthesisResult.prototype.audio
* @function
* @public
* @returns {ArrayBuffer} Translated audio in the target language.
*/
get audio() {
return this.privAudio;
}
/**
* The synthesis status.
* @member TranslationSynthesisResult.prototype.reason
* @function
* @public
* @returns {ResultReason} The synthesis status.
*/
get reason() {
return this.privReason;
}
};
exports.TranslationSynthesisResult = TranslationSynthesisResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ResultReason.js
var require_ResultReason = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ResultReason.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResultReason = void 0;
var ResultReason3;
(function(ResultReason4) {
ResultReason4[ResultReason4["NoMatch"] = 0] = "NoMatch";
ResultReason4[ResultReason4["Canceled"] = 1] = "Canceled";
ResultReason4[ResultReason4["RecognizingSpeech"] = 2] = "RecognizingSpeech";
ResultReason4[ResultReason4["RecognizedSpeech"] = 3] = "RecognizedSpeech";
ResultReason4[ResultReason4["RecognizedKeyword"] = 4] = "RecognizedKeyword";
ResultReason4[ResultReason4["RecognizingIntent"] = 5] = "RecognizingIntent";
ResultReason4[ResultReason4["RecognizedIntent"] = 6] = "RecognizedIntent";
ResultReason4[ResultReason4["TranslatingSpeech"] = 7] = "TranslatingSpeech";
ResultReason4[ResultReason4["TranslatedSpeech"] = 8] = "TranslatedSpeech";
ResultReason4[ResultReason4["SynthesizingAudio"] = 9] = "SynthesizingAudio";
ResultReason4[ResultReason4["SynthesizingAudioCompleted"] = 10] = "SynthesizingAudioCompleted";
ResultReason4[ResultReason4["SynthesizingAudioStarted"] = 11] = "SynthesizingAudioStarted";
ResultReason4[ResultReason4["EnrollingVoiceProfile"] = 12] = "EnrollingVoiceProfile";
ResultReason4[ResultReason4["EnrolledVoiceProfile"] = 13] = "EnrolledVoiceProfile";
ResultReason4[ResultReason4["RecognizedSpeakers"] = 14] = "RecognizedSpeakers";
ResultReason4[ResultReason4["RecognizedSpeaker"] = 15] = "RecognizedSpeaker";
ResultReason4[ResultReason4["ResetVoiceProfile"] = 16] = "ResetVoiceProfile";
ResultReason4[ResultReason4["DeletedVoiceProfile"] = 17] = "DeletedVoiceProfile";
ResultReason4[ResultReason4["VoicesListRetrieved"] = 18] = "VoicesListRetrieved";
ResultReason4[ResultReason4["TranslatingParticipantSpeech"] = 19] = "TranslatingParticipantSpeech";
ResultReason4[ResultReason4["TranslatedParticipantSpeech"] = 20] = "TranslatedParticipantSpeech";
ResultReason4[ResultReason4["TranslatedInstantMessage"] = 21] = "TranslatedInstantMessage";
ResultReason4[ResultReason4["TranslatedParticipantInstantMessage"] = 22] = "TranslatedParticipantInstantMessage";
})(ResultReason3 = exports.ResultReason || (exports.ResultReason = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechConfig.js
var require_SpeechConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechConfigImpl = exports.SpeechConfig = void 0;
var Exports_js_1 = require_Exports7();
var Contracts_js_1 = require_Contracts();
var Exports_js_2 = require_Exports3();
var SpeechConfig3 = class {
/**
* Creates and initializes an instance.
* @constructor
*/
constructor() {
return;
}
/**
* 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
*/
static fromSubscription(subscriptionKey, region) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region");
const speechImpl = new SpeechConfigImpl();
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, region);
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_IntentRegion, region);
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
return speechImpl;
}
/**
* Internal implementation of fromEndpoint() overloads. Accepts either a subscription key or a TokenCredential.
* @private
*/
static fromEndpoint(endpoint, auth) {
Contracts_js_1.Contracts.throwIfNull(endpoint, "endpoint");
const isValidString = typeof auth === "string" && auth.trim().length > 0;
const isTokenCredential = typeof auth === "object" && auth !== null && typeof auth.getToken === "function";
const isKeyCredential = typeof auth === "object" && auth !== null && typeof auth.key === "string";
if (auth !== void 0 && !isValidString && !isTokenCredential && !isKeyCredential) {
throw new Error("Invalid 'auth' parameter: expected a non-empty API key string, a TokenCredential, or a KeyCredential.");
}
let speechImpl;
if (typeof auth === "string") {
speechImpl = new SpeechConfigImpl();
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, auth);
} else if (typeof auth === "object" && typeof auth.getToken === "function") {
speechImpl = new SpeechConfigImpl(auth);
} else if (typeof auth === "object" && typeof auth.key === "string") {
speechImpl = new SpeechConfigImpl();
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, auth.key);
} else {
speechImpl = new SpeechConfigImpl();
}
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, endpoint.href);
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.
*/
static fromHost(hostName, subscriptionKey) {
Contracts_js_1.Contracts.throwIfNull(hostName, "hostName");
const speechImpl = new SpeechConfigImpl();
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, hostName.protocol + "//" + hostName.hostname + (hostName.port === "" ? "" : ":" + hostName.port));
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, "1");
if (void 0 !== subscriptionKey) {
speechImpl.setProperty(Exports_js_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.
*/
static fromAuthorizationToken(authorizationToken, region) {
Contracts_js_1.Contracts.throwIfNull(authorizationToken, "authorizationToken");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region");
const speechImpl = new SpeechConfigImpl();
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, region);
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_IntentRegion, region);
speechImpl.authorizationToken = authorizationToken;
return speechImpl;
}
/**
* Closes the configuration.
* @member SpeechConfig.prototype.close
* @function
* @public
*/
// eslint-disable-next-line @typescript-eslint/no-empty-function
close() {
}
};
exports.SpeechConfig = SpeechConfig3;
var SpeechConfigImpl = class _SpeechConfigImpl extends SpeechConfig3 {
constructor(tokenCredential) {
super();
this.privProperties = new Exports_js_2.PropertyCollection();
this.speechRecognitionLanguage = "en-US";
this.outputFormat = Exports_js_2.OutputFormat.Simple;
this.privTokenCredential = tokenCredential;
}
get properties() {
return this.privProperties;
}
get endPoint() {
return new URL(this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint));
}
get subscriptionKey() {
return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key);
}
get region() {
return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region);
}
get authorizationToken() {
return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token);
}
set authorizationToken(value) {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token, value);
}
get speechRecognitionLanguage() {
return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage);
}
set speechRecognitionLanguage(value) {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, value);
}
get autoDetectSourceLanguages() {
return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages);
}
set autoDetectSourceLanguages(value) {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, value);
}
get outputFormat() {
return Exports_js_2.OutputFormat[this.privProperties.getProperty(Exports_js_1.OutputFormatPropertyName, void 0)];
}
set outputFormat(value) {
this.privProperties.setProperty(Exports_js_1.OutputFormatPropertyName, Exports_js_2.OutputFormat[value]);
}
get endpointId() {
return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId);
}
set endpointId(value) {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId, value);
}
get tokenCredential() {
return this.privTokenCredential;
}
setProperty(name, value) {
Contracts_js_1.Contracts.throwIfNull(value, "value");
this.privProperties.setProperty(name, value);
}
getProperty(name, def) {
return this.privProperties.getProperty(name, def);
}
setProxy(proxyHostName, proxyPort, proxyUserName, proxyPassword) {
this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName);
this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyPort], proxyPort);
this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName);
this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyPassword], proxyPassword);
}
setServiceProperty(name, value) {
const currentProperties = JSON.parse(this.privProperties.getProperty(Exports_js_1.ServicePropertiesPropertyName, "{}"));
currentProperties[name] = value;
this.privProperties.setProperty(Exports_js_1.ServicePropertiesPropertyName, JSON.stringify(currentProperties));
}
setProfanity(profanity) {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_ProfanityOption, Exports_js_2.ProfanityOption[profanity]);
}
enableAudioLogging() {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, "true");
}
requestWordLevelTimestamps() {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "true");
this.privProperties.setProperty(Exports_js_1.OutputFormatPropertyName, Exports_js_2.OutputFormat[Exports_js_2.OutputFormat.Detailed]);
}
enableDictation() {
this.privProperties.setProperty(Exports_js_1.ForceDictationPropertyName, "true");
}
clone() {
const ret = new _SpeechConfigImpl(this.tokenCredential);
ret.privProperties = this.privProperties.clone();
return ret;
}
get speechSynthesisLanguage() {
return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthLanguage);
}
set speechSynthesisLanguage(language) {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthLanguage, language);
}
get speechSynthesisVoiceName() {
return this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthVoice);
}
set speechSynthesisVoiceName(voice) {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthVoice, voice);
}
get speechSynthesisOutputFormat() {
return Exports_js_2.SpeechSynthesisOutputFormat[this.privProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, void 0)];
}
set speechSynthesisOutputFormat(format2) {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, Exports_js_2.SpeechSynthesisOutputFormat[format2]);
}
};
exports.SpeechConfigImpl = SpeechConfigImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechTranslationConfig.js
var require_SpeechTranslationConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechTranslationConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechTranslationConfigImpl = exports.SpeechTranslationConfig = void 0;
var Exports_js_1 = require_Exports7();
var Contracts_js_1 = require_Contracts();
var Exports_js_2 = require_Exports3();
var SpeechTranslationConfig = class extends Exports_js_2.SpeechConfig {
/**
* Creates an instance of recognizer config.
*/
constructor() {
super();
}
/**
* 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.
*/
static fromSubscription(subscriptionKey, region) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(subscriptionKey, "subscriptionKey");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region");
const ret = new SpeechTranslationConfigImpl();
ret.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
ret.properties.setProperty(Exports_js_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.
*/
static fromAuthorizationToken(authorizationToken, region) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region");
const ret = new SpeechTranslationConfigImpl();
ret.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token, authorizationToken);
ret.properties.setProperty(Exports_js_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.
*/
static fromHost(hostName, subscriptionKey) {
Contracts_js_1.Contracts.throwIfNull(hostName, "hostName");
const speechImpl = new SpeechTranslationConfigImpl();
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, hostName.protocol + "//" + hostName.hostname + (hostName.port === "" ? "" : ":" + hostName.port));
if (void 0 !== subscriptionKey) {
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
}
return speechImpl;
}
/**
* Internal implementation of fromEndpoint() overloads. Accepts either a subscription key or a TokenCredential.
* @private
*/
static fromEndpoint(endpoint, auth) {
Contracts_js_1.Contracts.throwIfNull(endpoint, "endpoint");
const isValidString = typeof auth === "string" && auth.trim().length > 0;
const isTokenCredential = typeof auth === "object" && auth !== null && typeof auth.getToken === "function";
const isKeyCredential = typeof auth === "object" && auth !== null && typeof auth.key === "string";
if (auth !== void 0 && !isValidString && !isTokenCredential && !isKeyCredential) {
throw new Error("Invalid 'auth' parameter: expected a non-empty API key string, a TokenCredential, or a KeyCredential.");
}
let speechImpl;
if (typeof auth === "string") {
speechImpl = new SpeechTranslationConfigImpl();
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, auth);
} else if (typeof auth === "object" && typeof auth.getToken === "function") {
speechImpl = new SpeechTranslationConfigImpl(auth);
} else if (typeof auth === "object" && typeof auth.key === "string") {
speechImpl = new SpeechTranslationConfigImpl();
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key, auth.key);
} else {
speechImpl = new SpeechTranslationConfigImpl();
}
speechImpl.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, endpoint.href);
return speechImpl;
}
};
exports.SpeechTranslationConfig = SpeechTranslationConfig;
var SpeechTranslationConfigImpl = class extends SpeechTranslationConfig {
constructor(tokenCredential) {
super();
this.privSpeechProperties = new Exports_js_2.PropertyCollection();
this.outputFormat = Exports_js_2.OutputFormat.Simple;
this.privTokenCredential = tokenCredential;
}
/**
* 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 authorizationToken(value) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value");
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token, value);
}
/**
* Sets the speech recognition language.
* @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage
* @function
* @public
* @param {string} value - The authorization token.
*/
set speechRecognitionLanguage(value) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value");
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, value);
}
/**
* Gets the speech recognition language.
* @member SpeechTranslationConfigImpl.prototype.speechRecognitionLanguage
* @function
* @public
* @return {string} The speechRecognitionLanguage.
*/
get speechRecognitionLanguage() {
return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage]);
}
/**
* @member SpeechTranslationConfigImpl.prototype.subscriptionKey
* @function
* @public
*/
get subscriptionKey() {
return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_Key]);
}
/**
* Gets the output format
* @member SpeechTranslationConfigImpl.prototype.outputFormat
* @function
* @public
*/
get outputFormat() {
return Exports_js_2.OutputFormat[this.privSpeechProperties.getProperty(Exports_js_1.OutputFormatPropertyName, void 0)];
}
/**
* Gets/Sets the output format
* @member SpeechTranslationConfigImpl.prototype.outputFormat
* @function
* @public
*/
set outputFormat(value) {
this.privSpeechProperties.setProperty(Exports_js_1.OutputFormatPropertyName, Exports_js_2.OutputFormat[value]);
}
/**
* Gets the endpoint id.
* @member SpeechTranslationConfigImpl.prototype.endpointId
* @function
* @public
*/
get endpointId() {
return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId);
}
/**
* Gets/Sets the endpoint id.
* @member SpeechTranslationConfigImpl.prototype.endpointId
* @function
* @public
*/
set endpointId(value) {
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId, value);
}
/**
* Add a (text) target language to translate into.
* @member SpeechTranslationConfigImpl.prototype.addTargetLanguage
* @function
* @public
* @param {string} value - The language such as de-DE
*/
addTargetLanguage(value) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value");
const languages = this.targetLanguages;
if (!languages.includes(value)) {
languages.push(value);
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(","));
}
}
/**
* Gets the (text) target language to translate into.
* @member SpeechTranslationConfigImpl.prototype.targetLanguages
* @function
* @public
* @param {string} value - The language such as de-DE
*/
get targetLanguages() {
if (this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationToLanguages, void 0) !== void 0) {
return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
} else {
return [];
}
}
/**
* Gets the voice name.
* @member SpeechTranslationConfigImpl.prototype.voiceName
* @function
* @public
*/
get voiceName() {
return this.getProperty(Exports_js_2.PropertyId[Exports_js_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 voiceName(value) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value");
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationVoice, value);
}
/**
* Provides the region.
* @member SpeechTranslationConfigImpl.prototype.region
* @function
* @public
* @returns {string} The region.
*/
get region() {
return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region);
}
get tokenCredential() {
return this.privTokenCredential;
}
setProxy(proxyHostName, proxyPort, proxyUserName, proxyPassword) {
this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyHostName], proxyHostName);
this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyPort], proxyPort);
this.setProperty(Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_ProxyUserName], proxyUserName);
this.setProperty(Exports_js_2.PropertyId[Exports_js_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.
*/
getProperty(name, def) {
return this.privSpeechProperties.getProperty(name, def);
}
/**
* Gets/Sets an arbitrary property value.
* @member SpeechTranslationConfigImpl.prototype.setProperty
* @function
* @public
* @param {string | PropertyId} name - The name of the property to set.
* @param {string} value - The value of the property.
*/
setProperty(name, value) {
this.privSpeechProperties.setProperty(name, value);
}
/**
* Provides access to custom properties.
* @member SpeechTranslationConfigImpl.prototype.properties
* @function
* @public
* @returns {PropertyCollection} The properties.
*/
get properties() {
return this.privSpeechProperties;
}
/**
* Dispose of associated resources.
* @member SpeechTranslationConfigImpl.prototype.close
* @function
* @public
*/
close() {
return;
}
setServiceProperty(name, value) {
const currentProperties = JSON.parse(this.privSpeechProperties.getProperty(Exports_js_1.ServicePropertiesPropertyName, "{}"));
currentProperties[name] = value;
this.privSpeechProperties.setProperty(Exports_js_1.ServicePropertiesPropertyName, JSON.stringify(currentProperties));
}
setProfanity(profanity) {
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_ProfanityOption, Exports_js_2.ProfanityOption[profanity]);
}
enableAudioLogging() {
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, "true");
}
requestWordLevelTimestamps() {
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "true");
}
enableDictation() {
this.privSpeechProperties.setProperty(Exports_js_1.ForceDictationPropertyName, "true");
}
get speechSynthesisLanguage() {
return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthLanguage);
}
set speechSynthesisLanguage(language) {
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthLanguage, language);
}
get speechSynthesisVoiceName() {
return this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthVoice);
}
set speechSynthesisVoiceName(voice) {
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthVoice, voice);
}
get speechSynthesisOutputFormat() {
return Exports_js_2.SpeechSynthesisOutputFormat[this.privSpeechProperties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, void 0)];
}
set speechSynthesisOutputFormat(format2) {
this.privSpeechProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SynthOutputFormat, Exports_js_2.SpeechSynthesisOutputFormat[format2]);
}
};
exports.SpeechTranslationConfigImpl = SpeechTranslationConfigImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PropertyCollection.js
var require_PropertyCollection = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PropertyCollection.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PropertyCollection = void 0;
var Exports_js_1 = require_Exports3();
var PropertyCollection = class _PropertyCollection {
constructor() {
this.privKeys = [];
this.privValues = [];
}
/**
* Returns the property value in type 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 | number | boolean} def - The default value which is returned if the parameter
* is not available in the collection.
* @returns {string} value of the parameter.
*/
getProperty(key, def) {
let keyToUse;
if (typeof key === "string") {
keyToUse = key;
} else {
keyToUse = Exports_js_1.PropertyId[key];
}
for (let n = 0; n < this.privKeys.length; n++) {
if (this.privKeys[n] === keyToUse) {
return this.privValues[n];
}
}
if (def === void 0) {
return void 0;
}
return String(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.
*/
setProperty(key, value) {
let keyToUse;
if (typeof key === "string") {
keyToUse = key;
} else {
keyToUse = Exports_js_1.PropertyId[key];
}
for (let 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.
*/
clone() {
const clonedMap = new _PropertyCollection();
for (let 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} destinationCollection - The collection to merge into.
*/
mergeTo(destinationCollection) {
this.privKeys.forEach((key) => {
if (destinationCollection.getProperty(key, void 0) === void 0) {
const value = this.getProperty(key);
destinationCollection.setProperty(key, value);
}
});
}
/**
* Get the keys in Property Collection.
* @member PropertyCollection.prototype.keys
* @function
* @public
* @returns {string []} Keys in the collection.
*/
get keys() {
return this.privKeys;
}
};
exports.PropertyCollection = PropertyCollection;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PropertyId.js
var require_PropertyId = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PropertyId.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PropertyId = void 0;
var PropertyId2;
(function(PropertyId3) {
PropertyId3[PropertyId3["SpeechServiceConnection_Key"] = 0] = "SpeechServiceConnection_Key";
PropertyId3[PropertyId3["SpeechServiceConnection_Endpoint"] = 1] = "SpeechServiceConnection_Endpoint";
PropertyId3[PropertyId3["SpeechServiceConnection_Region"] = 2] = "SpeechServiceConnection_Region";
PropertyId3[PropertyId3["SpeechServiceAuthorization_Token"] = 3] = "SpeechServiceAuthorization_Token";
PropertyId3[PropertyId3["SpeechServiceAuthorization_Type"] = 4] = "SpeechServiceAuthorization_Type";
PropertyId3[PropertyId3["SpeechServiceConnection_EndpointId"] = 5] = "SpeechServiceConnection_EndpointId";
PropertyId3[PropertyId3["SpeechServiceConnection_TranslationToLanguages"] = 6] = "SpeechServiceConnection_TranslationToLanguages";
PropertyId3[PropertyId3["SpeechServiceConnection_TranslationVoice"] = 7] = "SpeechServiceConnection_TranslationVoice";
PropertyId3[PropertyId3["SpeechServiceConnection_TranslationFeatures"] = 8] = "SpeechServiceConnection_TranslationFeatures";
PropertyId3[PropertyId3["SpeechServiceConnection_TranslationCategoryId"] = 9] = "SpeechServiceConnection_TranslationCategoryId";
PropertyId3[PropertyId3["SpeechServiceConnection_IntentRegion"] = 10] = "SpeechServiceConnection_IntentRegion";
PropertyId3[PropertyId3["SpeechServiceConnection_ProxyHostName"] = 11] = "SpeechServiceConnection_ProxyHostName";
PropertyId3[PropertyId3["SpeechServiceConnection_ProxyPort"] = 12] = "SpeechServiceConnection_ProxyPort";
PropertyId3[PropertyId3["SpeechServiceConnection_ProxyUserName"] = 13] = "SpeechServiceConnection_ProxyUserName";
PropertyId3[PropertyId3["SpeechServiceConnection_ProxyPassword"] = 14] = "SpeechServiceConnection_ProxyPassword";
PropertyId3[PropertyId3["SpeechServiceConnection_RecoMode"] = 15] = "SpeechServiceConnection_RecoMode";
PropertyId3[PropertyId3["SpeechServiceConnection_RecoLanguage"] = 16] = "SpeechServiceConnection_RecoLanguage";
PropertyId3[PropertyId3["Speech_SessionId"] = 17] = "Speech_SessionId";
PropertyId3[PropertyId3["SpeechServiceConnection_SynthLanguage"] = 18] = "SpeechServiceConnection_SynthLanguage";
PropertyId3[PropertyId3["SpeechServiceConnection_SynthVoice"] = 19] = "SpeechServiceConnection_SynthVoice";
PropertyId3[PropertyId3["SpeechServiceConnection_SynthOutputFormat"] = 20] = "SpeechServiceConnection_SynthOutputFormat";
PropertyId3[PropertyId3["SpeechServiceConnection_AutoDetectSourceLanguages"] = 21] = "SpeechServiceConnection_AutoDetectSourceLanguages";
PropertyId3[PropertyId3["SpeechServiceResponse_RequestDetailedResultTrueFalse"] = 22] = "SpeechServiceResponse_RequestDetailedResultTrueFalse";
PropertyId3[PropertyId3["SpeechServiceResponse_RequestProfanityFilterTrueFalse"] = 23] = "SpeechServiceResponse_RequestProfanityFilterTrueFalse";
PropertyId3[PropertyId3["SpeechServiceResponse_JsonResult"] = 24] = "SpeechServiceResponse_JsonResult";
PropertyId3[PropertyId3["SpeechServiceResponse_JsonErrorDetails"] = 25] = "SpeechServiceResponse_JsonErrorDetails";
PropertyId3[PropertyId3["CancellationDetails_Reason"] = 26] = "CancellationDetails_Reason";
PropertyId3[PropertyId3["CancellationDetails_ReasonText"] = 27] = "CancellationDetails_ReasonText";
PropertyId3[PropertyId3["CancellationDetails_ReasonDetailedText"] = 28] = "CancellationDetails_ReasonDetailedText";
PropertyId3[PropertyId3["LanguageUnderstandingServiceResponse_JsonResult"] = 29] = "LanguageUnderstandingServiceResponse_JsonResult";
PropertyId3[PropertyId3["SpeechServiceConnection_Url"] = 30] = "SpeechServiceConnection_Url";
PropertyId3[PropertyId3["SpeechServiceConnection_InitialSilenceTimeoutMs"] = 31] = "SpeechServiceConnection_InitialSilenceTimeoutMs";
PropertyId3[PropertyId3["SpeechServiceConnection_EndSilenceTimeoutMs"] = 32] = "SpeechServiceConnection_EndSilenceTimeoutMs";
PropertyId3[PropertyId3["Speech_SegmentationSilenceTimeoutMs"] = 33] = "Speech_SegmentationSilenceTimeoutMs";
PropertyId3[PropertyId3["Speech_SegmentationMaximumTimeMs"] = 34] = "Speech_SegmentationMaximumTimeMs";
PropertyId3[PropertyId3["Speech_SegmentationStrategy"] = 35] = "Speech_SegmentationStrategy";
PropertyId3[PropertyId3["SpeechServiceConnection_EnableAudioLogging"] = 36] = "SpeechServiceConnection_EnableAudioLogging";
PropertyId3[PropertyId3["SpeechServiceConnection_LanguageIdMode"] = 37] = "SpeechServiceConnection_LanguageIdMode";
PropertyId3[PropertyId3["SpeechServiceConnection_RecognitionEndpointVersion"] = 38] = "SpeechServiceConnection_RecognitionEndpointVersion";
PropertyId3[PropertyId3["SpeechServiceConnection_SpeakerIdMode"] = 39] = "SpeechServiceConnection_SpeakerIdMode";
PropertyId3[PropertyId3["SpeechServiceResponse_ProfanityOption"] = 40] = "SpeechServiceResponse_ProfanityOption";
PropertyId3[PropertyId3["SpeechServiceResponse_PostProcessingOption"] = 41] = "SpeechServiceResponse_PostProcessingOption";
PropertyId3[PropertyId3["SpeechServiceResponse_RequestWordLevelTimestamps"] = 42] = "SpeechServiceResponse_RequestWordLevelTimestamps";
PropertyId3[PropertyId3["SpeechServiceResponse_StablePartialResultThreshold"] = 43] = "SpeechServiceResponse_StablePartialResultThreshold";
PropertyId3[PropertyId3["SpeechServiceResponse_OutputFormatOption"] = 44] = "SpeechServiceResponse_OutputFormatOption";
PropertyId3[PropertyId3["SpeechServiceResponse_TranslationRequestStablePartialResult"] = 45] = "SpeechServiceResponse_TranslationRequestStablePartialResult";
PropertyId3[PropertyId3["SpeechServiceResponse_RequestWordBoundary"] = 46] = "SpeechServiceResponse_RequestWordBoundary";
PropertyId3[PropertyId3["SpeechServiceResponse_RequestPunctuationBoundary"] = 47] = "SpeechServiceResponse_RequestPunctuationBoundary";
PropertyId3[PropertyId3["SpeechServiceResponse_RequestSentenceBoundary"] = 48] = "SpeechServiceResponse_RequestSentenceBoundary";
PropertyId3[PropertyId3["SpeechServiceResponse_DiarizeIntermediateResults"] = 49] = "SpeechServiceResponse_DiarizeIntermediateResults";
PropertyId3[PropertyId3["Conversation_ApplicationId"] = 50] = "Conversation_ApplicationId";
PropertyId3[PropertyId3["Conversation_DialogType"] = 51] = "Conversation_DialogType";
PropertyId3[PropertyId3["Conversation_Initial_Silence_Timeout"] = 52] = "Conversation_Initial_Silence_Timeout";
PropertyId3[PropertyId3["Conversation_From_Id"] = 53] = "Conversation_From_Id";
PropertyId3[PropertyId3["Conversation_Conversation_Id"] = 54] = "Conversation_Conversation_Id";
PropertyId3[PropertyId3["Conversation_Custom_Voice_Deployment_Ids"] = 55] = "Conversation_Custom_Voice_Deployment_Ids";
PropertyId3[PropertyId3["Conversation_Speech_Activity_Template"] = 56] = "Conversation_Speech_Activity_Template";
PropertyId3[PropertyId3["Conversation_Request_Bot_Status_Messages"] = 57] = "Conversation_Request_Bot_Status_Messages";
PropertyId3[PropertyId3["Conversation_Agent_Connection_Id"] = 58] = "Conversation_Agent_Connection_Id";
PropertyId3[PropertyId3["SpeechServiceConnection_Host"] = 59] = "SpeechServiceConnection_Host";
PropertyId3[PropertyId3["ConversationTranslator_Host"] = 60] = "ConversationTranslator_Host";
PropertyId3[PropertyId3["ConversationTranslator_Name"] = 61] = "ConversationTranslator_Name";
PropertyId3[PropertyId3["ConversationTranslator_CorrelationId"] = 62] = "ConversationTranslator_CorrelationId";
PropertyId3[PropertyId3["ConversationTranslator_Token"] = 63] = "ConversationTranslator_Token";
PropertyId3[PropertyId3["PronunciationAssessment_ReferenceText"] = 64] = "PronunciationAssessment_ReferenceText";
PropertyId3[PropertyId3["PronunciationAssessment_GradingSystem"] = 65] = "PronunciationAssessment_GradingSystem";
PropertyId3[PropertyId3["PronunciationAssessment_Granularity"] = 66] = "PronunciationAssessment_Granularity";
PropertyId3[PropertyId3["PronunciationAssessment_EnableMiscue"] = 67] = "PronunciationAssessment_EnableMiscue";
PropertyId3[PropertyId3["PronunciationAssessment_Json"] = 68] = "PronunciationAssessment_Json";
PropertyId3[PropertyId3["PronunciationAssessment_Params"] = 69] = "PronunciationAssessment_Params";
PropertyId3[PropertyId3["SpeakerRecognition_Api_Version"] = 70] = "SpeakerRecognition_Api_Version";
PropertyId3[PropertyId3["WebWorkerLoadType"] = 71] = "WebWorkerLoadType";
PropertyId3[PropertyId3["TalkingAvatarService_WebRTC_SDP"] = 72] = "TalkingAvatarService_WebRTC_SDP";
})(PropertyId2 = exports.PropertyId || (exports.PropertyId = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Recognizer.js
var require_Recognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Recognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Recognizer = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var Recognizer = class _Recognizer {
/**
* Creates and initializes an instance of a Recognizer
* @constructor
* @param {AudioConfig} audioInput - An optional audio input stream associated with the recognizer
* @param {PropertyCollection} properties - A set of properties to set on the recognizer
* @param {IConnectionFactory} connectionFactory - The factory class used to create a custom IConnection for the recognizer
*/
constructor(audioConfig, properties, connectionFactory, tokenCredential) {
this.audioConfig = audioConfig !== void 0 ? audioConfig : Exports_js_3.AudioConfig.fromDefaultMicrophoneInput();
this.privDisposed = false;
this.privProperties = properties.clone();
this.privConnectionFactory = connectionFactory;
this.tokenCredential = tokenCredential;
this.implCommonRecognizerSetup();
}
/**
* Dispose of associated resources.
* @member Recognizer.prototype.close
* @function
* @public
*/
close(cb, errorCb) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed);
(0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, errorCb);
}
/**
* @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 internalData() {
return this.privReco;
}
/**
* 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.
*/
async dispose(disposing) {
if (this.privDisposed) {
return;
}
this.privDisposed = true;
if (disposing) {
if (this.privReco) {
await this.privReco.audioSource.turnOff();
await this.privReco.dispose();
}
}
}
/**
* 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.
*/
static get telemetryEnabled() {
return Exports_js_1.ServiceRecognizerBase.telemetryDataEnabled;
}
/**
* 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.
*/
static enableTelemetry(enabled) {
Exports_js_1.ServiceRecognizerBase.telemetryDataEnabled = enabled;
}
// Does the generic recognizer setup that is common across all recognizer types.
implCommonRecognizerSetup() {
let osPlatform = typeof window !== "undefined" ? "Browser" : "Node";
let osName = "unknown";
let osVersion = "unknown";
if (typeof navigator !== "undefined") {
osPlatform = osPlatform + "/" + navigator.platform;
osName = navigator.userAgent;
osVersion = navigator.appVersion;
}
const recognizerConfig = this.createRecognizerConfig(new Exports_js_1.SpeechServiceConfig(new Exports_js_1.Context(new Exports_js_1.OS(osPlatform, osName, osVersion))));
this.privReco = this.createServiceRecognizer(_Recognizer.getAuth(this.privProperties, this.tokenCredential), this.privConnectionFactory, this.audioConfig, recognizerConfig);
}
async recognizeOnceAsyncImpl(recognitionMode) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed);
const ret = new Exports_js_2.Deferred();
await this.implRecognizerStop();
await this.privReco.recognize(recognitionMode, ret.resolve, ret.reject);
const result = await ret.promise;
await this.implRecognizerStop();
return result;
}
async startContinuousRecognitionAsyncImpl(recognitionMode) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed);
await this.implRecognizerStop();
await this.privReco.recognize(recognitionMode, void 0, void 0);
}
async stopContinuousRecognitionAsyncImpl() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed);
await this.implRecognizerStop();
}
async implRecognizerStop() {
if (this.privReco) {
await this.privReco.stopRecognizing();
}
return;
}
static getAuth(properties, tokenCredential) {
const subscriptionKey = properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Key, void 0);
if (subscriptionKey && subscriptionKey !== "") {
return new Exports_js_1.CognitiveSubscriptionKeyAuthentication(subscriptionKey);
}
if (tokenCredential) {
return new Exports_js_1.CognitiveTokenAuthentication(async () => {
try {
const tokenResponse = await tokenCredential.getToken("https://cognitiveservices.azure.com/.default");
return tokenResponse?.token ?? "";
} catch (err) {
throw err;
}
}, async () => {
try {
const tokenResponse = await tokenCredential.getToken("https://cognitiveservices.azure.com/.default");
return tokenResponse?.token ?? "";
} catch (err) {
throw err;
}
});
}
return new Exports_js_1.CognitiveTokenAuthentication(() => {
const authorizationToken = properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, void 0);
return Promise.resolve(authorizationToken);
}, () => {
const authorizationToken = properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, void 0);
return Promise.resolve(authorizationToken);
});
}
};
exports.Recognizer = Recognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseDetection/PhraseDetectionContext.js
var require_PhraseDetectionContext = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseDetection/PhraseDetectionContext.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecognitionMode = void 0;
var RecognitionMode;
(function(RecognitionMode2) {
RecognitionMode2["Interactive"] = "Interactive";
RecognitionMode2["Dictation"] = "Dictation";
RecognitionMode2["Conversation"] = "Conversation";
RecognitionMode2["None"] = "None";
})(RecognitionMode = exports.RecognitionMode || (exports.RecognitionMode = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechRecognizer.js
var require_SpeechRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechRecognizer = void 0;
var Exports_js_1 = require_Exports7();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var SpeechRecognizer4 = class _SpeechRecognizer extends Exports_js_3.Recognizer {
/**
* 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
*/
constructor(speechConfig, audioConfig) {
const speechConfigImpl = speechConfig;
Contracts_js_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(speechConfigImpl.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
super(audioConfig, speechConfigImpl.properties, new Exports_js_1.SpeechConnectionFactory(), speechConfig.tokenCredential);
this.privDisposedRecognizer = false;
}
/**
* 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
*/
static FromConfig(speechConfig, autoDetectSourceLanguageConfig, audioConfig) {
const speechConfigImpl = speechConfig;
autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties);
const recognizer = new _SpeechRecognizer(speechConfig, audioConfig);
return recognizer;
}
/**
* 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 endpointId() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_EndpointId, "00000000-0000-0000-0000-000000000000");
}
/**
* Gets the authorization token used to communicate with the service.
* @member SpeechRecognizer.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
get authorizationToken() {
return this.properties.getProperty(Exports_js_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 authorizationToken(token) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token");
this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, token);
}
/**
* Gets the spoken language of recognition.
* @member SpeechRecognizer.prototype.speechRecognitionLanguage
* @function
* @public
* @returns {string} The spoken language of recognition.
*/
get speechRecognitionLanguage() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage);
}
/**
* Gets the output format of recognition.
* @member SpeechRecognizer.prototype.outputFormat
* @function
* @public
* @returns {OutputFormat} The output format of recognition.
*/
get outputFormat() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
if (this.properties.getProperty(Exports_js_1.OutputFormatPropertyName, Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]) === Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]) {
return Exports_js_3.OutputFormat.Simple;
} else {
return Exports_js_3.OutputFormat.Detailed;
}
}
/**
* 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 properties() {
return this.privProperties;
}
/**
* 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.
*/
recognizeOnceAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.recognizeOnceAsyncImpl(PhraseDetectionContext_js_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.
*/
startContinuousRecognitionAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(this.properties.getProperty(Exports_js_1.ForceDictationPropertyName, void 0) === void 0 ? PhraseDetectionContext_js_1.RecognitionMode.Conversation : PhraseDetectionContext_js_1.RecognitionMode.Dictation), 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.
*/
stopContinuousRecognitionAsync(cb, err) {
(0, Exports_js_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.
*/
startKeywordRecognitionAsync(model, cb, err) {
Contracts_js_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.
*/
stopKeywordRecognitionAsync(cb) {
if (!!cb) {
cb();
}
}
/**
* closes all external resources held by an instance of this class.
* @member SpeechRecognizer.prototype.close
* @function
* @public
*/
close(cb, errorCb) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
(0, Exports_js_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.
*/
async dispose(disposing) {
if (this.privDisposedRecognizer) {
return;
}
if (disposing) {
this.privDisposedRecognizer = true;
await this.implRecognizerStop();
}
await super.dispose(disposing);
}
createRecognizerConfig(speechConfig) {
return new Exports_js_1.RecognizerConfig(speechConfig, this.privProperties);
}
createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) {
const configImpl = audioConfig;
return new Exports_js_1.SpeechServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);
}
};
exports.SpeechRecognizer = SpeechRecognizer4;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/IntentRecognizer.js
var require_IntentRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/IntentRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentRecognizer = void 0;
var Exports_js_1 = require_Exports7();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var IntentRecognizer = class extends Exports_js_3.Recognizer {
/**
* 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
*/
constructor(speechConfig, audioConfig) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig, "speechConfig");
const configImpl = speechConfig;
Contracts_js_1.Contracts.throwIfNullOrUndefined(configImpl, "speechConfig");
super(audioConfig, configImpl.properties, new Exports_js_1.IntentConnectionFactory());
this.privAddedIntents = [];
this.privAddedLmIntents = {};
this.privDisposedIntentRecognizer = false;
this.privProperties = configImpl.properties;
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
}
/**
* Gets the spoken language of recognition.
* @member IntentRecognizer.prototype.speechRecognitionLanguage
* @function
* @public
* @returns {string} the spoken language of recognition.
*/
get speechRecognitionLanguage() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage);
}
/**
* Gets the authorization token used to communicate with the service.
* @member IntentRecognizer.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
get authorizationToken() {
return this.properties.getProperty(Exports_js_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 authorizationToken(value) {
this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, value);
}
/**
* 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 properties() {
return this.privProperties;
}
/**
* 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.
*/
recognizeOnceAsync(cb, err) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);
if (Object.keys(this.privAddedLmIntents).length !== 0 || void 0 !== this.privUmbrellaIntent) {
const context = this.buildSpeechContext();
this.privReco.speechContext.getContext().intent = context.Intent;
this.privReco.dynamicGrammar.addReferenceGrammar(context.ReferenceGrammars);
const intentReco = this.privReco;
intentReco.setIntents(this.privAddedLmIntents, this.privUmbrellaIntent);
}
(0, Exports_js_2.marshalPromiseToCallbacks)(this.recognizeOnceAsyncImpl(PhraseDetectionContext_js_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.
*/
startContinuousRecognitionAsync(cb, err) {
if (Object.keys(this.privAddedLmIntents).length !== 0 || void 0 !== this.privUmbrellaIntent) {
const context = this.buildSpeechContext();
this.privReco.speechContext.getContext().intent = context.Intent;
this.privReco.dynamicGrammar.addReferenceGrammar(context.ReferenceGrammars);
const intentReco = this.privReco;
intentReco.setIntents(this.privAddedLmIntents, this.privUmbrellaIntent);
}
(0, Exports_js_2.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(PhraseDetectionContext_js_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.
*/
stopContinuousRecognitionAsync(cb, err) {
(0, Exports_js_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.
*/
startKeywordRecognitionAsync(model, cb, err) {
Contracts_js_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.
*/
stopKeywordRecognitionAsync(cb, err) {
if (!!cb) {
try {
cb();
} catch (e) {
if (!!err) {
err(e);
}
}
}
}
/**
* 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.
*/
addIntent(simplePhrase, intentId) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);
Contracts_js_1.Contracts.throwIfNullOrWhitespace(intentId, "intentId");
Contracts_js_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.
*/
addIntentWithLanguageModel(intentId, model, intentName) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);
Contracts_js_1.Contracts.throwIfNullOrWhitespace(intentId, "intentId");
Contracts_js_1.Contracts.throwIfNull(model, "model");
const modelImpl = model;
Contracts_js_1.Contracts.throwIfNullOrWhitespace(modelImpl.appId, "model.appId");
this.privAddedLmIntents[intentId] = new Exports_js_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.
*/
addAllIntents(model, intentId) {
Contracts_js_1.Contracts.throwIfNull(model, "model");
const modelImpl = model;
Contracts_js_1.Contracts.throwIfNullOrWhitespace(modelImpl.appId, "model.appId");
this.privUmbrellaIntent = new Exports_js_1.AddedLmIntent(modelImpl, intentId);
}
/**
* closes all external resources held by an instance of this class.
* @member IntentRecognizer.prototype.close
* @function
* @public
*/
close(cb, errorCb) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedIntentRecognizer);
(0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, errorCb);
}
createRecognizerConfig(speechConfig) {
return new Exports_js_1.RecognizerConfig(speechConfig, this.privProperties);
}
createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) {
const audioImpl = audioConfig;
return new Exports_js_1.IntentServiceRecognizer(authentication, connectionFactory, audioImpl, recognizerConfig, this);
}
async dispose(disposing) {
if (this.privDisposedIntentRecognizer) {
return;
}
if (disposing) {
this.privDisposedIntentRecognizer = true;
await super.dispose(disposing);
}
}
buildSpeechContext() {
let appId;
let region;
let subscriptionKey;
const refGrammers = [];
if (void 0 !== this.privUmbrellaIntent) {
appId = this.privUmbrellaIntent.modelImpl.appId;
region = this.privUmbrellaIntent.modelImpl.region;
subscriptionKey = this.privUmbrellaIntent.modelImpl.subscriptionKey;
}
for (const intentId of Object.keys(this.privAddedLmIntents)) {
const addedLmIntent = this.privAddedLmIntents[intentId];
if (appId === void 0) {
appId = addedLmIntent.modelImpl.appId;
} else {
if (appId !== addedLmIntent.modelImpl.appId) {
throw new Error("Intents must all be from the same LUIS model");
}
}
if (region === void 0) {
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 === void 0) {
subscriptionKey = addedLmIntent.modelImpl.subscriptionKey;
} else {
if (subscriptionKey !== addedLmIntent.modelImpl.subscriptionKey) {
throw new Error("Intents must all use the same subscription key");
}
}
const grammer = "luis/" + appId + "-PRODUCTION#" + intentId;
refGrammers.push(grammer);
}
return {
Intent: {
id: appId,
key: subscriptionKey === void 0 ? this.privProperties.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_Key]) : subscriptionKey,
provider: "LUIS"
},
ReferenceGrammars: void 0 === this.privUmbrellaIntent ? refGrammers : ["luis/" + appId + "-PRODUCTION"]
};
}
};
exports.IntentRecognizer = IntentRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfileType.js
var require_VoiceProfileType = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfileType.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfileType = void 0;
var VoiceProfileType;
(function(VoiceProfileType2) {
VoiceProfileType2[VoiceProfileType2["TextIndependentIdentification"] = 0] = "TextIndependentIdentification";
VoiceProfileType2[VoiceProfileType2["TextDependentVerification"] = 1] = "TextDependentVerification";
VoiceProfileType2[VoiceProfileType2["TextIndependentVerification"] = 2] = "TextIndependentVerification";
})(VoiceProfileType = exports.VoiceProfileType || (exports.VoiceProfileType = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ConnectionMessage.js
var require_ConnectionMessage2 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ConnectionMessage.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionMessageImpl = exports.ConnectionMessage = void 0;
var HeaderNames_js_1 = require_HeaderNames();
var Exports_js_1 = require_Exports();
var PropertyCollection_js_1 = require_PropertyCollection();
var PropertyId_js_1 = require_PropertyId();
var ConnectionMessage = class {
};
exports.ConnectionMessage = ConnectionMessage;
var ConnectionMessageImpl = class {
constructor(message) {
this.privConnectionMessage = message;
this.privProperties = new PropertyCollection_js_1.PropertyCollection();
if (!!this.privConnectionMessage.headers[HeaderNames_js_1.HeaderNames.ConnectionId]) {
this.privProperties.setProperty(PropertyId_js_1.PropertyId.Speech_SessionId, this.privConnectionMessage.headers[HeaderNames_js_1.HeaderNames.ConnectionId]);
}
Object.keys(this.privConnectionMessage.headers).forEach((header) => {
this.privProperties.setProperty(header, this.privConnectionMessage.headers[header]);
});
}
/**
* The message path.
*/
get path() {
return this.privConnectionMessage.headers[Object.keys(this.privConnectionMessage.headers).find((key) => key.toLowerCase() === "path".toLowerCase())];
}
/**
* Checks to see if the ConnectionMessage is a text message.
* See also IsBinaryMessage().
*/
get isTextMessage() {
return this.privConnectionMessage.messageType === Exports_js_1.MessageType.Text;
}
/**
* Checks to see if the ConnectionMessage is a binary message.
* See also GetBinaryMessage().
*/
get isBinaryMessage() {
return this.privConnectionMessage.messageType === Exports_js_1.MessageType.Binary;
}
/**
* 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 TextMessage() {
return this.privConnectionMessage.textBody;
}
/**
* Gets the binary message payload.
*/
get binaryMessage() {
return this.privConnectionMessage.binaryBody;
}
/**
* 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 properties() {
return this.privProperties;
}
/**
* Returns a string that represents the connection message.
*/
toString() {
return "";
}
};
exports.ConnectionMessageImpl = ConnectionMessageImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Connection.js
var require_Connection = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Connection.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Connection = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var ConnectionMessage_js_1 = require_ConnectionMessage2();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var Connection = class _Connection {
/**
* Gets the Connection instance from the specified recognizer.
* @param recognizer The recognizer associated with the connection.
* @return The Connection instance of the recognizer.
*/
static fromRecognizer(recognizer) {
const recoBase = recognizer.internalData;
const 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.
*/
static fromSynthesizer(synthesizer) {
const synthBase = synthesizer.internalData;
const 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.
*/
openConnection(cb, err) {
(0, Exports_js_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.
*/
closeConnection(cb, err) {
if (this.privInternalData instanceof Exports_js_1.SynthesisAdapterBase) {
throw new Error("Disconnecting a synthesizer's connection is currently not supported");
} else {
(0, Exports_js_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.
*/
setMessageProperty(path, propertyName, propertyValue) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(propertyName, "propertyName");
if (this.privInternalData instanceof Exports_js_1.ServiceRecognizerBase) {
if (path.toLowerCase() !== "speech.context") {
throw new Error("Only speech.context message property sets are currently supported for recognizer");
} else {
const context = this.privInternalData.speechContext.getContext();
context[propertyName] = propertyValue;
}
} else if (this.privInternalData instanceof Exports_js_1.SynthesisAdapterBase) {
if (path.toLowerCase() !== "speech.config" && path.toLowerCase() !== "synthesis.context") {
throw new Error("Only speech.config and synthesis.context message paths are currently supported for synthesizer");
} else if (path.toLowerCase() === "speech.config") {
if (propertyName.toLowerCase() !== "context") {
throw new Error("Only context property is currently supported for speech.config message path for synthesizer");
} else {
this.privInternalData.synthesizerConfig.setContextFromJson(propertyValue);
}
} 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.
*/
sendMessageAsync(path, payload, success, error) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.privInternalData.sendNetworkMessage(path, payload), success, error);
}
/**
* Dispose of associated resources.
*/
close() {
}
setupEvents() {
this.privEventListener = this.privInternalData.connectionEvents.attach((connectionEvent) => {
if (connectionEvent.name === "ConnectionEstablishedEvent") {
if (!!this.connected) {
this.connected(new Exports_js_3.ConnectionEventArgs(connectionEvent.connectionId));
}
} else if (connectionEvent.name === "ConnectionClosedEvent") {
if (!!this.disconnected) {
this.disconnected(new Exports_js_3.ConnectionEventArgs(connectionEvent.connectionId));
}
} else if (connectionEvent.name === "ConnectionMessageSentEvent") {
if (!!this.messageSent) {
this.messageSent(new Exports_js_3.ConnectionMessageEventArgs(new ConnectionMessage_js_1.ConnectionMessageImpl(connectionEvent.message)));
}
} else if (connectionEvent.name === "ConnectionMessageReceivedEvent") {
if (!!this.messageReceived) {
this.messageReceived(new Exports_js_3.ConnectionMessageEventArgs(new ConnectionMessage_js_1.ConnectionMessageImpl(connectionEvent.message)));
}
}
});
this.privServiceEventListener = this.privInternalData.serviceEvents.attach((e) => {
if (!!this.receivedServiceMessage) {
this.receivedServiceMessage(new Exports_js_3.ServiceEventArgs(e.jsonString, e.name));
}
});
}
};
exports.Connection = Connection;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationRecognizer.js
var require_TranslationRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationRecognizer = void 0;
var Exports_js_1 = require_Exports7();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var Exports_js_2 = require_Exports();
var Connection_js_1 = require_Connection();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var TranslationRecognizer = class _TranslationRecognizer extends Exports_js_3.Recognizer {
/**
* 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
* @param {IConnectionFactory} connectionFactory - An optional connection factory to use to generate the endpoint URIs, headers to set, etc...
*/
constructor(speechConfig, audioConfig, connectionFactory) {
const configImpl = speechConfig;
Contracts_js_1.Contracts.throwIfNull(configImpl, "speechConfig");
super(audioConfig, configImpl.properties, connectionFactory || new Exports_js_1.TranslationConnectionFactory(), speechConfig.tokenCredential);
this.privDisposedTranslationRecognizer = false;
if (this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice, void 0) !== void 0) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice]);
}
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages]);
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
}
/**
* TranslationRecognizer constructor.
* @constructor
* @param {SpeechTranslationConfig} speechTranslationConfig - 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
*/
static FromConfig(speechTranslationConfig, autoDetectSourceLanguageConfig, audioConfig) {
const speechTranslationConfigImpl = speechTranslationConfig;
autoDetectSourceLanguageConfig.properties.mergeTo(speechTranslationConfigImpl.properties);
if (autoDetectSourceLanguageConfig.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, void 0) === Exports_js_1.AutoDetectSourceLanguagesOpenRangeOptionName) {
speechTranslationConfigImpl.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage, "en-US");
}
return new _TranslationRecognizer(speechTranslationConfig, audioConfig);
}
/**
* 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 speechRecognitionLanguage() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage);
}
/**
* 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 targetLanguages() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
}
/**
* Gets the name of output voice.
* @member TranslationRecognizer.prototype.voiceName
* @function
* @public
* @returns {string} the name of output voice.
*/
get voiceName() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice, void 0);
}
/**
* 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 properties() {
return this.privProperties;
}
/**
* Gets the authorization token used to communicate with the service.
* @member TranslationRecognizer.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
get authorizationToken() {
return this.properties.getProperty(Exports_js_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 authorizationToken(value) {
this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, value);
}
/**
* 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 suitable only
* 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.
*/
recognizeOnceAsync(cb, err) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
(0, Exports_js_2.marshalPromiseToCallbacks)(this.recognizeOnceAsyncImpl(PhraseDetectionContext_js_1.RecognitionMode.Interactive), 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.
*/
startContinuousRecognitionAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(PhraseDetectionContext_js_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.
*/
stopContinuousRecognitionAsync(cb, err) {
(0, Exports_js_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
*/
removeTargetLanguage(lang) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(lang, "language to be removed");
if (this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, void 0) !== void 0) {
const languages = this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
const index = languages.indexOf(lang);
if (index > -1) {
languages.splice(index, 1);
this.properties.setProperty(Exports_js_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
*/
addTargetLanguage(lang) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(lang, "language to be added");
let languages = [];
if (this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, void 0) !== void 0) {
languages = this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages).split(",");
if (!languages.includes(lang)) {
languages.push(lang);
this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, languages.join(","));
}
} else {
this.properties.setProperty(Exports_js_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
*/
close(cb, errorCb) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedTranslationRecognizer);
(0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, errorCb);
}
/**
* handles ConnectionEstablishedEvent for conversation translation scenarios.
* @member TranslationRecognizer.prototype.onConnection
* @function
* @public
*/
// eslint-disable-next-line @typescript-eslint/no-empty-function
onConnection() {
}
async dispose(disposing) {
if (this.privDisposedTranslationRecognizer) {
return;
}
this.privDisposedTranslationRecognizer = true;
if (disposing) {
await this.implRecognizerStop();
await super.dispose(disposing);
}
}
createRecognizerConfig(speechConfig) {
return new Exports_js_1.RecognizerConfig(speechConfig, this.privProperties);
}
createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) {
const configImpl = audioConfig;
return new Exports_js_1.TranslationServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);
}
updateLanguages(languages) {
const conn = Connection_js_1.Connection.fromRecognizer(this);
if (!!conn) {
conn.setMessageProperty("speech.context", "translationcontext", { to: languages });
conn.sendMessageAsync("event", JSON.stringify({
id: "translation",
name: "updateLanguage",
to: languages
}));
}
}
};
exports.TranslationRecognizer = TranslationRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Translations.js
var require_Translations = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Translations.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Translations = void 0;
var Exports_js_1 = require_Exports3();
var Translations = class {
constructor() {
this.privMap = new Exports_js_1.PropertyCollection();
}
/**
* Get the languages in the object in a String array.
* @member Translations.prototype.languages
* @function
* @public
* @returns {string[]} languages in translations object.
*/
get languages() {
return this.privMap.keys;
}
/**
* 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.
*/
get(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.
*/
set(key, value) {
this.privMap.setProperty(key, value);
}
};
exports.Translations = Translations;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/NoMatchReason.js
var require_NoMatchReason = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/NoMatchReason.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoMatchReason = void 0;
var NoMatchReason;
(function(NoMatchReason2) {
NoMatchReason2[NoMatchReason2["NotRecognized"] = 0] = "NotRecognized";
NoMatchReason2[NoMatchReason2["InitialSilenceTimeout"] = 1] = "InitialSilenceTimeout";
NoMatchReason2[NoMatchReason2["InitialBabbleTimeout"] = 2] = "InitialBabbleTimeout";
})(NoMatchReason = exports.NoMatchReason || (exports.NoMatchReason = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/NoMatchDetails.js
var require_NoMatchDetails = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/NoMatchDetails.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoMatchDetails = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports3();
var NoMatchDetails = class _NoMatchDetails {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {NoMatchReason} reason - The no-match reason.
*/
constructor(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.
*/
static fromResult(result) {
const simpleSpeech = Exports_js_1.SimpleSpeechPhrase.fromJSON(result.json, 0);
let reason = Exports_js_2.NoMatchReason.NotRecognized;
switch (simpleSpeech.RecognitionStatus) {
case Exports_js_1.RecognitionStatus.BabbleTimeout:
reason = Exports_js_2.NoMatchReason.InitialBabbleTimeout;
break;
case Exports_js_1.RecognitionStatus.InitialSilenceTimeout:
reason = Exports_js_2.NoMatchReason.InitialSilenceTimeout;
break;
default:
reason = Exports_js_2.NoMatchReason.NotRecognized;
break;
}
return new _NoMatchDetails(reason);
}
/**
* The reason the recognition was canceled.
* @member NoMatchDetails.prototype.reason
* @function
* @public
* @returns {NoMatchReason} Specifies the reason canceled.
*/
get reason() {
return this.privReason;
}
};
exports.NoMatchDetails = NoMatchDetails;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationRecognitionCanceledEventArgs.js
var require_TranslationRecognitionCanceledEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TranslationRecognitionCanceledEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationRecognitionCanceledEventArgs = void 0;
var TranslationRecognitionCanceledEventArgs = class {
/**
* 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.
*/
constructor(sessionid, cancellationReason, errorDetails, errorCode, result) {
this.privCancelReason = cancellationReason;
this.privErrorDetails = errorDetails;
this.privResult = result;
this.privSessionId = sessionid;
this.privErrorCode = errorCode;
}
/**
* Specifies the recognition result.
* @member TranslationRecognitionCanceledEventArgs.prototype.result
* @function
* @public
* @returns {TranslationRecognitionResult} the recognition result.
*/
get result() {
return this.privResult;
}
/**
* Specifies the session identifier.
* @member TranslationRecognitionCanceledEventArgs.prototype.sessionId
* @function
* @public
* @returns {string} the session identifier.
*/
get sessionId() {
return this.privSessionId;
}
/**
* The reason the recognition was canceled.
* @member TranslationRecognitionCanceledEventArgs.prototype.reason
* @function
* @public
* @returns {CancellationReason} Specifies the reason canceled.
*/
get reason() {
return this.privCancelReason;
}
/**
* 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 errorCode() {
return this.privErrorCode;
}
/**
* 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 errorDetails() {
return this.privErrorDetails;
}
};
exports.TranslationRecognitionCanceledEventArgs = TranslationRecognitionCanceledEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/IntentRecognitionCanceledEventArgs.js
var require_IntentRecognitionCanceledEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/IntentRecognitionCanceledEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentRecognitionCanceledEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var IntentRecognitionCanceledEventArgs = class extends Exports_js_1.IntentRecognitionEventArgs {
/**
* 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.
*/
constructor(reason, errorDetails, errorCode, result, offset, sessionId) {
super(result, offset, sessionId);
this.privReason = reason;
this.privErrorDetails = errorDetails;
this.privErrorCode = errorCode;
}
/**
* The reason the recognition was canceled.
* @member IntentRecognitionCanceledEventArgs.prototype.reason
* @function
* @public
* @returns {CancellationReason} Specifies the reason canceled.
*/
get reason() {
return this.privReason;
}
/**
* 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 errorCode() {
return this.privErrorCode;
}
/**
* 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 errorDetails() {
return this.privErrorDetails;
}
};
exports.IntentRecognitionCanceledEventArgs = IntentRecognitionCanceledEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CancellationDetailsBase.js
var require_CancellationDetailsBase = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CancellationDetailsBase.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancellationDetailsBase = void 0;
var CancellationDetailsBase = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {CancellationReason} reason - The cancellation reason.
* @param {string} errorDetails - The error details, if provided.
*/
constructor(reason, errorDetails, errorCode) {
this.privReason = reason;
this.privErrorDetails = errorDetails;
this.privErrorCode = errorCode;
}
/**
* The reason the recognition was canceled.
* @member CancellationDetailsBase.prototype.reason
* @function
* @public
* @returns {CancellationReason} Specifies the reason canceled.
*/
get reason() {
return this.privReason;
}
/**
* 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 errorDetails() {
return this.privErrorDetails;
}
/**
* 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 ErrorCode() {
return this.privErrorCode;
}
};
exports.CancellationDetailsBase = CancellationDetailsBase;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CancellationDetails.js
var require_CancellationDetails = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CancellationDetails.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancellationDetails = void 0;
var Exports_js_1 = require_Exports7();
var CancellationDetailsBase_js_1 = require_CancellationDetailsBase();
var Exports_js_2 = require_Exports3();
var CancellationDetails = class _CancellationDetails extends CancellationDetailsBase_js_1.CancellationDetailsBase {
constructor(reason, errorDetails, errorCode) {
super(reason, errorDetails, errorCode);
}
/**
* 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.
*/
static fromResult(result) {
let reason = Exports_js_2.CancellationReason.Error;
let errorCode = Exports_js_2.CancellationErrorCode.NoError;
if (result instanceof Exports_js_2.RecognitionResult && !!result.json) {
const simpleSpeech = Exports_js_1.SimpleSpeechPhrase.fromJSON(result.json, 0);
reason = Exports_js_1.EnumTranslation.implTranslateCancelResult(simpleSpeech.RecognitionStatus);
}
if (!!result.properties) {
errorCode = Exports_js_2.CancellationErrorCode[result.properties.getProperty(Exports_js_1.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[Exports_js_2.CancellationErrorCode.NoError])];
}
return new _CancellationDetails(reason, result.errorDetails || Exports_js_1.EnumTranslation.implTranslateErrorDetails(errorCode), errorCode);
}
};
exports.CancellationDetails = CancellationDetails;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CancellationErrorCodes.js
var require_CancellationErrorCodes = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CancellationErrorCodes.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancellationErrorCode = void 0;
var CancellationErrorCode;
(function(CancellationErrorCode2) {
CancellationErrorCode2[CancellationErrorCode2["NoError"] = 0] = "NoError";
CancellationErrorCode2[CancellationErrorCode2["AuthenticationFailure"] = 1] = "AuthenticationFailure";
CancellationErrorCode2[CancellationErrorCode2["BadRequestParameters"] = 2] = "BadRequestParameters";
CancellationErrorCode2[CancellationErrorCode2["TooManyRequests"] = 3] = "TooManyRequests";
CancellationErrorCode2[CancellationErrorCode2["ConnectionFailure"] = 4] = "ConnectionFailure";
CancellationErrorCode2[CancellationErrorCode2["ServiceTimeout"] = 5] = "ServiceTimeout";
CancellationErrorCode2[CancellationErrorCode2["ServiceError"] = 6] = "ServiceError";
CancellationErrorCode2[CancellationErrorCode2["RuntimeError"] = 7] = "RuntimeError";
CancellationErrorCode2[CancellationErrorCode2["Forbidden"] = 8] = "Forbidden";
})(CancellationErrorCode = exports.CancellationErrorCode || (exports.CancellationErrorCode = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ConnectionEventArgs.js
var require_ConnectionEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ConnectionEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var ConnectionEventArgs = class extends Exports_js_1.SessionEventArgs {
};
exports.ConnectionEventArgs = ConnectionEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ServiceEventArgs.js
var require_ServiceEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ServiceEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var ServiceEventArgs = class extends Exports_js_1.SessionEventArgs {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {string} json - json payload of the USP message.
*/
constructor(json, name, sessionId) {
super(sessionId);
this.privJsonResult = json;
this.privEventName = name;
}
get jsonString() {
return this.privJsonResult;
}
get eventName() {
return this.privEventName;
}
};
exports.ServiceEventArgs = ServiceEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PhraseListGrammar.js
var require_PhraseListGrammar = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PhraseListGrammar.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PhraseListGrammar = void 0;
var Contracts_js_1 = require_Contracts();
var PhraseListGrammar = class _PhraseListGrammar {
constructor(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.
*/
static fromRecognizer(recognizer) {
const recoBase = recognizer.internalData;
return new _PhraseListGrammar(recoBase);
}
/**
* Adds a single phrase to the current recognizer.
* @param phrase Phrase to add.
*/
addPhrase(phrase) {
this.privGrammerBuilder.addPhrase(phrase);
}
/**
* Adds multiple phrases to the current recognizer.
* @param phrases Array of phrases to add.
*/
addPhrases(phrases) {
this.privGrammerBuilder.addPhrase(phrases);
}
/**
* Clears all phrases added to the current recognizer.
*/
clear() {
this.privGrammerBuilder.clearPhrases();
}
/**
* Sets the phrase list grammar biasing weight.
* The allowed range is [0.0, 2.0].
* The default weight is 1.0. Value zero disables the phrase list.
* @param weight Phrase list grammar biasing weight.
*/
setWeight(weight) {
Contracts_js_1.Contracts.throwIfNumberOutOfRange(weight, "weight", 0, 2);
this.privGrammerBuilder.setWeight(weight);
}
};
exports.PhraseListGrammar = PhraseListGrammar;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/DialogServiceConfig.js
var require_DialogServiceConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/DialogServiceConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogServiceConfigImpl = exports.DialogServiceConfig = void 0;
var Contracts_js_1 = require_Contracts();
var Exports_js_1 = require_Exports3();
var DialogServiceConfig = class {
/**
* Creates an instance of DialogService config.
* @constructor
*/
constructor() {
return;
}
/**
* Sets the corresponding backend application identifier.
* @member DialogServiceConfig.prototype.Conversation_ApplicationId
* @function
* @public
* @param {string} value - The application identifier to set.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-function
set applicationId(value) {
}
static get DialogTypes() {
return {
BotFramework: "bot_framework",
CustomCommands: "custom_commands"
};
}
};
exports.DialogServiceConfig = DialogServiceConfig;
var DialogServiceConfigImpl = class extends DialogServiceConfig {
/**
* Creates an instance of dialogService config.
*/
constructor() {
super();
this.privSpeechConfig = new Exports_js_1.SpeechConfigImpl();
}
/**
* Provides access to custom properties.
* @member DialogServiceConfigImpl.prototype.properties
* @function
* @public
* @returns {PropertyCollection} The properties.
*/
get properties() {
return this.privSpeechConfig.properties;
}
/**
* Gets the speech recognition language.
* @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage
* @function
* @public
*/
get speechRecognitionLanguage() {
return this.privSpeechConfig.speechRecognitionLanguage;
}
/**
* Sets the speech recognition language.
* @member DialogServiceConfigImpl.prototype.speechRecognitionLanguage
* @function
* @public
* @param {string} value - The language to set.
*/
set speechRecognitionLanguage(value) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value");
this.privSpeechConfig.speechRecognitionLanguage = value;
}
get outputFormat() {
return this.privSpeechConfig.outputFormat;
}
set outputFormat(value) {
this.privSpeechConfig.outputFormat = value;
}
/**
* 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.
*/
setProperty(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.
*/
getProperty(name, def) {
void 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.
*/
setProxy(proxyHostName, proxyPort, proxyUserName, proxyPassword) {
this.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyHostName, proxyHostName);
this.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyPort, `${proxyPort}`);
if (proxyUserName) {
this.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyUserName, proxyUserName);
}
if (proxyPassword) {
this.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyPassword, proxyPassword);
}
}
setServiceProperty(name, value, channel) {
void channel;
this.privSpeechConfig.setServiceProperty(name, value);
}
/**
* Dispose of associated resources.
* @member DialogServiceConfigImpl.prototype.close
* @function
* @public
*/
close() {
return;
}
};
exports.DialogServiceConfigImpl = DialogServiceConfigImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/BotFrameworkConfig.js
var require_BotFrameworkConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/BotFrameworkConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BotFrameworkConfig = void 0;
var Contracts_js_1 = require_Contracts();
var DialogServiceConfig_js_1 = require_DialogServiceConfig();
var Exports_js_1 = require_Exports3();
var BotFrameworkConfig = class extends DialogServiceConfig_js_1.DialogServiceConfigImpl {
/**
* Creates an instance of BotFrameworkConfig.
*/
constructor() {
super();
}
/**
* 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.
*/
static fromSubscription(subscription, region, botId) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(subscription, "subscription");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region");
const botFrameworkConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl();
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.BotFramework);
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Key, subscription);
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Region, region);
if (botId) {
botFrameworkConfig.setProperty(Exports_js_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.
*/
static fromAuthorizationToken(authorizationToken, region, botId) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region");
const botFrameworkConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl();
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.BotFramework);
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceAuthorization_Token, authorizationToken);
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Region, region);
if (botId) {
botFrameworkConfig.setProperty(Exports_js_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.
*/
static fromHost(host, subscriptionKey, botId) {
void botId;
Contracts_js_1.Contracts.throwIfNullOrUndefined(host, "host");
const resolvedHost = host instanceof URL ? host : new URL(`wss://${host}.convai.speech.azure.us`);
Contracts_js_1.Contracts.throwIfNullOrUndefined(resolvedHost, "resolvedHost");
const botFrameworkConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl();
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.BotFramework);
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Host, resolvedHost.toString());
if (void 0 !== subscriptionKey) {
botFrameworkConfig.setProperty(Exports_js_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.
*/
static fromEndpoint(endpoint, subscriptionKey) {
Contracts_js_1.Contracts.throwIfNull(endpoint, "endpoint");
const botFrameworkConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl();
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.BotFramework);
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Endpoint, endpoint.toString());
if (void 0 !== subscriptionKey) {
botFrameworkConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Key, subscriptionKey);
}
return botFrameworkConfig;
}
};
exports.BotFrameworkConfig = BotFrameworkConfig;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CustomCommandsConfig.js
var require_CustomCommandsConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/CustomCommandsConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomCommandsConfig = void 0;
var Contracts_js_1 = require_Contracts();
var DialogServiceConfig_js_1 = require_DialogServiceConfig();
var Exports_js_1 = require_Exports3();
var CustomCommandsConfig = class extends DialogServiceConfig_js_1.DialogServiceConfigImpl {
/**
* Creates an instance of CustomCommandsConfig.
*/
constructor() {
super();
}
/**
* 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.
*/
static fromSubscription(applicationId, subscription, region) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(applicationId, "applicationId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(subscription, "subscription");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region");
const customCommandsConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl();
customCommandsConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.CustomCommands);
customCommandsConfig.setProperty(Exports_js_1.PropertyId.Conversation_ApplicationId, applicationId);
customCommandsConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Key, subscription);
customCommandsConfig.setProperty(Exports_js_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.
*/
static fromAuthorizationToken(applicationId, authorizationToken, region) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(applicationId, "applicationId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(authorizationToken, "authorizationToken");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(region, "region");
const customCommandsConfig = new DialogServiceConfig_js_1.DialogServiceConfigImpl();
customCommandsConfig.setProperty(Exports_js_1.PropertyId.Conversation_DialogType, DialogServiceConfig_js_1.DialogServiceConfig.DialogTypes.CustomCommands);
customCommandsConfig.setProperty(Exports_js_1.PropertyId.Conversation_ApplicationId, applicationId);
customCommandsConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceAuthorization_Token, authorizationToken);
customCommandsConfig.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_Region, region);
return customCommandsConfig;
}
/**
* Sets the corresponding backend application identifier.
* @member CustomCommandsConfig.prototype.Conversation_ApplicationId
* @function
* @public
* @param {string} value - The application identifier to set.
*/
set applicationId(value) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "value");
this.setProperty(Exports_js_1.PropertyId.Conversation_ApplicationId, value);
}
/**
* Gets the corresponding backend application identifier.
* @member CustomCommandsConfig.prototype.Conversation_ApplicationId
* @function
* @public
* @param {string} value - The application identifier to get.
*/
get applicationId() {
return this.getProperty(Exports_js_1.PropertyId.Conversation_ApplicationId);
}
};
exports.CustomCommandsConfig = CustomCommandsConfig;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/QueryParameterNames.js
var require_QueryParameterNames = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/QueryParameterNames.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.QueryParameterNames = void 0;
var QueryParameterNames = class {
};
exports.QueryParameterNames = QueryParameterNames;
QueryParameterNames.BotId = "botid";
QueryParameterNames.CustomSpeechDeploymentId = "cid";
QueryParameterNames.CustomVoiceDeploymentId = "deploymentId";
QueryParameterNames.EnableAudioLogging = "storeAudio";
QueryParameterNames.EnableLanguageId = "lidEnabled";
QueryParameterNames.EnableWordLevelTimestamps = "wordLevelTimestamps";
QueryParameterNames.EndSilenceTimeoutMs = "endSilenceTimeoutMs";
QueryParameterNames.SegmentationSilenceTimeoutMs = "segmentationSilenceTimeoutMs";
QueryParameterNames.SegmentationMaximumTimeMs = "segmentationMaximumTimeMs";
QueryParameterNames.SegmentationStrategy = "segmentationStrategy";
QueryParameterNames.Format = "format";
QueryParameterNames.InitialSilenceTimeoutMs = "initialSilenceTimeoutMs";
QueryParameterNames.Language = "language";
QueryParameterNames.Profanity = "profanity";
QueryParameterNames.RequestBotStatusMessages = "enableBotMessageStatus";
QueryParameterNames.StableIntermediateThreshold = "stableIntermediateThreshold";
QueryParameterNames.StableTranslation = "stableTranslation";
QueryParameterNames.TestHooks = "testhooks";
QueryParameterNames.Postprocessing = "postprocessing";
QueryParameterNames.CtsMeetingId = "meetingId";
QueryParameterNames.CtsDeviceId = "deviceId";
QueryParameterNames.CtsIsParticipant = "isParticipant";
QueryParameterNames.EnableAvatar = "enableTalkingAvatar";
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ConnectionFactoryBase.js
var require_ConnectionFactoryBase = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ConnectionFactoryBase.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionFactoryBase = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var Exports_js_3 = require_Exports3();
var QueryParameterNames_js_1 = require_QueryParameterNames();
var ConnectionFactoryBase = class {
static getHostSuffix(region) {
if (!!region) {
if (region.toLowerCase().startsWith("china")) {
return ".azure.cn";
}
if (region.toLowerCase().startsWith("usgov")) {
return ".azure.us";
}
}
return ".microsoft.com";
}
setCommonUrlParams(config, queryParams, endpoint) {
const propertyIdToParameterMap = /* @__PURE__ */ new Map([
[Exports_js_3.PropertyId.Speech_SegmentationSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.SegmentationSilenceTimeoutMs],
[Exports_js_3.PropertyId.SpeechServiceConnection_EnableAudioLogging, QueryParameterNames_js_1.QueryParameterNames.EnableAudioLogging],
[Exports_js_3.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.EndSilenceTimeoutMs],
[Exports_js_3.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.InitialSilenceTimeoutMs],
[Exports_js_3.PropertyId.SpeechServiceResponse_PostProcessingOption, QueryParameterNames_js_1.QueryParameterNames.Postprocessing],
[Exports_js_3.PropertyId.SpeechServiceResponse_ProfanityOption, QueryParameterNames_js_1.QueryParameterNames.Profanity],
[Exports_js_3.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, QueryParameterNames_js_1.QueryParameterNames.EnableWordLevelTimestamps],
[Exports_js_3.PropertyId.SpeechServiceResponse_StablePartialResultThreshold, QueryParameterNames_js_1.QueryParameterNames.StableIntermediateThreshold]
]);
propertyIdToParameterMap.forEach((parameterName, propertyId) => {
this.setUrlParameter(propertyId, parameterName, config, queryParams, endpoint);
});
const serviceProperties = JSON.parse(config.parameters.getProperty(Exports_js_1.ServicePropertiesPropertyName, "{}"));
Object.keys(serviceProperties).forEach((value) => {
queryParams[value] = serviceProperties[value];
});
}
setUrlParameter(propId, parameterName, config, queryParams, endpoint) {
const value = config.parameters.getProperty(propId, void 0);
if (value && (!endpoint || endpoint.search(parameterName) === -1)) {
queryParams[parameterName] = value.toLocaleLowerCase();
}
}
static async getRedirectUrlFromEndpoint(endpoint) {
const redirectUrl = new URL(endpoint);
redirectUrl.protocol = "https:";
redirectUrl.port = "443";
const params = redirectUrl.searchParams;
params.append("GenerateRedirectResponse", "true");
const redirectedUrlString = redirectUrl.toString();
Exports_js_2.Events.instance.onEvent(new Exports_js_2.ConnectionRedirectEvent("", redirectedUrlString, void 0, "ConnectionFactoryBase: redirectUrl request"));
const redirectResponse = await fetch(redirectedUrlString);
if (redirectResponse.status !== 200) {
return endpoint;
}
const redirectUrlString = await redirectResponse.text();
Exports_js_2.Events.instance.onEvent(new Exports_js_2.ConnectionRedirectEvent("", redirectUrlString, endpoint, "ConnectionFactoryBase: redirectUrlString"));
try {
return new URL(redirectUrlString.trim()).toString();
} catch (error) {
return endpoint;
}
}
};
exports.ConnectionFactoryBase = ConnectionFactoryBase;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/DialogConnectorFactory.js
var require_DialogConnectorFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/DialogConnectorFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogConnectionFactory = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports7();
var Exports_js_3 = require_Exports3();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var Exports_js_4 = require_Exports7();
var HeaderNames_js_1 = require_HeaderNames();
var QueryParameterNames_js_1 = require_QueryParameterNames();
var DialogConnectionFactory = class _DialogConnectionFactory extends ConnectionFactoryBase_js_1.ConnectionFactoryBase {
create(config, authInfo, connectionId) {
const applicationId = config.parameters.getProperty(Exports_js_3.PropertyId.Conversation_ApplicationId, "");
const dialogType = config.parameters.getProperty(Exports_js_3.PropertyId.Conversation_DialogType);
const region = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Region);
const language = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage, "en-US");
const requestTurnStatus = config.parameters.getProperty(Exports_js_3.PropertyId.Conversation_Request_Bot_Status_Messages, "true");
const queryParams = {};
queryParams[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId;
queryParams[QueryParameterNames_js_1.QueryParameterNames.Format] = config.parameters.getProperty(Exports_js_2.OutputFormatPropertyName, Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]).toLowerCase();
queryParams[QueryParameterNames_js_1.QueryParameterNames.Language] = language;
queryParams[QueryParameterNames_js_1.QueryParameterNames.RequestBotStatusMessages] = requestTurnStatus;
if (applicationId) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.BotId] = applicationId;
if (dialogType === Exports_js_3.DialogServiceConfig.DialogTypes.CustomCommands) {
queryParams[HeaderNames_js_1.HeaderNames.CustomCommandsAppId] = applicationId;
}
}
const resourceInfix = dialogType === Exports_js_3.DialogServiceConfig.DialogTypes.CustomCommands ? "commands/" : "";
const version = dialogType === Exports_js_3.DialogServiceConfig.DialogTypes.CustomCommands ? "v1" : dialogType === Exports_js_3.DialogServiceConfig.DialogTypes.BotFramework ? "v3" : "v0";
const headers = {};
if (authInfo.token != null && authInfo.token !== "") {
headers[authInfo.headerName] = authInfo.token;
}
let endpoint = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Endpoint, "");
if (!endpoint) {
const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region);
const host = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Host, `wss://${region}.${_DialogConnectionFactory.BaseUrl}${hostSuffix}`);
const standardizedHost = host.endsWith("/") ? host : host + "/";
endpoint = `${standardizedHost}${resourceInfix}${_DialogConnectionFactory.ApiKey}/${version}`;
}
this.setCommonUrlParams(config, queryParams, endpoint);
const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
return Promise.resolve(new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_4.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId));
}
};
exports.DialogConnectionFactory = DialogConnectionFactory;
DialogConnectionFactory.ApiKey = "api";
DialogConnectionFactory.BaseUrl = "convai.speech";
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/DialogServiceConnector.js
var require_DialogServiceConnector = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/DialogServiceConnector.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogServiceConnector = void 0;
var DialogConnectorFactory_js_1 = require_DialogConnectorFactory();
var Exports_js_1 = require_Exports7();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var PropertyId_js_1 = require_PropertyId();
var DialogServiceConnector = class extends Exports_js_3.Recognizer {
/**
* 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
*/
constructor(dialogConfig, audioConfig) {
const dialogServiceConfigImpl = dialogConfig;
Contracts_js_1.Contracts.throwIfNull(dialogConfig, "dialogConfig");
super(audioConfig, dialogServiceConfigImpl.properties, new DialogConnectorFactory_js_1.DialogConnectionFactory());
this.isTurnComplete = true;
this.privIsDisposed = false;
this.privProperties = dialogServiceConfigImpl.properties.clone();
const agentConfig = this.buildAgentConfig();
this.privReco.agentConfig.set(agentConfig);
}
/**
* 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
*/
connect(cb, err) {
(0, Exports_js_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.
*/
disconnect(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.privReco.disconnect(), cb, err);
}
/**
* Gets the authorization token used to communicate with the service.
* @member DialogServiceConnector.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
get authorizationToken() {
return this.properties.getProperty(PropertyId_js_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 authorizationToken(token) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token");
this.properties.setProperty(PropertyId_js_1.PropertyId.SpeechServiceAuthorization_Token, token);
}
/**
* 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 properties() {
return this.privProperties;
}
/** 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 speechActivityTemplate() {
return this.properties.getProperty(PropertyId_js_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 speechActivityTemplate(speechActivityTemplate) {
this.properties.setProperty(PropertyId_js_1.PropertyId.Conversation_Speech_Activity_Template, speechActivityTemplate);
}
/**
* 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.
*/
listenOnceAsync(cb, err) {
if (this.isTurnComplete) {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
const callbackHolder = async () => {
await this.privReco.connect();
await this.implRecognizerStop();
this.isTurnComplete = false;
const ret = new Exports_js_2.Deferred();
await this.privReco.recognize(PhraseDetectionContext_js_1.RecognitionMode.Conversation, ret.resolve, ret.reject);
const e = await ret.promise;
await this.implRecognizerStop();
return e;
};
const retPromise = callbackHolder();
retPromise.catch(() => {
this.dispose(true).catch(() => {
});
});
(0, Exports_js_2.marshalPromiseToCallbacks)(retPromise.finally(() => {
this.isTurnComplete = true;
}), cb, err);
}
}
sendActivityAsync(activity, cb, errCb) {
(0, Exports_js_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
*/
close(cb, err) {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
(0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, err);
}
async dispose(disposing) {
if (this.privIsDisposed) {
return;
}
if (disposing) {
this.privIsDisposed = true;
await this.implRecognizerStop();
await super.dispose(disposing);
}
}
createRecognizerConfig(speechConfig) {
return new Exports_js_1.RecognizerConfig(speechConfig, this.privProperties);
}
createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) {
const audioSource = audioConfig;
return new Exports_js_1.DialogServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this);
}
buildAgentConfig() {
const communicationType = this.properties.getProperty("Conversation_Communication_Type", "Default");
return {
botInfo: {
commType: communicationType,
commandsCulture: void 0,
connectionId: this.properties.getProperty(PropertyId_js_1.PropertyId.Conversation_Agent_Connection_Id),
conversationId: this.properties.getProperty(PropertyId_js_1.PropertyId.Conversation_Conversation_Id, void 0),
fromId: this.properties.getProperty(PropertyId_js_1.PropertyId.Conversation_From_Id, void 0),
ttsAudioFormat: this.properties.getProperty(PropertyId_js_1.PropertyId.SpeechServiceConnection_SynthOutputFormat, void 0)
},
version: 0.2
};
}
};
exports.DialogServiceConnector = DialogServiceConnector;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ActivityReceivedEventArgs.js
var require_ActivityReceivedEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ActivityReceivedEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ActivityReceivedEventArgs = void 0;
var ActivityReceivedEventArgs = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {any} activity - The activity..
*/
constructor(activity, audioStream) {
this.privActivity = activity;
this.privAudioStream = audioStream;
}
/**
* Gets the received activity
* @member ActivityReceivedEventArgs.prototype.activity
* @function
* @public
* @returns {any} the received activity.
*/
get activity() {
return this.privActivity;
}
get audioStream() {
return this.privAudioStream;
}
};
exports.ActivityReceivedEventArgs = ActivityReceivedEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/TurnStatusPayload.js
var require_TurnStatusPayload = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/TurnStatusPayload.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TurnStatusResponsePayload = void 0;
var TurnStatusResponsePayload = class _TurnStatusResponsePayload {
constructor(json) {
this.privMessageStatusResponse = JSON.parse(json);
}
static fromJSON(json) {
return new _TurnStatusResponsePayload(json);
}
get interactionId() {
return this.privMessageStatusResponse.interactionId;
}
get conversationId() {
return this.privMessageStatusResponse.conversationId;
}
get statusCode() {
switch (this.privMessageStatusResponse.statusCode) {
case "Success":
return 200;
case "Failed":
return 400;
case "TimedOut":
return 429;
default:
return this.privMessageStatusResponse.statusCode;
}
}
};
exports.TurnStatusResponsePayload = TurnStatusResponsePayload;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TurnStatusReceivedEventArgs.js
var require_TurnStatusReceivedEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/TurnStatusReceivedEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TurnStatusReceivedEventArgs = void 0;
var TurnStatusPayload_js_1 = require_TurnStatusPayload();
var TurnStatusReceivedEventArgs = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {string} turnStatus - The JSON-encoded turn status message.
*/
constructor(turnStatus) {
this.privTurnStatus = TurnStatusPayload_js_1.TurnStatusResponsePayload.fromJSON(turnStatus);
}
/**
* Gets the interaction identifier associated with this turn status event.
* @member TurnStatusReceivedEventArgs.prototype.interactionId
* @function
* @public
* @returns {any} the received interaction id.
*/
get interactionId() {
return this.privTurnStatus.interactionId;
}
/**
* Gets the conversation identifier associated with this turn status event.
* @member TurnStatusReceivedEventArgs.prototype.conversationId
* @function
* @public
* @returns {any} the received conversation id.
*/
get conversationId() {
return this.privTurnStatus.conversationId;
}
/**
* Gets the received turn status code.
* @member TurnStatusReceivedEventArgs.prototype.statusCode
* @function
* @public
* @returns {number} the received turn status.
*/
get statusCode() {
return this.privTurnStatus.statusCode;
}
};
exports.TurnStatusReceivedEventArgs = TurnStatusReceivedEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ServicePropertyChannel.js
var require_ServicePropertyChannel = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ServicePropertyChannel.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServicePropertyChannel = void 0;
var ServicePropertyChannel;
(function(ServicePropertyChannel2) {
ServicePropertyChannel2[ServicePropertyChannel2["UriQueryParameter"] = 0] = "UriQueryParameter";
})(ServicePropertyChannel = exports.ServicePropertyChannel || (exports.ServicePropertyChannel = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ProfanityOption.js
var require_ProfanityOption = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ProfanityOption.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProfanityOption = void 0;
var ProfanityOption;
(function(ProfanityOption2) {
ProfanityOption2[ProfanityOption2["Masked"] = 0] = "Masked";
ProfanityOption2[ProfanityOption2["Removed"] = 1] = "Removed";
ProfanityOption2[ProfanityOption2["Raw"] = 2] = "Raw";
})(ProfanityOption = exports.ProfanityOption || (exports.ProfanityOption = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/BaseAudioPlayer.js
var require_BaseAudioPlayer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/BaseAudioPlayer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseAudioPlayer = void 0;
var Error_js_1 = require_Error();
var Exports_js_1 = require_Exports3();
var AudioStreamFormat_js_1 = require_AudioStreamFormat();
var BaseAudioPlayer = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {AudioStreamFormat} audioFormat audio stream format recognized by the player.
*/
constructor(audioFormat) {
this.audioContext = null;
this.gainNode = null;
this.autoUpdateBufferTimer = 0;
if (audioFormat === void 0) {
audioFormat = Exports_js_1.AudioStreamFormat.getDefaultInputFormat();
}
this.init(audioFormat);
}
/**
* play Audio sample
* @param newAudioData audio data to be played.
*/
playAudioSample(newAudioData, cb, err) {
try {
this.ensureInitializedContext();
const audioData = this.formatAudioData(newAudioData);
const newSamplesData = new Float32Array(this.samples.length + audioData.length);
newSamplesData.set(this.samples, 0);
newSamplesData.set(audioData, this.samples.length);
this.samples = newSamplesData;
if (!!cb) {
cb();
}
} catch (e) {
if (!!err) {
err(e);
}
}
}
/**
* stops audio and clears the buffers
*/
stopAudio(cb, err) {
if (this.audioContext !== null) {
this.samples = new Float32Array();
clearInterval(this.autoUpdateBufferTimer);
this.audioContext.close().then(() => {
if (!!cb) {
cb();
}
}, (error) => {
if (!!err) {
err(error);
}
});
this.audioContext = null;
}
}
init(audioFormat) {
this.audioFormat = audioFormat;
this.samples = new Float32Array();
}
ensureInitializedContext() {
if (this.audioContext === null) {
this.createAudioContext();
const timerPeriod = 200;
this.autoUpdateBufferTimer = setInterval(() => {
this.updateAudioBuffer();
}, timerPeriod);
}
}
createAudioContext() {
this.audioContext = AudioStreamFormat_js_1.AudioStreamFormatImpl.getAudioContext();
this.gainNode = this.audioContext.createGain();
this.gainNode.gain.value = 1;
this.gainNode.connect(this.audioContext.destination);
this.startTime = this.audioContext.currentTime;
}
formatAudioData(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_js_1.InvalidOperationError("Only WAVE_FORMAT_PCM (8/16/32 bps) format supported at this time");
}
}
formatArrayBuffer(audioData, maxValue2) {
const float32Data = new Float32Array(audioData.length);
for (let i = 0; i < audioData.length; i++) {
float32Data[i] = audioData[i] / maxValue2;
}
return float32Data;
}
updateAudioBuffer() {
if (this.samples.length === 0) {
return;
}
const channelCount = this.audioFormat.channels;
const bufferSource = this.audioContext.createBufferSource();
const frameCount = this.samples.length / channelCount;
const audioBuffer = this.audioContext.createBuffer(channelCount, frameCount, this.audioFormat.samplesPerSec);
for (let channel = 0; channel < channelCount; channel++) {
let channelOffset = channel;
const audioData = audioBuffer.getChannelData(channel);
for (let 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);
this.startTime += audioBuffer.duration;
this.samples = new Float32Array();
}
async playAudio(audioData) {
if (this.audioContext === null) {
this.createAudioContext();
}
const source = this.audioContext.createBufferSource();
const destination = this.audioContext.destination;
await this.audioContext.decodeAudioData(audioData, (newBuffer) => {
source.buffer = newBuffer;
source.connect(destination);
source.start(0);
});
}
};
exports.BaseAudioPlayer = BaseAudioPlayer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ConnectionMessageEventArgs.js
var require_ConnectionMessageEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ConnectionMessageEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionMessageEventArgs = void 0;
var ConnectionMessageEventArgs = class {
constructor(message) {
this.privConnectionMessage = message;
}
/**
* Gets the <see cref="ConnectionMessage"/> associated with this <see cref="ConnectionMessageEventArgs"/>.
*/
get message() {
return this.privConnectionMessage;
}
/**
* Returns a string that represents the connection message event.
*/
toString() {
return "Message: " + this.privConnectionMessage.toString();
}
};
exports.ConnectionMessageEventArgs = ConnectionMessageEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfile.js
var require_VoiceProfile = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfile.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfile = void 0;
var VoiceProfile = class {
/**
* 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.
*/
constructor(profileId, profileType) {
this.privId = profileId;
this.privProfileType = profileType;
}
/**
* profileId of this Voice Profile instance
* @member VoiceProfile.prototype.profileId
* @function
* @public
* @returns {string} profileId of this Voice Profile instance.
*/
get profileId() {
return this.privId;
}
/**
* profileType of this Voice Profile instance
* @member VoiceProfile.prototype.profileType
* @function
* @public
* @returns {VoiceProfileType} profile type of this Voice Profile instance.
*/
get profileType() {
return this.privProfileType;
}
};
exports.VoiceProfile = VoiceProfile;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfileEnrollmentResult.js
var require_VoiceProfileEnrollmentResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfileEnrollmentResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfileEnrollmentCancellationDetails = exports.VoiceProfileEnrollmentResult = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports3();
var VoiceProfileEnrollmentResult = class _VoiceProfileEnrollmentResult {
constructor(reason, json, statusText) {
this.privReason = reason;
this.privProperties = new Exports_js_2.PropertyCollection();
if (this.privReason !== Exports_js_2.ResultReason.Canceled) {
if (!!json) {
this.privDetails = JSON.parse(json);
if (this.privDetails.enrollmentStatus.toLowerCase() === "enrolling") {
this.privReason = Exports_js_2.ResultReason.EnrollingVoiceProfile;
}
}
} else {
this.privErrorDetails = statusText;
this.privProperties.setProperty(Exports_js_1.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[Exports_js_2.CancellationErrorCode.ServiceError]);
}
}
get reason() {
return this.privReason;
}
get enrollmentsCount() {
return this.privDetails.enrollmentsCount;
}
get enrollmentsLength() {
return this.privDetails.enrollmentsLength;
}
get properties() {
return this.privProperties;
}
get enrollmentResultDetails() {
return this.privDetails;
}
get errorDetails() {
return this.privErrorDetails;
}
static FromIdentificationProfileList(json) {
const results = [];
for (const item of json.value) {
const reason = item.enrollmentStatus.toLowerCase() === "enrolling" ? Exports_js_2.ResultReason.EnrollingVoiceProfile : item.enrollmentStatus.toLowerCase() === "enrolled" ? Exports_js_2.ResultReason.EnrolledVoiceProfile : Exports_js_2.ResultReason.Canceled;
const result = new _VoiceProfileEnrollmentResult(reason, null, null);
result.privDetails = this.getIdentificationDetails(item);
results.push(result);
}
return results;
}
static FromVerificationProfileList(json) {
const results = [];
for (const item of json.value) {
const reason = item.enrollmentStatus.toLowerCase() === "enrolling" ? Exports_js_2.ResultReason.EnrollingVoiceProfile : item.enrollmentStatus.toLowerCase() === "enrolled" ? Exports_js_2.ResultReason.EnrolledVoiceProfile : Exports_js_2.ResultReason.Canceled;
const result = new _VoiceProfileEnrollmentResult(reason, null, null);
result.privDetails = this.getVerificationDetails(item);
results.push(result);
}
return results;
}
static getIdentificationDetails(json) {
return {
audioLength: json.audioLength ? parseFloat(json.audioLength) : 0,
audioSpeechLength: json.audioSpeechLength ? parseFloat(json.audioSpeechLength) : 0,
enrollmentStatus: json.enrollmentStatus,
enrollmentsCount: json.enrollmentsCount || 0,
enrollmentsLength: json.enrollmentsLength ? parseFloat(json.enrollmentsLength) : 0,
enrollmentsSpeechLength: json.enrollmentsSpeechLength ? parseFloat(json.enrollmentsSpeechLength) : 0,
profileId: json.profileId || json.identificationProfileId,
remainingEnrollmentsSpeechLength: json.remainingEnrollmentsSpeechLength ? parseFloat(json.remainingEnrollmentsSpeechLength) : 0
};
}
static getVerificationDetails(json) {
return {
audioLength: json.audioLength ? parseFloat(json.audioLength) : 0,
audioSpeechLength: json.audioSpeechLength ? parseFloat(json.audioSpeechLength) : 0,
enrollmentStatus: json.enrollmentStatus,
enrollmentsCount: json.enrollmentsCount,
enrollmentsLength: json.enrollmentsLength ? parseFloat(json.enrollmentsLength) : 0,
enrollmentsSpeechLength: json.enrollmentsSpeechLength ? parseFloat(json.enrollmentsSpeechLength) : 0,
profileId: json.profileId || json.verificationProfileId,
remainingEnrollmentsCount: json.remainingEnrollments || json.remainingEnrollmentsCount,
remainingEnrollmentsSpeechLength: json.remainingEnrollmentsSpeechLength ? parseFloat(json.remainingEnrollmentsSpeechLength) : 0
};
}
};
exports.VoiceProfileEnrollmentResult = VoiceProfileEnrollmentResult;
var VoiceProfileEnrollmentCancellationDetails = class _VoiceProfileEnrollmentCancellationDetails extends Exports_js_2.CancellationDetailsBase {
constructor(reason, errorDetails, errorCode) {
super(reason, errorDetails, errorCode);
}
/**
* 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.
*/
static fromResult(result) {
const reason = Exports_js_2.CancellationReason.Error;
let errorCode = Exports_js_2.CancellationErrorCode.NoError;
if (!!result.properties) {
errorCode = Exports_js_2.CancellationErrorCode[result.properties.getProperty(Exports_js_1.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[Exports_js_2.CancellationErrorCode.NoError])];
}
return new _VoiceProfileEnrollmentCancellationDetails(reason, result.errorDetails, errorCode);
}
};
exports.VoiceProfileEnrollmentCancellationDetails = VoiceProfileEnrollmentCancellationDetails;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfileResult.js
var require_VoiceProfileResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfileResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfileCancellationDetails = exports.VoiceProfileResult = void 0;
var Exports_js_1 = require_Exports7();
var Contracts_js_1 = require_Contracts();
var Exports_js_2 = require_Exports3();
var VoiceProfileResult = class {
constructor(reason, statusText) {
this.privReason = reason;
this.privProperties = new Exports_js_2.PropertyCollection();
if (reason === Exports_js_2.ResultReason.Canceled) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(statusText, "statusText");
this.privErrorDetails = statusText;
this.privProperties.setProperty(Exports_js_1.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[Exports_js_2.CancellationErrorCode.ServiceError]);
}
}
get reason() {
return this.privReason;
}
get properties() {
return this.privProperties;
}
get errorDetails() {
return this.privErrorDetails;
}
};
exports.VoiceProfileResult = VoiceProfileResult;
var VoiceProfileCancellationDetails = class _VoiceProfileCancellationDetails extends Exports_js_2.CancellationDetailsBase {
constructor(reason, errorDetails, errorCode) {
super(reason, errorDetails, errorCode);
}
/**
* 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.
*/
static fromResult(result) {
const reason = Exports_js_2.CancellationReason.Error;
let errorCode = Exports_js_2.CancellationErrorCode.NoError;
if (!!result.properties) {
errorCode = Exports_js_2.CancellationErrorCode[result.properties.getProperty(Exports_js_1.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[Exports_js_2.CancellationErrorCode.NoError])];
}
return new _VoiceProfileCancellationDetails(reason, result.errorDetails, errorCode);
}
};
exports.VoiceProfileCancellationDetails = VoiceProfileCancellationDetails;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfilePhraseResult.js
var require_VoiceProfilePhraseResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfilePhraseResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfilePhraseResult = void 0;
var Contracts_js_1 = require_Contracts();
var Exports_js_1 = require_Exports3();
var VoiceProfilePhraseResult = class extends Exports_js_1.VoiceProfileResult {
constructor(reason, statusText, type, phraseArray) {
super(reason, statusText);
this.privPhrases = [];
Contracts_js_1.Contracts.throwIfNullOrUndefined(phraseArray, "phrase array");
this.privType = type;
if (!!phraseArray && !!phraseArray[0]) {
this.privPhrases = phraseArray;
}
}
get phrases() {
return this.privPhrases;
}
get type() {
return this.privType;
}
};
exports.VoiceProfilePhraseResult = VoiceProfilePhraseResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfileClient.js
var require_VoiceProfileClient = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceProfileClient.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfileClient = void 0;
var Exports_js_1 = require_Exports7();
var AudioConfig_js_1 = require_AudioConfig();
var Contracts_js_1 = require_Contracts();
var Exports_js_2 = require_Exports3();
var VoiceProfileClient = class extends Exports_js_2.Recognizer {
/**
* VoiceProfileClient constructor.
* @constructor
* @param {SpeechConfig} speechConfig - An set of initial properties for this synthesizer (authentication key, region, &c)
*/
constructor(speechConfig) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig, "speechConfig");
const speechConfigImpl = speechConfig;
Contracts_js_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig");
super(AudioConfig_js_1.AudioConfig.fromStreamInput(Exports_js_2.AudioInputStream.createPushStream()), speechConfigImpl.properties, new Exports_js_1.VoiceProfileConnectionFactory());
this.privProperties = speechConfigImpl.properties.clone();
this.privVoiceAdapter = this.privReco;
this.privDisposedVoiceAdapter = false;
}
/**
* 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 properties() {
return this.privProperties;
}
/**
* Gets the authorization token used to communicate with the service.
* @member VoiceProfileClient.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
get authorizationToken() {
return this.properties.getProperty(Exports_js_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 authorizationToken(token) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token");
this.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token, token);
}
/**
* Create a speaker recognition voice profile
* @member VoiceProfileClient.prototype.createProfileAsync
* @function
* @public
* @async
* @param {VoiceProfileType} profileType Type of Voice Profile to be created
* @param {string} lang Language string (locale) for Voice Profile
* @return {Promise<VoiceProfile>} - Promise of a VoiceProfile.
*/
async createProfileAsync(profileType, lang) {
const profileIds = await this.privVoiceAdapter.createProfile(profileType, lang);
return new Exports_js_2.VoiceProfile(profileIds[0], profileType);
}
/**
* 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.
*/
async retrieveEnrollmentResultAsync(profile) {
return this.privVoiceAdapter.retrieveEnrollmentResult(profile);
}
/**
* 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.
*/
async getAllProfilesAsync(profileType) {
return this.privVoiceAdapter.getAllProfiles(profileType);
}
/**
* Get valid authorization phrases for voice profile enrollment
* @member VoiceProfileClient.prototype.getActivationPhrasesAsync
* @function
* @public
* @async
* @param {VoiceProfileType} profileType Profile Type to get activation phrases for
* @param {string} lang Language string (locale) for Voice Profile
*/
async getActivationPhrasesAsync(profileType, lang) {
return this.privVoiceAdapter.getActivationPhrases(profileType, lang);
}
/**
* 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.
*/
async enrollProfileAsync(profile, audioConfig) {
const configImpl = audioConfig;
Contracts_js_1.Contracts.throwIfNullOrUndefined(configImpl, "audioConfig");
this.audioConfig = audioConfig;
this.privVoiceAdapter.SpeakerAudioSource = configImpl;
return this.privVoiceAdapter.enrollProfile(profile);
}
/**
* 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.
*/
async deleteProfileAsync(profile) {
return this.privVoiceAdapter.deleteProfile(profile);
}
/**
* 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.
*/
async resetProfileAsync(profile) {
return this.privVoiceAdapter.resetProfile(profile);
}
/**
* Clean up object and close underlying connection
* @member VoiceProfileClient.prototype.close
* @function
* @async
* @public
*/
async close() {
await this.dispose(true);
}
createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) {
const audioImpl = audioConfig;
return new Exports_js_1.VoiceServiceRecognizer(authentication, connectionFactory, audioImpl, recognizerConfig, this);
}
async dispose(disposing) {
if (this.privDisposedVoiceAdapter) {
return;
}
this.privDisposedVoiceAdapter = true;
if (disposing) {
await super.dispose(disposing);
}
}
createRecognizerConfig(speechConfig) {
return new Exports_js_1.RecognizerConfig(speechConfig, this.properties);
}
getResult(result, successReason) {
const response = new Exports_js_2.VoiceProfileResult(result.ok ? successReason : Exports_js_2.ResultReason.Canceled, result.statusText);
return response;
}
};
exports.VoiceProfileClient = VoiceProfileClient;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeakerRecognizer.js
var require_SpeakerRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeakerRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerRecognizer = void 0;
var Exports_js_1 = require_Exports7();
var Contracts_js_1 = require_Contracts();
var Exports_js_2 = require_Exports3();
var SpeakerRecognizer = class extends Exports_js_2.Recognizer {
/**
* Initializes an instance of the SpeakerRecognizer.
* @constructor
* @param {SpeechConfig} speechConfig - The set of configuration properties.
* @param {AudioConfig} audioConfig - An optional audio input config associated with the recognizer
*/
constructor(speechConfig, audioConfig) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig, "speechConfig");
const configImpl = speechConfig;
Contracts_js_1.Contracts.throwIfNullOrUndefined(configImpl, "speechConfig");
super(audioConfig, configImpl.properties, new Exports_js_1.SpeakerRecognitionConnectionFactory());
this.privAudioConfigImpl = audioConfig;
Contracts_js_1.Contracts.throwIfNull(this.privAudioConfigImpl, "audioConfig");
this.privDisposedSpeakerRecognizer = false;
this.privProperties = configImpl.properties;
}
/**
* Gets the authorization token used to communicate with the service.
* @member SpeakerRecognizer.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
get authorizationToken() {
return this.properties.getProperty(Exports_js_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 authorizationToken(token) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token");
this.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token, token);
}
/**
* 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 properties() {
return this.privProperties;
}
/**
* Get recognition result for model using given audio
* @member SpeakerRecognizer.prototype.recognizeOnceAsync
* @function
* @public
* @async
* @param {SpeakerIdentificationModel | SpeakerVerificationModel} 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.
*/
async recognizeOnceAsync(model) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedSpeakerRecognizer);
return this.recognizeSpeakerOnceAsyncImpl(model);
}
/**
* Included for compatibility
* @member SpeakerRecognizer.prototype.close
* @function
* @public
* @async
*/
async close() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedSpeakerRecognizer);
await this.dispose(true);
}
async recognizeSpeakerOnceAsyncImpl(model) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedSpeakerRecognizer);
await this.implRecognizerStop();
const result = await this.privReco.recognizeSpeaker(model);
await this.implRecognizerStop();
return result;
}
async implRecognizerStop() {
if (this.privReco) {
await this.privReco.stopRecognizing();
}
return;
}
createRecognizerConfig(speechConfig) {
return new Exports_js_1.RecognizerConfig(speechConfig, this.privProperties);
}
createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) {
const audioImpl = audioConfig;
return new Exports_js_1.SpeakerServiceRecognizer(authentication, connectionFactory, audioImpl, recognizerConfig, this);
}
async dispose(disposing) {
if (this.privDisposedSpeakerRecognizer) {
return;
}
if (disposing) {
this.privDisposedSpeakerRecognizer = true;
await super.dispose(disposing);
}
}
};
exports.SpeakerRecognizer = SpeakerRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeakerIdentificationModel.js
var require_SpeakerIdentificationModel = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeakerIdentificationModel.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerIdentificationModel = void 0;
var Contracts_js_1 = require_Contracts();
var Exports_js_1 = require_Exports3();
var SpeakerIdentificationModel = class _SpeakerIdentificationModel {
constructor(profiles) {
this.privVoiceProfiles = [];
this.privProfileIds = [];
Contracts_js_1.Contracts.throwIfNullOrUndefined(profiles, "VoiceProfiles");
if (profiles.length === 0) {
throw new Error("Empty Voice Profiles array");
}
for (const profile of profiles) {
if (profile.profileType !== Exports_js_1.VoiceProfileType.TextIndependentIdentification) {
throw new Error("Identification model can only be created from Identification profile: " + profile.profileId);
}
this.privVoiceProfiles.push(profile);
this.privProfileIds.push(profile.profileId);
}
}
static fromProfiles(profiles) {
return new _SpeakerIdentificationModel(profiles);
}
get voiceProfileIds() {
return this.privProfileIds.join(",");
}
get profileIds() {
return this.privProfileIds;
}
get scenario() {
return "TextIndependentIdentification";
}
};
exports.SpeakerIdentificationModel = SpeakerIdentificationModel;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeakerVerificationModel.js
var require_SpeakerVerificationModel = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeakerVerificationModel.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerVerificationModel = void 0;
var Contracts_js_1 = require_Contracts();
var Exports_js_1 = require_Exports3();
var SpeakerVerificationModel = class _SpeakerVerificationModel {
constructor(profile) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(profile, "VoiceProfile");
if (profile.profileType === Exports_js_1.VoiceProfileType.TextIndependentIdentification) {
throw new Error("Verification model cannot be created from Identification profile");
}
this.privVoiceProfile = profile;
}
static fromProfile(profile) {
return new _SpeakerVerificationModel(profile);
}
get voiceProfile() {
return this.privVoiceProfile;
}
get profileIds() {
return [this.voiceProfile.profileId];
}
get scenario() {
if (this.voiceProfile.profileType === Exports_js_1.VoiceProfileType.TextDependentVerification) {
return "TextDependentVerification";
} else {
return "TextIndependentVerification";
}
}
};
exports.SpeakerVerificationModel = SpeakerVerificationModel;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/LanguageIdMode.js
var require_LanguageIdMode = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/LanguageIdMode.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LanguageIdMode = void 0;
var LanguageIdMode;
(function(LanguageIdMode2) {
LanguageIdMode2[LanguageIdMode2["AtStart"] = 0] = "AtStart";
LanguageIdMode2[LanguageIdMode2["Continuous"] = 1] = "Continuous";
})(LanguageIdMode = exports.LanguageIdMode || (exports.LanguageIdMode = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AutoDetectSourceLanguageConfig.js
var require_AutoDetectSourceLanguageConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AutoDetectSourceLanguageConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutoDetectSourceLanguageConfig = void 0;
var Exports_js_1 = require_Exports7();
var Contracts_js_1 = require_Contracts();
var Exports_js_2 = require_Exports3();
var LanguageIdMode_js_1 = require_LanguageIdMode();
var AutoDetectSourceLanguageConfig = class _AutoDetectSourceLanguageConfig {
constructor() {
this.privProperties = new Exports_js_2.PropertyCollection();
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_LanguageIdMode, "AtStart");
this.privLanguageIdMode = LanguageIdMode_js_1.LanguageIdMode.AtStart;
}
/**
* @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.
*/
static fromOpenRange() {
const config = new _AutoDetectSourceLanguageConfig();
config.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, Exports_js_1.AutoDetectSourceLanguagesOpenRangeOptionName);
config.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, "en-US");
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.
*/
static fromLanguages(languages) {
Contracts_js_1.Contracts.throwIfArrayEmptyOrWhitespace(languages, "languages");
const config = new _AutoDetectSourceLanguageConfig();
config.properties.setProperty(Exports_js_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.
*/
static fromSourceLanguageConfigs(configs) {
if (configs.length < 1) {
throw new Error("Expected non-empty SourceLanguageConfig array.");
}
const autoConfig = new _AutoDetectSourceLanguageConfig();
const langs = [];
configs.forEach((config) => {
langs.push(config.language);
if (config.endpointId !== void 0 && config.endpointId !== "") {
const customProperty = config.language + Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId.toString();
autoConfig.properties.setProperty(customProperty, config.endpointId);
}
});
autoConfig.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, langs.join());
return autoConfig;
}
/**
* @member AutoDetectSourceLanguageConfig.prototype.properties
* @function
* @public
* @return {PropertyCollection} Properties of the config.
* @summary Gets an auto detected language config properties
*/
get properties() {
return this.privProperties;
}
/**
* @member AutoDetectSourceLanguageConfig.prototype.mode
* @function
* @public
* @param {LanguageIdMode} mode LID mode desired.
* @summary Sets LID operation to desired mode
*/
set mode(mode) {
if (mode === LanguageIdMode_js_1.LanguageIdMode.Continuous) {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, "2");
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_LanguageIdMode, "Continuous");
} else {
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, "1");
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_LanguageIdMode, "AtStart");
}
this.privLanguageIdMode = mode;
}
};
exports.AutoDetectSourceLanguageConfig = AutoDetectSourceLanguageConfig;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AutoDetectSourceLanguageResult.js
var require_AutoDetectSourceLanguageResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AutoDetectSourceLanguageResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutoDetectSourceLanguageResult = void 0;
var Contracts_js_1 = require_Contracts();
var AutoDetectSourceLanguageResult = class _AutoDetectSourceLanguageResult {
constructor(language, languageDetectionConfidence) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(language, "language");
Contracts_js_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.
*/
static fromResult(result) {
return new _AutoDetectSourceLanguageResult(result.language, result.languageDetectionConfidence);
}
/**
* Creates an instance of AutoDetectSourceLanguageResult object from a ConversationTranscriptionResult instance.
* @member AutoDetectSourceLanguageResult.fromConversationTranscriptionResult
* @function
* @public
* @param {ConversationTranscriptionResult} result - The transcription result.
* @returns {AutoDetectSourceLanguageResult} AutoDetectSourceLanguageResult object being created.
*/
static fromConversationTranscriptionResult(result) {
return new _AutoDetectSourceLanguageResult(result.language, result.languageDetectionConfidence);
}
get language() {
return this.privLanguage;
}
get languageDetectionConfidence() {
return this.privLanguageDetectionConfidence;
}
};
exports.AutoDetectSourceLanguageResult = AutoDetectSourceLanguageResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SourceLanguageConfig.js
var require_SourceLanguageConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SourceLanguageConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SourceLanguageConfig = void 0;
var Contracts_js_1 = require_Contracts();
var SourceLanguageConfig = class _SourceLanguageConfig {
constructor(language, endpointId) {
Contracts_js_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.
*/
static fromLanguage(language, endpointId) {
return new _SourceLanguageConfig(language, endpointId);
}
get language() {
return this.privLanguage;
}
get endpointId() {
return this.privEndpointId;
}
};
exports.SourceLanguageConfig = SourceLanguageConfig;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeakerRecognitionResult.js
var require_SpeakerRecognitionResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeakerRecognitionResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerRecognitionCancellationDetails = exports.SpeakerRecognitionResult = exports.SpeakerRecognitionResultType = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports3();
var SpeakerRecognitionResultType;
(function(SpeakerRecognitionResultType2) {
SpeakerRecognitionResultType2[SpeakerRecognitionResultType2["Verify"] = 0] = "Verify";
SpeakerRecognitionResultType2[SpeakerRecognitionResultType2["Identify"] = 1] = "Identify";
})(SpeakerRecognitionResultType = exports.SpeakerRecognitionResultType || (exports.SpeakerRecognitionResultType = {}));
var SpeakerRecognitionResult = class {
constructor(response, resultReason = Exports_js_2.ResultReason.RecognizedSpeaker, cancellationErrorCode = Exports_js_2.CancellationErrorCode.NoError, errorDetails = "") {
this.privProperties = new Exports_js_2.PropertyCollection();
const resultType = response.scenario === "TextIndependentIdentification" ? SpeakerRecognitionResultType.Identify : SpeakerRecognitionResultType.Verify;
this.privReason = resultReason;
if (this.privReason !== Exports_js_2.ResultReason.Canceled) {
if (resultType === SpeakerRecognitionResultType.Identify) {
this.privProfileId = response.identificationResult.identifiedProfile.profileId;
this.privScore = response.identificationResult.identifiedProfile.score;
this.privReason = Exports_js_2.ResultReason.RecognizedSpeakers;
} else {
this.privScore = response.verificationResult.score;
if (response.verificationResult.recognitionResult.toLowerCase() !== "accept") {
this.privReason = Exports_js_2.ResultReason.NoMatch;
}
if (response.verificationResult.profileId !== void 0 && response.verificationResult.profileId !== "") {
this.privProfileId = response.verificationResult.profileId;
}
}
} else {
this.privErrorDetails = errorDetails;
this.privProperties.setProperty(Exports_js_1.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[cancellationErrorCode]);
}
this.privProperties.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_JsonResult, JSON.stringify(response));
}
get properties() {
return this.privProperties;
}
get reason() {
return this.privReason;
}
get profileId() {
return this.privProfileId;
}
get errorDetails() {
return this.privErrorDetails;
}
get score() {
return this.privScore;
}
};
exports.SpeakerRecognitionResult = SpeakerRecognitionResult;
var SpeakerRecognitionCancellationDetails = class _SpeakerRecognitionCancellationDetails extends Exports_js_2.CancellationDetailsBase {
constructor(reason, errorDetails, errorCode) {
super(reason, errorDetails, errorCode);
}
/**
* 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.
*/
static fromResult(result) {
const reason = Exports_js_2.CancellationReason.Error;
let errorCode = Exports_js_2.CancellationErrorCode.NoError;
if (!!result.properties) {
errorCode = Exports_js_2.CancellationErrorCode[result.properties.getProperty(Exports_js_1.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[Exports_js_2.CancellationErrorCode.NoError])];
}
return new _SpeakerRecognitionCancellationDetails(reason, result.errorDetails, errorCode);
}
};
exports.SpeakerRecognitionCancellationDetails = SpeakerRecognitionCancellationDetails;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/Conversation.js
var require_Conversation = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/Conversation.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationImpl = exports.Conversation = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var Conversation = class {
constructor() {
return;
}
/**
* Create a conversation
* @param speechConfig
* @param cb
* @param err
*/
static createConversationAsync(speechConfig, arg2, arg3, arg4) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig, Exports_js_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "config"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig.region, Exports_js_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "SpeechServiceConnection_Region"));
if (!speechConfig.subscriptionKey && !speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceAuthorization_Token])) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig.subscriptionKey, Exports_js_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "SpeechServiceConnection_Key"));
}
let conversationImpl;
let cb;
let err;
if (typeof arg2 === "string") {
conversationImpl = new ConversationImpl(speechConfig, arg2);
(0, Exports_js_2.marshalPromiseToCallbacks)((async () => {
})(), arg3, arg4);
} else {
conversationImpl = new ConversationImpl(speechConfig);
cb = arg2;
err = arg3;
conversationImpl.createConversationAsync(() => {
if (!!cb) {
cb();
}
}, (error) => {
if (!!err) {
err(error);
}
});
}
return conversationImpl;
}
};
exports.Conversation = Conversation;
var ConversationImpl = class extends Conversation {
/**
* Create a conversation impl
* @param speechConfig
* @param {string} id - optional conversationId
*/
constructor(speechConfig, id) {
super();
this.privErrors = Exports_js_1.ConversationConnectionConfig.restErrors;
this.onConnected = (e) => {
this.privIsConnected = true;
try {
if (!!this.privConversationTranslator?.sessionStarted) {
this.privConversationTranslator.sessionStarted(this.privConversationTranslator, e);
}
} catch (e2) {
}
};
this.onDisconnected = (e) => {
try {
if (!!this.privConversationTranslator?.sessionStopped) {
this.privConversationTranslator.sessionStopped(this.privConversationTranslator, e);
}
} catch (e2) {
} finally {
void this.close(false);
}
};
this.onCanceled = (r, e) => {
try {
if (!!this.privConversationTranslator?.canceled) {
this.privConversationTranslator.canceled(this.privConversationTranslator, e);
}
} catch (e2) {
}
};
this.onParticipantUpdateCommandReceived = (r, e) => {
try {
const updatedParticipant = this.privParticipants.getParticipant(e.id);
if (updatedParticipant !== void 0) {
switch (e.key) {
case Exports_js_1.ConversationTranslatorCommandTypes.changeNickname:
updatedParticipant.displayName = e.value;
break;
case Exports_js_1.ConversationTranslatorCommandTypes.setUseTTS:
updatedParticipant.isUsingTts = e.value;
break;
case Exports_js_1.ConversationTranslatorCommandTypes.setProfanityFiltering:
updatedParticipant.profanity = e.value;
break;
case Exports_js_1.ConversationTranslatorCommandTypes.setMute:
updatedParticipant.isMuted = e.value;
break;
case Exports_js_1.ConversationTranslatorCommandTypes.setTranslateToLanguages:
updatedParticipant.translateToLanguages = e.value;
break;
}
this.privParticipants.addOrUpdateParticipant(updatedParticipant);
if (!!this.privConversationTranslator) {
this.privConversationTranslator.participantsChanged(this.privConversationTranslator, new Exports_js_3.ConversationParticipantsChangedEventArgs(Exports_js_3.ParticipantChangedReason.Updated, [this.toParticipant(updatedParticipant)], e.sessionId));
}
}
} catch (e2) {
}
};
this.onLockRoomCommandReceived = () => {
};
this.onMuteAllCommandReceived = (r, e) => {
try {
this.privParticipants.participants.forEach((p) => p.isMuted = p.isHost ? false : e.isMuted);
if (!!this.privConversationTranslator) {
this.privConversationTranslator.participantsChanged(this.privConversationTranslator, new Exports_js_3.ConversationParticipantsChangedEventArgs(Exports_js_3.ParticipantChangedReason.Updated, this.toParticipants(false), e.sessionId));
}
} catch (e2) {
}
};
this.onParticipantJoinCommandReceived = (r, e) => {
try {
const newParticipant = this.privParticipants.addOrUpdateParticipant(e.participant);
if (newParticipant !== void 0) {
if (!!this.privConversationTranslator) {
this.privConversationTranslator.participantsChanged(this.privConversationTranslator, new Exports_js_3.ConversationParticipantsChangedEventArgs(Exports_js_3.ParticipantChangedReason.JoinedConversation, [this.toParticipant(newParticipant)], e.sessionId));
}
}
} catch (e2) {
}
};
this.onParticipantLeaveCommandReceived = (r, e) => {
try {
const ejectedParticipant = this.privParticipants.getParticipant(e.participant.id);
if (ejectedParticipant !== void 0) {
this.privParticipants.deleteParticipant(e.participant.id);
if (!!this.privConversationTranslator) {
this.privConversationTranslator.participantsChanged(this.privConversationTranslator, new Exports_js_3.ConversationParticipantsChangedEventArgs(Exports_js_3.ParticipantChangedReason.LeftConversation, [this.toParticipant(ejectedParticipant)], e.sessionId));
}
}
} catch (e2) {
}
};
this.onTranslationReceived = (r, e) => {
try {
switch (e.command) {
case Exports_js_1.ConversationTranslatorMessageTypes.final:
if (!!this.privConversationTranslator) {
this.privConversationTranslator.transcribed(this.privConversationTranslator, new Exports_js_3.ConversationTranslationEventArgs(e.payload, void 0, e.sessionId));
}
break;
case Exports_js_1.ConversationTranslatorMessageTypes.partial:
if (!!this.privConversationTranslator) {
this.privConversationTranslator.transcribing(this.privConversationTranslator, new Exports_js_3.ConversationTranslationEventArgs(e.payload, void 0, e.sessionId));
}
break;
case Exports_js_1.ConversationTranslatorMessageTypes.instantMessage:
if (!!this.privConversationTranslator) {
this.privConversationTranslator.textMessageReceived(this.privConversationTranslator, new Exports_js_3.ConversationTranslationEventArgs(e.payload, void 0, e.sessionId));
}
break;
}
} catch (e2) {
}
};
this.onParticipantsListReceived = (r, e) => {
try {
if (e.sessionToken !== void 0 && e.sessionToken !== null) {
this.privRoom.token = e.sessionToken;
}
this.privParticipants.participants = [...e.participants];
if (this.privParticipants.me !== void 0) {
this.privIsReady = true;
}
if (!!this.privConversationTranslator) {
this.privConversationTranslator.participantsChanged(this.privConversationTranslator, new Exports_js_3.ConversationParticipantsChangedEventArgs(Exports_js_3.ParticipantChangedReason.JoinedConversation, this.toParticipants(true), e.sessionId));
}
if (this.me.isHost) {
const nickname = this.privConversationTranslator?.properties.getProperty(Exports_js_3.PropertyId.ConversationTranslator_Name);
if (nickname !== void 0 && nickname.length > 0 && nickname !== this.me.displayName) {
this.changeNicknameAsync(nickname);
}
}
} catch (e2) {
}
};
this.onConversationExpiration = (r, e) => {
try {
if (!!this.privConversationTranslator) {
this.privConversationTranslator.conversationExpiration(this.privConversationTranslator, e);
}
} catch (e2) {
}
};
this.privIsConnected = false;
this.privIsDisposed = false;
this.privConversationId = "";
this.privProperties = new Exports_js_3.PropertyCollection();
this.privManager = new Exports_js_1.ConversationManager();
const language = speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
if (!language) {
speechConfig.setProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage], Exports_js_1.ConversationConnectionConfig.defaultLanguageCode);
}
this.privLanguage = speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
if (!id) {
if (speechConfig.targetLanguages.length === 0) {
speechConfig.addTargetLanguage(this.privLanguage);
}
const profanity = speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceResponse_ProfanityOption]);
if (!profanity) {
speechConfig.setProfanity(Exports_js_3.ProfanityOption.Masked);
}
let hostNickname = speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.ConversationTranslator_Name]);
if (hostNickname === void 0 || hostNickname === null) {
hostNickname = "Host";
}
Contracts_js_1.Contracts.throwIfNullOrTooLong(hostNickname, "nickname", 50);
Contracts_js_1.Contracts.throwIfNullOrTooShort(hostNickname, "nickname", 2);
speechConfig.setProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.ConversationTranslator_Name], hostNickname);
} else {
this.privConversationId = id;
}
this.privConfig = speechConfig;
const configImpl = speechConfig;
Contracts_js_1.Contracts.throwIfNull(configImpl, "speechConfig");
this.privProperties = configImpl.properties.clone();
this.privIsConnected = false;
this.privParticipants = new Exports_js_1.InternalParticipants();
this.privIsReady = false;
this.privTextMessageMaxLength = 1e3;
}
// get the internal data about a conversation
get room() {
return this.privRoom;
}
// get the wrapper for connecting to the websockets
get connection() {
return this.privConversationRecognizer;
}
// get the config
get config() {
return this.privConfig;
}
// get the conversation Id
get conversationId() {
return this.privRoom ? this.privRoom.roomId : this.privConversationId;
}
// get the properties
get properties() {
return this.privProperties;
}
// get the speech language
get speechRecognitionLanguage() {
return this.privLanguage;
}
get isMutedByHost() {
return this.privParticipants.me?.isHost ? false : this.privParticipants.me?.isMuted;
}
get isConnected() {
return this.privIsConnected && this.privIsReady;
}
get participants() {
return this.toParticipants(true);
}
get me() {
return this.toParticipant(this.privParticipants.me);
}
get host() {
return this.toParticipant(this.privParticipants.host);
}
get transcriberRecognizer() {
return this.privTranscriberRecognizer;
}
get conversationInfo() {
const convId = this.conversationId;
const p = this.participants.map((part) => ({
id: part.id,
preferredLanguage: part.preferredLanguage,
voice: part.voice
}));
const props = {};
for (const key of Exports_js_1.ConversationConnectionConfig.transcriptionEventKeys) {
const val = this.properties.getProperty(key, "");
if (val !== "") {
props[key] = val;
}
}
const info = { id: convId, participants: p, conversationProperties: props };
return info;
}
get canSend() {
return this.privIsConnected && !this.privParticipants.me?.isMuted;
}
get canSendAsHost() {
return this.privIsConnected && this.privParticipants.me?.isHost;
}
// get / set the speech auth token
// eslint-disable-next-line @typescript-eslint/member-ordering
get authorizationToken() {
return this.privToken;
}
set authorizationToken(value) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "authorizationToken");
this.privToken = value;
}
set conversationTranslator(conversationTranslator) {
this.privConversationTranslator = conversationTranslator;
}
onToken(token) {
this.privConversationTranslator.onToken(token);
}
/**
* Create a new conversation as Host
* @param cb
* @param err
*/
createConversationAsync(cb, err) {
try {
if (!!this.privConversationRecognizer) {
this.handleError(new Error(this.privErrors.permissionDeniedStart), err);
}
this.privManager.createOrJoin(this.privProperties, void 0, (room) => {
if (!room) {
this.handleError(new Error(this.privErrors.permissionDeniedConnect), err);
}
this.privRoom = room;
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
} catch (error) {
this.handleError(error, err);
}
}
/**
* Starts a new conversation as host.
* @param cb
* @param err
*/
startConversationAsync(cb, err) {
try {
if (!!this.privConversationRecognizer) {
this.handleError(new Error(this.privErrors.permissionDeniedStart), err);
}
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedConnect);
this.privParticipants.meId = this.privRoom.participantId;
this.privConversationRecognizer = Exports_js_1.ConversationRecognizerFactory.fromConfig(this, this.privConfig);
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, () => {
this.handleCallback(cb, err);
}, (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
*/
addParticipantAsync(participant, cb, err) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(participant, "Participant");
(0, Exports_js_2.marshalPromiseToCallbacks)(this.addParticipantImplAsync(participant), cb, err);
}
/**
* Join a conversation as a participant.
* @param conversation
* @param nickname
* @param lang
* @param cb
* @param err
*/
joinConversationAsync(conversationId, nickname, lang, cb, err) {
try {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(conversationId, this.privErrors.invalidArgs.replace("{arg}", "conversationId"));
Contracts_js_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname"));
Contracts_js_1.Contracts.throwIfNullOrWhitespace(lang, this.privErrors.invalidArgs.replace("{arg}", "language"));
this.privManager.createOrJoin(this.privProperties, conversationId, (room) => {
Contracts_js_1.Contracts.throwIfNullOrUndefined(room, this.privErrors.permissionDeniedConnect);
this.privRoom = room;
this.privConfig.authorizationToken = room.cognitiveSpeechAuthToken;
if (!!cb) {
cb(room.cognitiveSpeechAuthToken);
}
}, (error) => {
this.handleError(error, err);
});
} catch (error) {
this.handleError(error, err);
}
}
/**
* Deletes a conversation
* @param cb
* @param err
*/
deleteConversationAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.deleteConversationImplAsync(), cb, err);
}
async deleteConversationImplAsync() {
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privProperties, this.privErrors.permissionDeniedConnect);
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.token, this.privErrors.permissionDeniedConnect);
await this.privManager.leave(this.privProperties, this.privRoom.token);
this.dispose();
}
/**
* Issues a request to close the client websockets
* @param cb
* @param err
*/
endConversationAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.endConversationImplAsync(), cb, err);
}
endConversationImplAsync() {
return this.close(true);
}
/**
* Issues a request to lock the conversation
* @param cb
* @param err
*/
lockConversationAsync(cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSendAsHost) {
this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "lock")), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getLockCommand(true), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Issues a request to mute the conversation
* @param cb
* @param err
*/
muteAllParticipantsAsync(cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privConversationRecognizer, this.privErrors.permissionDeniedSend);
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSendAsHost) {
this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "mute")), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getMuteAllCommand(true), () => {
this.handleCallback(cb, err);
}, (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
*/
muteParticipantAsync(userId, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrWhitespace(userId, this.privErrors.invalidArgs.replace("{arg}", "userId"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSend) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
if (!this.me.isHost && this.me.id !== userId) {
this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "mute")), err);
}
const exists = this.privParticipants.getParticipantIndex(userId);
if (exists === -1) {
this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getMuteCommand(userId, true), () => {
this.handleCallback(cb, err);
}, (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
*/
removeParticipantAsync(userId, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
if (!!this.privTranscriberRecognizer && userId.hasOwnProperty("id")) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.removeParticipantImplAsync(userId), cb, err);
} else {
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSendAsHost) {
this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "remove")), err);
}
let participantId = "";
if (typeof userId === "string") {
participantId = userId;
} else if (userId.hasOwnProperty("id")) {
const participant = userId;
participantId = participant.id;
} else if (userId.hasOwnProperty("userId")) {
const user = userId;
participantId = user.userId;
}
Contracts_js_1.Contracts.throwIfNullOrWhitespace(participantId, this.privErrors.invalidArgs.replace("{arg}", "userId"));
const index = this.participants.findIndex((p) => p.id === participantId);
if (index === -1) {
this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getEjectCommand(participantId), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Issues a request to unlock the conversation
* @param cb
* @param err
*/
unlockConversationAsync(cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSendAsHost) {
this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "unlock")), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getLockCommand(false), () => {
this.handleCallback(cb, err);
}, (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
*/
unmuteAllParticipantsAsync(cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSendAsHost) {
this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "unmute all")), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getMuteAllCommand(false), () => {
this.handleCallback(cb, err);
}, (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
*/
unmuteParticipantAsync(userId, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrWhitespace(userId, this.privErrors.invalidArgs.replace("{arg}", "userId"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSend) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
if (!this.me.isHost && this.me.id !== userId) {
this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "mute")), err);
}
const exists = this.privParticipants.getParticipantIndex(userId);
if (exists === -1) {
this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getMuteCommand(userId, false), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Send a text message
* @param message
* @param cb
* @param err
*/
sendTextMessageAsync(message, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrWhitespace(message, this.privErrors.invalidArgs.replace("{arg}", "message"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSend) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
if (message.length > this.privTextMessageMaxLength) {
this.handleError(new Error(this.privErrors.invalidArgs.replace("{arg}", "message length")), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getMessageCommand(message), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Set translated to languages
* @param {string[]} languages - languages to translate to
* @param cb
* @param err
*/
setTranslatedLanguagesAsync(languages, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfArrayEmptyOrWhitespace(languages, this.privErrors.invalidArgs.replace("{arg}", "languages"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSend) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getSetTranslateToLanguagesCommand(languages), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Change nickname
* @param {string} nickname - new nickname for the room
* @param cb
* @param err
*/
changeNicknameAsync(nickname, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSend) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getChangeNicknameCommand(nickname), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
isDisposed() {
return this.privIsDisposed;
}
dispose() {
if (this.isDisposed) {
return;
}
this.privIsDisposed = true;
if (!!this.config) {
this.config.close();
}
this.privConfig = void 0;
this.privLanguage = void 0;
this.privProperties = void 0;
this.privRoom = void 0;
this.privToken = void 0;
this.privManager = void 0;
this.privIsConnected = false;
this.privIsReady = false;
this.privParticipants = void 0;
}
async connectTranscriberRecognizer(recognizer) {
if (!!this.privTranscriberRecognizer) {
await this.privTranscriberRecognizer.close();
}
await recognizer.enforceAudioGating();
this.privTranscriberRecognizer = recognizer;
this.privTranscriberRecognizer.conversation = this;
}
getKeepAlive() {
const nickname = !!this.me ? this.me.displayName : "default_nickname";
return JSON.stringify({
id: "0",
nickname,
participantId: this.privRoom.participantId,
roomId: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.keepAlive
});
}
/* eslint-enable @typescript-eslint/typedef */
addParticipantImplAsync(participant) {
const newParticipant = this.privParticipants.addOrUpdateParticipant(participant);
if (newParticipant !== void 0) {
if (!!this.privTranscriberRecognizer) {
const conversationInfo = this.conversationInfo;
conversationInfo.participants = [participant];
return this.privTranscriberRecognizer.pushConversationEvent(conversationInfo, "join");
}
}
}
removeParticipantImplAsync(participant) {
this.privParticipants.deleteParticipant(participant.id);
const conversationInfo = this.conversationInfo;
conversationInfo.participants = [participant];
return this.privTranscriberRecognizer.pushConversationEvent(conversationInfo, "leave");
}
async close(dispose) {
try {
this.privIsConnected = false;
await this.privConversationRecognizer?.close();
this.privConversationRecognizer = void 0;
if (!!this.privConversationTranslator) {
this.privConversationTranslator.dispose();
}
} catch (e) {
throw e;
}
if (dispose) {
this.dispose();
}
}
/** Helpers */
handleCallback(cb, err) {
if (!!cb) {
try {
cb();
} catch (e) {
if (!!err) {
err(e);
}
}
cb = void 0;
}
}
handleError(error, err) {
if (!!err) {
if (error instanceof Error) {
const typedError = error;
err(typedError.name + ": " + typedError.message);
} else {
err(error);
}
}
}
/** Participant Helpers */
toParticipants(includeHost) {
const participants = this.privParticipants.participants.map((p) => this.toParticipant(p));
if (!includeHost) {
return participants.filter((p) => p.isHost === false);
} else {
return participants;
}
}
toParticipant(p) {
return new Exports_js_3.Participant(p.id, p.avatar, p.displayName, p.isHost, p.isMuted, p.isUsingTts, p.preferredLanguage, p.voice);
}
getMuteAllCommand(isMuted) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.setMuteAll,
participantId: this.privRoom.participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand,
value: isMuted
});
}
getMuteCommand(participantId, isMuted) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.setMute,
// eslint-disable-next-line object-shorthand
participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand,
value: isMuted
});
}
getLockCommand(isLocked) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.setLockState,
participantId: this.privRoom.participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand,
value: isLocked
});
}
getEjectCommand(participantId) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.ejectParticipant,
// eslint-disable-next-line object-shorthand
participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand
});
}
getSetTranslateToLanguagesCommand(languages) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.setTranslateToLanguages,
participantId: this.privRoom.participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand,
value: languages
});
}
getChangeNicknameCommand(nickname) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(nickname, "nickname");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.changeNickname,
nickname,
participantId: this.privRoom.participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand,
value: nickname
});
}
getMessageCommand(message) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(message, "message");
return JSON.stringify({
participantId: this.privRoom.participantId,
roomId: this.privRoom.roomId,
text: message,
type: Exports_js_1.ConversationTranslatorMessageTypes.instantMessage
});
}
};
exports.ConversationImpl = ConversationImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationCommon.js
var require_ConversationCommon = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationCommon.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationCommon = void 0;
var ConversationCommon = class {
constructor(audioConfig) {
this.privAudioConfig = audioConfig;
}
handleCallback(cb, err) {
if (!!cb) {
try {
cb();
} catch (e) {
if (!!err) {
err(e);
}
}
cb = void 0;
}
}
handleError(error, err) {
if (!!err) {
if (error instanceof Error) {
const typedError = error;
err(typedError.name + ": " + typedError.message);
} else {
err(error);
}
}
}
};
exports.ConversationCommon = ConversationCommon;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationExpirationEventArgs.js
var require_ConversationExpirationEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationExpirationEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationExpirationEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var ConversationExpirationEventArgs = class extends Exports_js_1.SessionEventArgs {
constructor(expirationTime, sessionId) {
super(sessionId);
this.privExpirationTime = expirationTime;
}
/** How much longer until the conversation expires (in minutes). */
get expirationTime() {
return this.privExpirationTime;
}
};
exports.ConversationExpirationEventArgs = ConversationExpirationEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationParticipantsChangedEventArgs.js
var require_ConversationParticipantsChangedEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationParticipantsChangedEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationParticipantsChangedEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var ConversationParticipantsChangedEventArgs = class extends Exports_js_1.SessionEventArgs {
constructor(reason, participants, sessionId) {
super(sessionId);
this.privReason = reason;
this.privParticipant = participants;
}
get reason() {
return this.privReason;
}
get participants() {
return this.privParticipant;
}
};
exports.ConversationParticipantsChangedEventArgs = ConversationParticipantsChangedEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranslationCanceledEventArgs.js
var require_ConversationTranslationCanceledEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranslationCanceledEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslationCanceledEventArgs = void 0;
var CancellationEventArgsBase_js_1 = require_CancellationEventArgsBase();
var ConversationTranslationCanceledEventArgs = class extends CancellationEventArgsBase_js_1.CancellationEventArgsBase {
};
exports.ConversationTranslationCanceledEventArgs = ConversationTranslationCanceledEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranslationEventArgs.js
var require_ConversationTranslationEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranslationEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslationEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var ConversationTranslationEventArgs = class extends Exports_js_1.RecognitionEventArgs {
/**
* 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.
*/
constructor(result, offset, sessionId) {
super(offset, sessionId);
this.privResult = result;
}
/**
* Specifies the recognition result.
* @returns {ConversationTranslationResult} the recognition result.
*/
get result() {
return this.privResult;
}
};
exports.ConversationTranslationEventArgs = ConversationTranslationEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranslationResult.js
var require_ConversationTranslationResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranslationResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslationResult = void 0;
var TranslationRecognitionResult_js_1 = require_TranslationRecognitionResult();
var ConversationTranslationResult = class extends TranslationRecognitionResult_js_1.TranslationRecognitionResult {
constructor(participantId, translations, originalLanguage, resultId, reason, text, duration, offset, errorDetails, json, properties) {
super(translations, resultId, reason, text, duration, offset, void 0, void 0, errorDetails, json, properties);
this.privId = participantId;
this.privOrigLang = originalLanguage;
}
/**
* The unique identifier for the participant this result is for.
*/
get participantId() {
return this.privId;
}
/**
* The original language this result was in.
*/
get originalLang() {
return this.privOrigLang;
}
};
exports.ConversationTranslationResult = ConversationTranslationResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/StringUtils.js
var require_StringUtils = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common/StringUtils.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StringUtils = void 0;
var StringUtils = class {
/**
* Formats a string by replacing the named {keys} in the string with the values contained in the replacement dictionary.
* @param format The format string that contains the parts to replace surrounded by {}. For example: "wss://{region}.cts.speech.microsoft.com".
* If your string needs to contain a { or } you can use the {{ and }} escape sequences respectively.
* @param replacements The dictionary of replacements. If a replacement is not found, it is replaced with an empty string
* @returns The formatted string. If you pass in a null or undefined format string, an empty string will be returned
*/
static formatString(format2, replacements) {
if (!format2) {
return "";
}
if (!replacements) {
return format2;
}
let formatted = "";
let key = "";
const appendToFormatted = (str) => {
formatted += str;
};
const appendToKey = (str) => {
key += str;
};
let appendFunc = appendToFormatted;
for (let i = 0; i < format2.length; i++) {
const c = format2[i];
const next = i + 1 < format2.length ? format2[i + 1] : "";
switch (c) {
case "{":
if (next === "{") {
appendFunc("{");
i++;
} else {
appendFunc = appendToKey;
}
break;
case "}":
if (next === "}") {
appendFunc("}");
i++;
} else {
if (replacements.hasOwnProperty(key)) {
formatted += replacements[key];
}
appendFunc = appendToFormatted;
key = "";
}
break;
default:
appendFunc(c);
break;
}
}
return formatted;
}
};
exports.StringUtils = StringUtils;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationTranslatorConnectionFactory.js
var require_ConversationTranslatorConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationTranslatorConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslatorConnectionFactory = void 0;
var Exports_js_1 = require_Exports4();
var StringUtils_js_1 = require_StringUtils();
var Contracts_js_1 = require_Contracts();
var Exports_js_2 = require_Exports3();
var HeaderNames_js_1 = require_HeaderNames();
var QueryParameterNames_js_1 = require_QueryParameterNames();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var Exports_js_3 = require_Exports7();
var ConversationTranslatorConnectionFactory = class _ConversationTranslatorConnectionFactory extends ConnectionFactoryBase_js_1.ConnectionFactoryBase {
constructor(convGetter) {
super();
Contracts_js_1.Contracts.throwIfNullOrUndefined(convGetter, "convGetter");
this.privConvGetter = convGetter;
}
create(config, authInfo, connectionId) {
const isVirtMicArrayEndpoint = config.parameters.getProperty("ConversationTranslator_MultiChannelAudio", "").toUpperCase() === "TRUE";
const convInfo = this.privConvGetter().room;
const region = convInfo.cognitiveSpeechRegion || config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, "");
const replacementValues = {
hostSuffix: ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region),
path: _ConversationTranslatorConnectionFactory.CTS_VIRT_MIC_PATH,
region: encodeURIComponent(region)
};
replacementValues[QueryParameterNames_js_1.QueryParameterNames.Language] = encodeURIComponent(config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, ""));
replacementValues[QueryParameterNames_js_1.QueryParameterNames.CtsMeetingId] = encodeURIComponent(convInfo.roomId);
replacementValues[QueryParameterNames_js_1.QueryParameterNames.CtsDeviceId] = encodeURIComponent(convInfo.participantId);
replacementValues[QueryParameterNames_js_1.QueryParameterNames.CtsIsParticipant] = convInfo.isHost ? "" : "&" + QueryParameterNames_js_1.QueryParameterNames.CtsIsParticipant;
let endpointUrl = "";
const queryParams = {};
const headers = {};
if (isVirtMicArrayEndpoint) {
endpointUrl = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint);
if (!endpointUrl) {
const hostName = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, "transcribe.{region}.cts.speech{hostSuffix}");
endpointUrl = "wss://" + hostName + "{path}";
}
endpointUrl = StringUtils_js_1.StringUtils.formatString(endpointUrl, replacementValues);
const parsedUrl = new URL(endpointUrl);
parsedUrl.searchParams.forEach((val, key) => {
queryParams[key] = val;
});
const connFactory = new Exports_js_3.TranscriberConnectionFactory();
connFactory.setQueryParams(queryParams, config, endpointUrl);
queryParams[QueryParameterNames_js_1.QueryParameterNames.CtsMeetingId] = replacementValues[QueryParameterNames_js_1.QueryParameterNames.CtsMeetingId];
queryParams[QueryParameterNames_js_1.QueryParameterNames.CtsDeviceId] = replacementValues[QueryParameterNames_js_1.QueryParameterNames.CtsDeviceId];
if (!convInfo.isHost) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.CtsIsParticipant] = "";
}
if (!(QueryParameterNames_js_1.QueryParameterNames.Format in queryParams)) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.Format] = "simple";
}
parsedUrl.searchParams.forEach((val, key) => {
parsedUrl.searchParams.set(key, queryParams[key]);
delete queryParams[key];
});
endpointUrl = parsedUrl.toString();
} else {
const connFactory = new Exports_js_3.TranslationConnectionFactory();
endpointUrl = connFactory.getEndpointUrl(config, true);
endpointUrl = StringUtils_js_1.StringUtils.formatString(endpointUrl, replacementValues);
connFactory.setQueryParams(queryParams, config, endpointUrl);
}
headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId;
headers[Exports_js_1.RestConfigBase.configParams.token] = convInfo.token;
if (!!authInfo.token) {
headers[authInfo.headerName] = authInfo.token;
}
const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "").toUpperCase() === "TRUE";
return Promise.resolve(new Exports_js_1.WebsocketConnection(endpointUrl, queryParams, headers, new Exports_js_3.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId));
}
};
exports.ConversationTranslatorConnectionFactory = ConversationTranslatorConnectionFactory;
ConversationTranslatorConnectionFactory.CTS_VIRT_MIC_PATH = "/speech/recognition/dynamicaudio";
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranslator.js
var require_ConversationTranslator = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranslator.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslator = exports.SpeechState = void 0;
var Exports_js_1 = require_Exports7();
var ConversationTranslatorConnectionFactory_js_1 = require_ConversationTranslatorConnectionFactory();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var Conversation_js_1 = require_Conversation();
var Exports_js_4 = require_Exports2();
var SpeechState;
(function(SpeechState2) {
SpeechState2[SpeechState2["Inactive"] = 0] = "Inactive";
SpeechState2[SpeechState2["Connecting"] = 1] = "Connecting";
SpeechState2[SpeechState2["Connected"] = 2] = "Connected";
})(SpeechState = exports.SpeechState || (exports.SpeechState = {}));
var ConversationTranslationRecognizer = class extends Exports_js_3.TranslationRecognizer {
constructor(speechConfig, audioConfig, translator, convGetter) {
super(speechConfig, audioConfig, new ConversationTranslatorConnectionFactory_js_1.ConversationTranslatorConnectionFactory(convGetter));
this.privSpeechState = SpeechState.Inactive;
if (!!translator) {
this.privTranslator = translator;
this.sessionStarted = () => {
this.privSpeechState = SpeechState.Connected;
};
this.sessionStopped = () => {
this.privSpeechState = SpeechState.Inactive;
};
this.recognizing = (tr, e) => {
if (!!this.privTranslator.recognizing) {
this.privTranslator.recognizing(this.privTranslator, e);
}
};
this.recognized = async (tr, e) => {
if (e.result?.errorDetails) {
await this.cancelSpeech();
this.fireCancelEvent(e.result.errorDetails);
} else {
if (!!this.privTranslator.recognized) {
this.privTranslator.recognized(this.privTranslator, e);
}
}
return;
};
this.canceled = async () => {
if (this.privSpeechState !== SpeechState.Inactive) {
try {
await this.cancelSpeech();
} catch (error) {
this.privSpeechState = SpeechState.Inactive;
}
}
};
}
}
get state() {
return this.privSpeechState;
}
set state(newState) {
this.privSpeechState = newState;
}
set authentication(token) {
this.privReco.authentication = token;
}
onConnection() {
this.privSpeechState = SpeechState.Connected;
}
async onCancelSpeech() {
this.privSpeechState = SpeechState.Inactive;
await this.cancelSpeech();
}
/**
* Fire a cancel event
* @param error
*/
fireCancelEvent(error) {
try {
if (!!this.privTranslator.canceled) {
const cancelEvent = new Exports_js_4.ConversationTranslationCanceledEventArgs(Exports_js_3.CancellationReason.Error, error, Exports_js_3.CancellationErrorCode.RuntimeError);
this.privTranslator.canceled(this.privTranslator, cancelEvent);
}
} catch (e) {
}
}
async cancelSpeech() {
try {
this.stopContinuousRecognitionAsync();
await this.privReco?.disconnect();
this.privSpeechState = SpeechState.Inactive;
} catch (e) {
}
}
};
var ConversationTranslator = class extends Exports_js_4.ConversationCommon {
constructor(audioConfig) {
super(audioConfig);
this.privErrors = Exports_js_1.ConversationConnectionConfig.restErrors;
this.privIsDisposed = false;
this.privIsSpeaking = false;
this.privPlaceholderKey = "abcdefghijklmnopqrstuvwxyz012345";
this.privPlaceholderRegion = "westus";
this.privProperties = new Exports_js_3.PropertyCollection();
}
get properties() {
return this.privProperties;
}
get speechRecognitionLanguage() {
return this.privSpeechRecognitionLanguage;
}
get participants() {
return this.privConversation?.participants;
}
get canSpeak() {
if (!this.privConversation.isConnected || !this.privCTRecognizer) {
return false;
}
if (this.privIsSpeaking || this.privCTRecognizer.state === SpeechState.Connected || this.privCTRecognizer.state === SpeechState.Connecting) {
return false;
}
if (this.privConversation.isMutedByHost) {
return false;
}
return true;
}
onToken(token) {
this.privCTRecognizer.authentication = token;
}
setServiceProperty(name, value) {
const currentProperties = JSON.parse(this.privProperties.getProperty(Exports_js_1.ServicePropertiesPropertyName, "{}"));
currentProperties[name] = value;
this.privProperties.setProperty(Exports_js_1.ServicePropertiesPropertyName, JSON.stringify(currentProperties));
}
joinConversationAsync(conversation, nickname, param1, param2, param3) {
try {
if (typeof conversation === "string") {
Contracts_js_1.Contracts.throwIfNullOrUndefined(conversation, this.privErrors.invalidArgs.replace("{arg}", "conversation id"));
Contracts_js_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname"));
if (!!this.privConversation) {
this.handleError(new Error(this.privErrors.permissionDeniedStart), param3);
}
let lang = param1;
if (lang === void 0 || lang === null || lang === "") {
lang = Exports_js_1.ConversationConnectionConfig.defaultLanguageCode;
}
this.privSpeechTranslationConfig = Exports_js_3.SpeechTranslationConfig.fromSubscription(this.privPlaceholderKey, this.privPlaceholderRegion);
this.privSpeechTranslationConfig.setProfanity(Exports_js_3.ProfanityOption.Masked);
this.privSpeechTranslationConfig.addTargetLanguage(lang);
this.privSpeechTranslationConfig.setProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage], lang);
this.privSpeechTranslationConfig.setProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.ConversationTranslator_Name], nickname);
const propertyIdsToCopy = [
Exports_js_3.PropertyId.SpeechServiceConnection_Host,
Exports_js_3.PropertyId.ConversationTranslator_Host,
Exports_js_3.PropertyId.SpeechServiceConnection_Endpoint,
Exports_js_3.PropertyId.SpeechServiceConnection_ProxyHostName,
Exports_js_3.PropertyId.SpeechServiceConnection_ProxyPassword,
Exports_js_3.PropertyId.SpeechServiceConnection_ProxyPort,
Exports_js_3.PropertyId.SpeechServiceConnection_ProxyUserName,
"ConversationTranslator_MultiChannelAudio",
"ConversationTranslator_Region"
];
for (const prop of propertyIdsToCopy) {
const value = this.privProperties.getProperty(prop);
if (value) {
const key = typeof prop === "string" ? prop : Exports_js_3.PropertyId[prop];
this.privSpeechTranslationConfig.setProperty(key, value);
}
}
const currentProperties = JSON.parse(this.privProperties.getProperty(Exports_js_1.ServicePropertiesPropertyName, "{}"));
for (const prop of Object.keys(currentProperties)) {
this.privSpeechTranslationConfig.setServiceProperty(prop, currentProperties[prop], Exports_js_3.ServicePropertyChannel.UriQueryParameter);
}
this.privConversation = new Conversation_js_1.ConversationImpl(this.privSpeechTranslationConfig);
this.privConversation.conversationTranslator = this;
this.privConversation.joinConversationAsync(conversation, nickname, lang, (result) => {
if (!result) {
this.handleError(new Error(this.privErrors.permissionDeniedConnect), param3);
}
this.privSpeechTranslationConfig.authorizationToken = result;
this.privConversation.room.isHost = false;
this.privConversation.startConversationAsync(() => {
this.handleCallback(param2, param3);
}, (error) => {
this.handleError(error, param3);
});
}, (error) => {
this.handleError(error, param3);
});
} else if (typeof conversation === "object") {
Contracts_js_1.Contracts.throwIfNullOrUndefined(conversation, this.privErrors.invalidArgs.replace("{arg}", "conversation id"));
Contracts_js_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname"));
this.privProperties.setProperty(Exports_js_3.PropertyId.ConversationTranslator_Name, nickname);
this.privConversation = conversation;
this.privConversation.conversationTranslator = this;
this.privConversation.room.isHost = true;
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedConnect);
Contracts_js_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
*/
leaveConversationAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)((async () => {
await this.cancelSpeech();
await this.privConversation.endConversationImplAsync();
await this.privConversation.deleteConversationImplAsync();
this.dispose();
})(), cb, err);
}
/**
* Send a text message
* @param message
* @param cb
* @param err
*/
sendTextMessageAsync(message, cb, err) {
try {
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedSend);
Contracts_js_1.Contracts.throwIfNullOrWhitespace(message, this.privErrors.invalidArgs.replace("{arg}", message));
this.privConversation.sendTextMessageAsync(message, cb, err);
} catch (error) {
this.handleError(error, err);
}
}
/**
* Start speaking
* @param cb
* @param err
*/
startTranscribingAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)((async () => {
try {
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privConversation, this.privErrors.permissionDeniedSend);
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privConversation.room.token, this.privErrors.permissionDeniedConnect);
if (this.privCTRecognizer === void 0) {
await this.connectTranslatorRecognizer();
}
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privCTRecognizer, this.privErrors.permissionDeniedSend);
if (!this.canSpeak) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
await this.startContinuousRecognition();
this.privIsSpeaking = true;
} catch (error) {
this.privIsSpeaking = false;
await this.cancelSpeech();
throw error;
}
})(), cb, err);
}
/**
* Stop speaking
* @param cb
* @param err
*/
stopTranscribingAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)((async () => {
try {
if (!this.privIsSpeaking) {
await this.cancelSpeech();
return;
}
this.privIsSpeaking = false;
await new Promise((resolve, reject) => {
this.privCTRecognizer.stopContinuousRecognitionAsync(resolve, reject);
});
} catch (error) {
await this.cancelSpeech();
}
})(), cb, err);
}
isDisposed() {
return this.privIsDisposed;
}
dispose(reason, success, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)((async () => {
if (this.isDisposed && !this.privIsSpeaking) {
return;
}
await this.cancelSpeech();
this.privIsDisposed = true;
this.privSpeechTranslationConfig.close();
this.privSpeechRecognitionLanguage = void 0;
this.privProperties = void 0;
this.privAudioConfig = void 0;
this.privSpeechTranslationConfig = void 0;
this.privConversation.dispose();
this.privConversation = void 0;
})(), success, err);
}
/**
* Cancel the speech websocket
*/
async cancelSpeech() {
try {
this.privIsSpeaking = false;
await this.privCTRecognizer?.onCancelSpeech();
this.privCTRecognizer = void 0;
} catch (e) {
}
}
/**
* 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'
*/
async connectTranslatorRecognizer() {
try {
if (this.privAudioConfig === void 0) {
this.privAudioConfig = Exports_js_3.AudioConfig.fromDefaultMicrophoneInput();
}
if (this.privSpeechTranslationConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_Key]) === this.privPlaceholderKey) {
this.privSpeechTranslationConfig.setProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_Key], "");
}
const convGetter = () => this.privConversation;
this.privCTRecognizer = new ConversationTranslationRecognizer(this.privSpeechTranslationConfig, this.privAudioConfig, this, convGetter);
} catch (error) {
await this.cancelSpeech();
throw error;
}
}
/**
* Handle the start speaking request
*/
startContinuousRecognition() {
return new Promise((resolve, reject) => {
this.privCTRecognizer.startContinuousRecognitionAsync(resolve, reject);
});
}
};
exports.ConversationTranslator = ConversationTranslator;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranscriber.js
var require_ConversationTranscriber = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranscriber.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranscriber = void 0;
var Exports_js_1 = require_Exports7();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var ConversationTranscriber = class _ConversationTranscriber extends Exports_js_3.Recognizer {
/**
* ConversationTranscriber constructor.
* @constructor
* @param {SpeechConfig} speechConfig - an set of initial properties for this recognizer
* @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer
*/
constructor(speechConfig, audioConfig) {
const speechConfigImpl = speechConfig;
Contracts_js_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(speechConfigImpl.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage), Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
super(audioConfig, speechConfigImpl.properties, new Exports_js_1.ConversationTranscriberConnectionFactory(), speechConfig.tokenCredential);
this.privProperties.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, "2");
this.privDisposedRecognizer = false;
}
/**
* ConversationTranscriber 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
*/
static FromConfig(speechConfig, autoDetectSourceLanguageConfig, audioConfig) {
const speechConfigImpl = speechConfig;
autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties);
const recognizer = new _ConversationTranscriber(speechConfig, audioConfig);
return recognizer;
}
/**
* Gets the endpoint id of a customized speech model that is used for transcription.
* @member ConversationTranscriber.prototype.endpointId
* @function
* @public
* @returns {string} the endpoint id of a customized speech model that is used for speech recognition.
*/
get endpointId() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_EndpointId, "00000000-0000-0000-0000-000000000000");
}
/**
* Gets the authorization token used to communicate with the service.
* @member ConversationTranscriber.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
get authorizationToken() {
return this.properties.getProperty(Exports_js_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 authorizationToken(token) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token");
this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, token);
}
/**
* Gets the spoken language of transcription.
* @member ConversationTranscriber.prototype.speechRecognitionLanguage
* @function
* @public
* @returns {string} The spoken language of transcription.
*/
get speechRecognitionLanguage() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage);
}
/**
* Gets the output format of transcription.
* @member ConversationTranscriber.prototype.outputFormat
* @function
* @public
* @returns {OutputFormat} The output format of transcription.
*/
get outputFormat() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
if (this.properties.getProperty(Exports_js_1.OutputFormatPropertyName, Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]) === Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]) {
return Exports_js_3.OutputFormat.Simple;
} else {
return Exports_js_3.OutputFormat.Detailed;
}
}
/**
* The collection of properties and their values defined for this conversation transcriber.
* @member ConversationTranscriber.prototype.properties
* @function
* @public
* @returns {PropertyCollection} The collection of properties and their values defined for this SpeechRecognizer.
*/
get properties() {
return this.privProperties;
}
/**
* 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.
*/
startTranscribingAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(PhraseDetectionContext_js_1.RecognitionMode.Conversation), cb, err);
}
/**
* Stops conversation transcription.
* @member ConversationTranscriber.prototype.stopTranscribingAsync
* @function
* @public
* @param cb - Callback invoked once the transcription has stopped.
* @param err - Callback invoked in case of an error.
*/
stopTranscribingAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(), cb, err);
}
/**
* closes all external resources held by an instance of this class.
* @member ConversationTranscriber.prototype.close
* @function
* @public
*/
close(cb, errorCb) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
(0, Exports_js_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.
*/
async dispose(disposing) {
if (this.privDisposedRecognizer) {
return;
}
if (disposing) {
this.privDisposedRecognizer = true;
await this.implRecognizerStop();
}
await super.dispose(disposing);
}
createRecognizerConfig(speechConfig) {
return new Exports_js_1.RecognizerConfig(speechConfig, this.privProperties);
}
createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) {
const configImpl = audioConfig;
recognizerConfig.isSpeakerDiarizationEnabled = true;
return new Exports_js_1.ConversationTranscriptionServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);
}
};
exports.ConversationTranscriber = ConversationTranscriber;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/IParticipant.js
var require_IParticipant = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/IParticipant.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Participant = exports.User = void 0;
var Exports_js_1 = require_Exports3();
var User = class {
constructor(userId) {
this.privUserId = userId;
}
get userId() {
return this.privUserId;
}
};
exports.User = User;
var Participant = class _Participant {
constructor(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_js_1.PropertyCollection();
}
get avatar() {
return this.privAvatar;
}
get displayName() {
return this.privDisplayName;
}
get id() {
return this.privId;
}
get preferredLanguage() {
return this.privPreferredLanguage;
}
get isHost() {
return this.privIsHost;
}
get isMuted() {
return this.privIsMuted;
}
get isUsingTts() {
return this.privIsUsingTts;
}
get voice() {
return this.privVoice;
}
get properties() {
return this.privProperties;
}
static From(id, language, voice) {
return new _Participant(id, "", id, false, false, false, language, voice);
}
};
exports.Participant = Participant;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ParticipantChangedReason.js
var require_ParticipantChangedReason = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ParticipantChangedReason.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParticipantChangedReason = void 0;
var ParticipantChangedReason;
(function(ParticipantChangedReason2) {
ParticipantChangedReason2[ParticipantChangedReason2["JoinedConversation"] = 0] = "JoinedConversation";
ParticipantChangedReason2[ParticipantChangedReason2["LeftConversation"] = 1] = "LeftConversation";
ParticipantChangedReason2[ParticipantChangedReason2["Updated"] = 2] = "Updated";
})(ParticipantChangedReason = exports.ParticipantChangedReason || (exports.ParticipantChangedReason = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/Meeting.js
var require_Meeting = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/Meeting.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MeetingImpl = exports.Meeting = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var Meeting = class {
constructor() {
return;
}
/**
* Create a meeting
* @param speechConfig
* @param meetingId
* @param cb
* @param err
*/
static createMeetingAsync(speechConfig, meetingId, arg3, arg4) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig, Exports_js_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "config"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig.region, Exports_js_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "SpeechServiceConnection_Region"));
Contracts_js_1.Contracts.throwIfNull(meetingId, "meetingId");
if (meetingId.length === 0) {
throw new Error("meetingId cannot be empty");
}
if (!speechConfig.subscriptionKey && !speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceAuthorization_Token])) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(speechConfig.subscriptionKey, Exports_js_1.ConversationConnectionConfig.restErrors.invalidArgs.replace("{arg}", "SpeechServiceConnection_Key"));
}
const meetingImpl = new MeetingImpl(speechConfig, meetingId);
(0, Exports_js_2.marshalPromiseToCallbacks)((async () => {
})(), arg3, arg4);
return meetingImpl;
}
};
exports.Meeting = Meeting;
var MeetingImpl = class extends Meeting {
/**
* Create a Meeting impl
* @param speechConfig
* @param {string} id - optional conversationId
*/
constructor(speechConfig, id) {
super();
this.privErrors = Exports_js_1.ConversationConnectionConfig.restErrors;
this.onConnected = (e) => {
this.privIsConnected = true;
try {
if (!!this.privConversationTranslator?.sessionStarted) {
this.privConversationTranslator.sessionStarted(this.privConversationTranslator, e);
}
} catch (e2) {
}
};
this.onDisconnected = (e) => {
try {
if (!!this.privConversationTranslator?.sessionStopped) {
this.privConversationTranslator.sessionStopped(this.privConversationTranslator, e);
}
} catch (e2) {
} finally {
void this.close(false);
}
};
this.onCanceled = (r, e) => {
try {
if (!!this.privConversationTranslator?.canceled) {
this.privConversationTranslator.canceled(this.privConversationTranslator, e);
}
} catch (e2) {
}
};
this.onParticipantUpdateCommandReceived = (r, e) => {
try {
const updatedParticipant = this.privParticipants.getParticipant(e.id);
if (updatedParticipant !== void 0) {
switch (e.key) {
case Exports_js_1.ConversationTranslatorCommandTypes.changeNickname:
updatedParticipant.displayName = e.value;
break;
case Exports_js_1.ConversationTranslatorCommandTypes.setUseTTS:
updatedParticipant.isUsingTts = e.value;
break;
case Exports_js_1.ConversationTranslatorCommandTypes.setProfanityFiltering:
updatedParticipant.profanity = e.value;
break;
case Exports_js_1.ConversationTranslatorCommandTypes.setMute:
updatedParticipant.isMuted = e.value;
break;
case Exports_js_1.ConversationTranslatorCommandTypes.setTranslateToLanguages:
updatedParticipant.translateToLanguages = e.value;
break;
}
this.privParticipants.addOrUpdateParticipant(updatedParticipant);
if (!!this.privConversationTranslator) {
this.privConversationTranslator.participantsChanged(this.privConversationTranslator, new Exports_js_3.ConversationParticipantsChangedEventArgs(Exports_js_3.ParticipantChangedReason.Updated, [this.toParticipant(updatedParticipant)], e.sessionId));
}
}
} catch (e2) {
}
};
this.onLockRoomCommandReceived = () => {
};
this.onMuteAllCommandReceived = (r, e) => {
try {
this.privParticipants.participants.forEach((p) => p.isMuted = p.isHost ? false : e.isMuted);
if (!!this.privConversationTranslator) {
this.privConversationTranslator.participantsChanged(this.privConversationTranslator, new Exports_js_3.ConversationParticipantsChangedEventArgs(Exports_js_3.ParticipantChangedReason.Updated, this.toParticipants(false), e.sessionId));
}
} catch (e2) {
}
};
this.onParticipantJoinCommandReceived = (r, e) => {
try {
const newParticipant = this.privParticipants.addOrUpdateParticipant(e.participant);
if (newParticipant !== void 0) {
if (!!this.privConversationTranslator) {
this.privConversationTranslator.participantsChanged(this.privConversationTranslator, new Exports_js_3.ConversationParticipantsChangedEventArgs(Exports_js_3.ParticipantChangedReason.JoinedConversation, [this.toParticipant(newParticipant)], e.sessionId));
}
}
} catch (e2) {
}
};
this.onParticipantLeaveCommandReceived = (r, e) => {
try {
const ejectedParticipant = this.privParticipants.getParticipant(e.participant.id);
if (ejectedParticipant !== void 0) {
this.privParticipants.deleteParticipant(e.participant.id);
if (!!this.privConversationTranslator) {
this.privConversationTranslator.participantsChanged(this.privConversationTranslator, new Exports_js_3.ConversationParticipantsChangedEventArgs(Exports_js_3.ParticipantChangedReason.LeftConversation, [this.toParticipant(ejectedParticipant)], e.sessionId));
}
}
} catch (e2) {
}
};
this.onTranslationReceived = (r, e) => {
try {
switch (e.command) {
case Exports_js_1.ConversationTranslatorMessageTypes.final:
if (!!this.privConversationTranslator) {
this.privConversationTranslator.transcribed(this.privConversationTranslator, new Exports_js_3.ConversationTranslationEventArgs(e.payload, void 0, e.sessionId));
}
break;
case Exports_js_1.ConversationTranslatorMessageTypes.partial:
if (!!this.privConversationTranslator) {
this.privConversationTranslator.transcribing(this.privConversationTranslator, new Exports_js_3.ConversationTranslationEventArgs(e.payload, void 0, e.sessionId));
}
break;
case Exports_js_1.ConversationTranslatorMessageTypes.instantMessage:
if (!!this.privConversationTranslator) {
this.privConversationTranslator.textMessageReceived(this.privConversationTranslator, new Exports_js_3.ConversationTranslationEventArgs(e.payload, void 0, e.sessionId));
}
break;
}
} catch (e2) {
}
};
this.onParticipantsListReceived = (r, e) => {
try {
if (e.sessionToken !== void 0 && e.sessionToken !== null) {
this.privRoom.token = e.sessionToken;
}
this.privParticipants.participants = [...e.participants];
if (this.privParticipants.me !== void 0) {
this.privIsReady = true;
}
if (!!this.privConversationTranslator) {
this.privConversationTranslator.participantsChanged(this.privConversationTranslator, new Exports_js_3.ConversationParticipantsChangedEventArgs(Exports_js_3.ParticipantChangedReason.JoinedConversation, this.toParticipants(true), e.sessionId));
}
if (this.me.isHost) {
const nickname = this.privConversationTranslator?.properties.getProperty(Exports_js_3.PropertyId.ConversationTranslator_Name);
if (nickname !== void 0 && nickname.length > 0 && nickname !== this.me.displayName) {
this.changeNicknameAsync(nickname);
}
}
} catch (e2) {
}
};
this.onConversationExpiration = (r, e) => {
try {
if (!!this.privConversationTranslator) {
this.privConversationTranslator.conversationExpiration(this.privConversationTranslator, e);
}
} catch (e2) {
}
};
this.privIsConnected = false;
this.privIsDisposed = false;
this.privConversationId = "";
this.privProperties = new Exports_js_3.PropertyCollection();
this.privManager = new Exports_js_1.ConversationManager();
const language = speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
if (!language) {
speechConfig.setProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage], Exports_js_1.ConversationConnectionConfig.defaultLanguageCode);
}
this.privLanguage = speechConfig.getProperty(Exports_js_3.PropertyId[Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage]);
this.privConversationId = id;
this.privConfig = speechConfig;
const configImpl = speechConfig;
Contracts_js_1.Contracts.throwIfNull(configImpl, "speechConfig");
this.privProperties = configImpl.properties.clone();
this.privIsConnected = false;
this.privParticipants = new Exports_js_1.InternalParticipants();
this.privIsReady = false;
this.privTextMessageMaxLength = 1e3;
}
// get the internal data about a conversation
get room() {
return this.privRoom;
}
// get the wrapper for connecting to the websockets
get connection() {
return this.privConversationRecognizer;
}
// get the config
get config() {
return this.privConfig;
}
// get the meeting Id
get meetingId() {
return this.privRoom ? this.privRoom.roomId : this.privConversationId;
}
// get the properties
get properties() {
return this.privProperties;
}
// get the speech language
get speechRecognitionLanguage() {
return this.privLanguage;
}
get isMutedByHost() {
return this.privParticipants.me?.isHost ? false : this.privParticipants.me?.isMuted;
}
get isConnected() {
return this.privIsConnected && this.privIsReady;
}
get participants() {
return this.toParticipants(true);
}
get me() {
return this.toParticipant(this.privParticipants.me);
}
get host() {
return this.toParticipant(this.privParticipants.host);
}
get transcriberRecognizer() {
return this.privTranscriberRecognizer;
}
get meetingInfo() {
const convId = this.meetingId;
const p = this.participants.map((part) => ({
id: part.id,
preferredLanguage: part.preferredLanguage,
voice: part.voice
}));
const props = {};
for (const key of Exports_js_1.ConversationConnectionConfig.transcriptionEventKeys) {
const val = this.properties.getProperty(key, "");
if (val !== "") {
props[key] = val;
}
}
const info = { id: convId, participants: p, meetingProperties: props };
return info;
}
get canSend() {
return this.privIsConnected && !this.privParticipants.me?.isMuted;
}
get canSendAsHost() {
return this.privIsConnected && this.privParticipants.me?.isHost;
}
// get / set the speech auth token
// eslint-disable-next-line @typescript-eslint/member-ordering
get authorizationToken() {
return this.privToken;
}
set authorizationToken(value) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(value, "authorizationToken");
this.privToken = value;
}
/**
* Create a new meeting as Host
* @param cb
* @param err
*/
createMeetingAsync(cb, err) {
try {
if (!!this.privConversationRecognizer) {
this.handleError(new Error(this.privErrors.permissionDeniedStart), err);
}
this.privManager.createOrJoin(this.privProperties, void 0, (room) => {
if (!room) {
this.handleError(new Error(this.privErrors.permissionDeniedConnect), err);
}
this.privRoom = room;
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
} catch (error) {
this.handleError(error, err);
}
}
/**
* Starts a new meeting as host.
* @param cb
* @param err
*/
startMeetingAsync(cb, err) {
try {
if (!!this.privConversationRecognizer) {
this.handleError(new Error(this.privErrors.permissionDeniedStart), err);
}
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedConnect);
this.privParticipants.meId = this.privRoom.participantId;
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, () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
} catch (error) {
this.handleError(error, err);
}
}
/**
* Join a meeting as a participant.
* @param { IParticipant } participant - participant to add
* @param cb
* @param err
*/
addParticipantAsync(participant, cb, err) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(participant, "Participant");
(0, Exports_js_2.marshalPromiseToCallbacks)(this.addParticipantImplAsync(participant), cb, err);
}
/**
* Join a meeting as a participant.
* @param meeting
* @param nickname
* @param lang
* @param cb
* @param err
*/
joinMeetingAsync(meetingId, nickname, lang, cb, err) {
try {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(meetingId, this.privErrors.invalidArgs.replace("{arg}", "conversationId"));
Contracts_js_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname"));
Contracts_js_1.Contracts.throwIfNullOrWhitespace(lang, this.privErrors.invalidArgs.replace("{arg}", "language"));
this.privManager.createOrJoin(this.privProperties, meetingId, (room) => {
Contracts_js_1.Contracts.throwIfNullOrUndefined(room, this.privErrors.permissionDeniedConnect);
this.privRoom = room;
this.privConfig.authorizationToken = room.cognitiveSpeechAuthToken;
if (!!cb) {
cb(room.cognitiveSpeechAuthToken);
}
}, (error) => {
this.handleError(error, err);
});
} catch (error) {
this.handleError(error, err);
}
}
/**
* Deletes a meeting
* @param cb
* @param err
*/
deleteMeetingAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.deleteMeetingImplAsync(), cb, err);
}
async deleteMeetingImplAsync() {
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privProperties, this.privErrors.permissionDeniedConnect);
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.token, this.privErrors.permissionDeniedConnect);
await this.privManager.leave(this.privProperties, this.privRoom.token);
this.dispose();
}
/**
* Issues a request to close the client websockets
* @param cb
* @param err
*/
endMeetingAsync(cb, err) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.endMeetingImplAsync(), cb, err);
}
endMeetingImplAsync() {
return this.close(true);
}
/**
* Issues a request to lock the conversation
* @param cb
* @param err
*/
lockMeetingAsync(cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSendAsHost) {
this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "lock")), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getLockCommand(true), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Issues a request to mute the meeting
* @param cb
* @param err
*/
muteAllParticipantsAsync(cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privConversationRecognizer, this.privErrors.permissionDeniedSend);
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSendAsHost) {
this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "mute")), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getMuteAllCommand(true), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Issues a request to mute a participant in the meeting
* @param userId
* @param cb
* @param err
*/
muteParticipantAsync(userId, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrWhitespace(userId, this.privErrors.invalidArgs.replace("{arg}", "userId"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSend) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
if (!this.me.isHost && this.me.id !== userId) {
this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "mute")), err);
}
const exists = this.privParticipants.getParticipantIndex(userId);
if (exists === -1) {
this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getMuteCommand(userId, true), () => {
this.handleCallback(cb, err);
}, (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
*/
removeParticipantAsync(userId, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
if (!!this.privTranscriberRecognizer && userId.hasOwnProperty("id")) {
(0, Exports_js_2.marshalPromiseToCallbacks)(this.removeParticipantImplAsync(userId), cb, err);
} else {
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSendAsHost) {
this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "remove")), err);
}
let participantId = "";
if (typeof userId === "string") {
participantId = userId;
} else if (userId.hasOwnProperty("id")) {
const participant = userId;
participantId = participant.id;
} else if (userId.hasOwnProperty("userId")) {
const user = userId;
participantId = user.userId;
}
Contracts_js_1.Contracts.throwIfNullOrWhitespace(participantId, this.privErrors.invalidArgs.replace("{arg}", "userId"));
const index = this.participants.findIndex((p) => p.id === participantId);
if (index === -1) {
this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getEjectCommand(participantId), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Issues a request to unlock the meeting
* @param cb
* @param err
*/
unlockMeetingAsync(cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSendAsHost) {
this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "unlock")), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getLockCommand(false), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Issues a request to unmute all participants in the meeting
* @param cb
* @param err
*/
unmuteAllParticipantsAsync(cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSendAsHost) {
this.handleError(new Error(this.privErrors.permissionDeniedConversation.replace("{command}", "unmute all")), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getMuteAllCommand(false), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Issues a request to unmute a participant in the meeting
* @param userId
* @param cb
* @param err
*/
unmuteParticipantAsync(userId, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrWhitespace(userId, this.privErrors.invalidArgs.replace("{arg}", "userId"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSend) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
if (!this.me.isHost && this.me.id !== userId) {
this.handleError(new Error(this.privErrors.permissionDeniedParticipant.replace("{command}", "mute")), err);
}
const exists = this.privParticipants.getParticipantIndex(userId);
if (exists === -1) {
this.handleError(new Error(this.privErrors.invalidParticipantRequest), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getMuteCommand(userId, false), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Send a text message
* @param message
* @param cb
* @param err
*/
sendTextMessageAsync(message, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrWhitespace(message, this.privErrors.invalidArgs.replace("{arg}", "message"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSend) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
if (message.length > this.privTextMessageMaxLength) {
this.handleError(new Error(this.privErrors.invalidArgs.replace("{arg}", "message length")), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getMessageCommand(message), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Set translated to languages
* @param {string[]} languages - languages to translate to
* @param cb
* @param err
*/
setTranslatedLanguagesAsync(languages, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfArrayEmptyOrWhitespace(languages, this.privErrors.invalidArgs.replace("{arg}", "languages"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSend) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getSetTranslateToLanguagesCommand(languages), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
/**
* Change nickname
* @param {string} nickname - new nickname for the room
* @param cb
* @param err
*/
changeNicknameAsync(nickname, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfDisposed(this.privConversationRecognizer.isDisposed());
Contracts_js_1.Contracts.throwIfNullOrWhitespace(nickname, this.privErrors.invalidArgs.replace("{arg}", "nickname"));
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRoom, this.privErrors.permissionDeniedSend);
if (!this.canSend) {
this.handleError(new Error(this.privErrors.permissionDeniedSend), err);
}
if (!!this.privConversationRecognizer) {
this.privConversationRecognizer.sendRequest(this.getChangeNicknameCommand(nickname), () => {
this.handleCallback(cb, err);
}, (error) => {
this.handleError(error, err);
});
}
} catch (error) {
this.handleError(error, err);
}
}
isDisposed() {
return this.privIsDisposed;
}
dispose() {
if (this.isDisposed) {
return;
}
this.privIsDisposed = true;
if (!!this.config) {
this.config.close();
}
this.privConfig = void 0;
this.privLanguage = void 0;
this.privProperties = void 0;
this.privRoom = void 0;
this.privToken = void 0;
this.privManager = void 0;
this.privIsConnected = false;
this.privIsReady = false;
this.privParticipants = void 0;
}
async connectTranscriberRecognizer(recognizer) {
if (!!this.privTranscriberRecognizer) {
await this.privTranscriberRecognizer.close();
}
await recognizer.enforceAudioGating();
this.privTranscriberRecognizer = recognizer;
this.privTranscriberRecognizer.meeting = this;
}
getKeepAlive() {
const nickname = !!this.me ? this.me.displayName : "default_nickname";
return JSON.stringify({
id: "0",
nickname,
participantId: this.privRoom.participantId,
roomId: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.keepAlive
});
}
/* eslint-enable @typescript-eslint/typedef */
addParticipantImplAsync(participant) {
const newParticipant = this.privParticipants.addOrUpdateParticipant(participant);
if (newParticipant !== void 0) {
if (!!this.privTranscriberRecognizer) {
const meetingInfo = this.meetingInfo;
meetingInfo.participants = [participant];
return this.privTranscriberRecognizer.pushMeetingEvent(meetingInfo, "join");
}
}
}
removeParticipantImplAsync(participant) {
this.privParticipants.deleteParticipant(participant.id);
const meetingInfo = this.meetingInfo;
meetingInfo.participants = [participant];
return this.privTranscriberRecognizer.pushMeetingEvent(meetingInfo, "leave");
}
async close(dispose) {
try {
this.privIsConnected = false;
await this.privConversationRecognizer?.close();
this.privConversationRecognizer = void 0;
if (!!this.privConversationTranslator) {
this.privConversationTranslator.dispose();
}
} catch (e) {
throw e;
}
if (dispose) {
this.dispose();
}
}
/** Helpers */
handleCallback(cb, err) {
if (!!cb) {
try {
cb();
} catch (e) {
if (!!err) {
err(e);
}
}
cb = void 0;
}
}
handleError(error, err) {
if (!!err) {
if (error instanceof Error) {
const typedError = error;
err(typedError.name + ": " + typedError.message);
} else {
err(error);
}
}
}
/** Participant Helpers */
toParticipants(includeHost) {
const participants = this.privParticipants.participants.map((p) => this.toParticipant(p));
if (!includeHost) {
return participants.filter((p) => p.isHost === false);
} else {
return participants;
}
}
toParticipant(p) {
return new Exports_js_3.Participant(p.id, p.avatar, p.displayName, p.isHost, p.isMuted, p.isUsingTts, p.preferredLanguage, p.voice);
}
getMuteAllCommand(isMuted) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "meetingd");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.setMuteAll,
participantId: this.privRoom.participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand,
value: isMuted
});
}
getMuteCommand(participantId, isMuted) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "conversationId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.setMute,
// eslint-disable-next-line object-shorthand
participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand,
value: isMuted
});
}
getLockCommand(isLocked) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "meetingId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.setLockState,
participantId: this.privRoom.participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand,
value: isLocked
});
}
getEjectCommand(participantId) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "meetingId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.ejectParticipant,
// eslint-disable-next-line object-shorthand
participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand
});
}
getSetTranslateToLanguagesCommand(languages) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "meetingId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.setTranslateToLanguages,
participantId: this.privRoom.participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand,
value: languages
});
}
getChangeNicknameCommand(nickname) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "meetingId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(nickname, "nickname");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
return JSON.stringify({
command: Exports_js_1.ConversationTranslatorCommandTypes.changeNickname,
nickname,
participantId: this.privRoom.participantId,
roomid: this.privRoom.roomId,
type: Exports_js_1.ConversationTranslatorMessageTypes.participantCommand,
value: nickname
});
}
getMessageCommand(message) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.roomId, "meetingId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(this.privRoom.participantId, "participantId");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(message, "message");
return JSON.stringify({
participantId: this.privRoom.participantId,
roomId: this.privRoom.roomId,
text: message,
type: Exports_js_1.ConversationTranslatorMessageTypes.instantMessage
});
}
};
exports.MeetingImpl = MeetingImpl;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/MeetingTranscriptionCanceledEventArgs.js
var require_MeetingTranscriptionCanceledEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/MeetingTranscriptionCanceledEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MeetingTranscriptionCanceledEventArgs = void 0;
var CancellationEventArgsBase_js_1 = require_CancellationEventArgsBase();
var MeetingTranscriptionCanceledEventArgs = class extends CancellationEventArgsBase_js_1.CancellationEventArgsBase {
};
exports.MeetingTranscriptionCanceledEventArgs = MeetingTranscriptionCanceledEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/MeetingTranscriber.js
var require_MeetingTranscriber = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/MeetingTranscriber.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MeetingTranscriber = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var Exports_js_4 = require_Exports2();
var MeetingTranscriber = class {
/**
* MeetingTranscriber constructor.
* @constructor
* @param {AudioConfig} audioConfig - An optional audio configuration associated with the recognizer
*/
constructor(audioConfig) {
this.privAudioConfig = audioConfig;
this.privProperties = new Exports_js_3.PropertyCollection();
this.privRecognizer = void 0;
this.privDisposedRecognizer = false;
}
/**
* Gets the spoken language of recognition.
* @member MeetingTranscriber.prototype.speechRecognitionLanguage
* @function
* @public
* @returns {string} The spoken language of recognition.
*/
get speechRecognitionLanguage() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage);
}
/**
* The collection of properties and their values defined for this MeetingTranscriber.
* @member MeetingTranscriber.prototype.properties
* @function
* @public
* @returns {PropertyCollection} The collection of properties and their values defined for this MeetingTranscriber.
*/
get properties() {
return this.privProperties;
}
/**
* @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 internalData() {
return this.privRecognizer.internalData;
}
/**
* @Deprecated
* @Obsolete
* Please use the Connection.fromRecognizer pattern to obtain a connection object
*/
get connection() {
return Exports_js_3.Connection.fromRecognizer(this.privRecognizer);
}
/**
* Gets the authorization token used to communicate with the service.
* @member MeetingTranscriber.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
get authorizationToken() {
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token);
}
/**
* Gets/Sets the authorization token used to communicate with the service.
* @member MeetingTranscriber.prototype.authorizationToken
* @function
* @public
* @param {string} token - Authorization token.
*/
set authorizationToken(token) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token");
this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, token);
}
/**
* @param {Meeting} meeting - meeting to be recognized
*/
joinMeetingAsync(meeting, cb, err) {
const meetingImpl = meeting;
Contracts_js_1.Contracts.throwIfNullOrUndefined(Exports_js_4.MeetingImpl, "Meeting");
this.privRecognizer = new Exports_js_1.TranscriberRecognizer(meeting.config, this.privAudioConfig);
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privRecognizer, "Recognizer");
this.privRecognizer.connectMeetingCallbacks(this);
(0, Exports_js_2.marshalPromiseToCallbacks)(meetingImpl.connectTranscriberRecognizer(this.privRecognizer), cb, err);
}
/**
* Starts meeting transcription, until stopTranscribingAsync() is called.
* User must subscribe to events to receive transcription results.
* @member MeetingTranscriber.prototype.startTranscribingAsync
* @function
* @public
* @param cb - Callback invoked once the transcription has started.
* @param err - Callback invoked in case of an error.
*/
startTranscribingAsync(cb, err) {
this.privRecognizer.startContinuousRecognitionAsync(cb, err);
}
/**
* Starts meeting transcription, until stopTranscribingAsync() is called.
* User must subscribe to events to receive transcription results.
* @member MeetingTranscriber.prototype.stopTranscribingAsync
* @function
* @public
* @param cb - Callback invoked once the transcription has started.
* @param err - Callback invoked in case of an error.
*/
stopTranscribingAsync(cb, err) {
this.privRecognizer.stopContinuousRecognitionAsync(cb, err);
}
/**
* Leave the current meeting. After this is called, you will no longer receive any events.
*/
leaveMeetingAsync(cb, err) {
this.privRecognizer.disconnectCallbacks();
(0, Exports_js_2.marshalPromiseToCallbacks)((async () => {
return;
})(), cb, err);
}
/**
* closes all external resources held by an instance of this class.
* @member MeetingTranscriber.prototype.close
* @function
* @public
*/
close(cb, errorCb) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
(0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, errorCb);
}
/**
* Disposes any resources held by the object.
* @member MeetingTranscriber.prototype.dispose
* @function
* @public
* @param {boolean} disposing - true if disposing the object.
*/
async dispose(disposing) {
if (this.privDisposedRecognizer) {
return;
}
if (!!this.privRecognizer) {
await this.privRecognizer.close();
this.privRecognizer = void 0;
}
if (disposing) {
this.privDisposedRecognizer = true;
}
}
};
exports.MeetingTranscriber = MeetingTranscriber;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranscriptionResult.js
var require_ConversationTranscriptionResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/ConversationTranscriptionResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranscriptionResult = void 0;
var Exports_js_1 = require_Exports3();
var ConversationTranscriptionResult = class extends Exports_js_1.RecognitionResult {
/**
* 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.
* @param {string} errorDetails - Error details, if provided.
* @param {string} json - Additional Json, if provided.
* @param {PropertyCollection} properties - Additional properties, if provided.
*/
constructor(resultId, reason, text, duration, offset, language, languageDetectionConfidence, speakerId, errorDetails, json, properties) {
super(resultId, reason, text, duration, offset, language, languageDetectionConfidence, errorDetails, json, properties);
this.privSpeakerId = speakerId;
}
/**
* speaker id
* @member ConversationTranscriptionResult.prototype.speakerId
* @function
* @public
* @returns {string} id of speaker in given result
*/
get speakerId() {
return this.privSpeakerId;
}
};
exports.ConversationTranscriptionResult = ConversationTranscriptionResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/Exports.js
var require_Exports2 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Transcription/Exports.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranscriptionResult = exports.MeetingTranscriber = exports.MeetingTranscriptionCanceledEventArgs = exports.MeetingImpl = exports.Meeting = exports.ParticipantChangedReason = exports.User = exports.Participant = exports.ConversationTranscriber = exports.ConversationTranslator = exports.ConversationTranslationResult = exports.ConversationTranslationEventArgs = exports.ConversationTranslationCanceledEventArgs = exports.ConversationParticipantsChangedEventArgs = exports.ConversationExpirationEventArgs = exports.ConversationCommon = exports.ConversationImpl = exports.Conversation = void 0;
var Conversation_js_1 = require_Conversation();
Object.defineProperty(exports, "Conversation", { enumerable: true, get: function() {
return Conversation_js_1.Conversation;
} });
Object.defineProperty(exports, "ConversationImpl", { enumerable: true, get: function() {
return Conversation_js_1.ConversationImpl;
} });
var ConversationCommon_js_1 = require_ConversationCommon();
Object.defineProperty(exports, "ConversationCommon", { enumerable: true, get: function() {
return ConversationCommon_js_1.ConversationCommon;
} });
var ConversationExpirationEventArgs_js_1 = require_ConversationExpirationEventArgs();
Object.defineProperty(exports, "ConversationExpirationEventArgs", { enumerable: true, get: function() {
return ConversationExpirationEventArgs_js_1.ConversationExpirationEventArgs;
} });
var ConversationParticipantsChangedEventArgs_js_1 = require_ConversationParticipantsChangedEventArgs();
Object.defineProperty(exports, "ConversationParticipantsChangedEventArgs", { enumerable: true, get: function() {
return ConversationParticipantsChangedEventArgs_js_1.ConversationParticipantsChangedEventArgs;
} });
var ConversationTranslationCanceledEventArgs_js_1 = require_ConversationTranslationCanceledEventArgs();
Object.defineProperty(exports, "ConversationTranslationCanceledEventArgs", { enumerable: true, get: function() {
return ConversationTranslationCanceledEventArgs_js_1.ConversationTranslationCanceledEventArgs;
} });
var ConversationTranslationEventArgs_js_1 = require_ConversationTranslationEventArgs();
Object.defineProperty(exports, "ConversationTranslationEventArgs", { enumerable: true, get: function() {
return ConversationTranslationEventArgs_js_1.ConversationTranslationEventArgs;
} });
var ConversationTranslationResult_js_1 = require_ConversationTranslationResult();
Object.defineProperty(exports, "ConversationTranslationResult", { enumerable: true, get: function() {
return ConversationTranslationResult_js_1.ConversationTranslationResult;
} });
var ConversationTranslator_js_1 = require_ConversationTranslator();
Object.defineProperty(exports, "ConversationTranslator", { enumerable: true, get: function() {
return ConversationTranslator_js_1.ConversationTranslator;
} });
var ConversationTranscriber_js_1 = require_ConversationTranscriber();
Object.defineProperty(exports, "ConversationTranscriber", { enumerable: true, get: function() {
return ConversationTranscriber_js_1.ConversationTranscriber;
} });
var IParticipant_js_1 = require_IParticipant();
Object.defineProperty(exports, "Participant", { enumerable: true, get: function() {
return IParticipant_js_1.Participant;
} });
Object.defineProperty(exports, "User", { enumerable: true, get: function() {
return IParticipant_js_1.User;
} });
var ParticipantChangedReason_js_1 = require_ParticipantChangedReason();
Object.defineProperty(exports, "ParticipantChangedReason", { enumerable: true, get: function() {
return ParticipantChangedReason_js_1.ParticipantChangedReason;
} });
var Meeting_js_1 = require_Meeting();
Object.defineProperty(exports, "Meeting", { enumerable: true, get: function() {
return Meeting_js_1.Meeting;
} });
Object.defineProperty(exports, "MeetingImpl", { enumerable: true, get: function() {
return Meeting_js_1.MeetingImpl;
} });
var MeetingTranscriptionCanceledEventArgs_js_1 = require_MeetingTranscriptionCanceledEventArgs();
Object.defineProperty(exports, "MeetingTranscriptionCanceledEventArgs", { enumerable: true, get: function() {
return MeetingTranscriptionCanceledEventArgs_js_1.MeetingTranscriptionCanceledEventArgs;
} });
var MeetingTranscriber_js_1 = require_MeetingTranscriber();
Object.defineProperty(exports, "MeetingTranscriber", { enumerable: true, get: function() {
return MeetingTranscriber_js_1.MeetingTranscriber;
} });
var ConversationTranscriptionResult_js_1 = require_ConversationTranscriptionResult();
Object.defineProperty(exports, "ConversationTranscriptionResult", { enumerable: true, get: function() {
return ConversationTranscriptionResult_js_1.ConversationTranscriptionResult;
} });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Synthesizer.js
var require_Synthesizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Synthesizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisRequest = exports.Synthesizer = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var Synthesizer = class _Synthesizer {
/**
* Creates and initializes an instance of a Recognizer
* @constructor
* @param {SpeechConfig} speechConfig - The speech config to initialize the synthesizer.
*/
constructor(speechConfig) {
const speechConfigImpl = speechConfig;
Contracts_js_1.Contracts.throwIfNull(speechConfigImpl, "speechConfig");
this.privProperties = speechConfigImpl.properties.clone();
this.privDisposed = false;
this.privSynthesizing = false;
this.synthesisRequestQueue = new Exports_js_2.Queue();
this.tokenCredential = speechConfig.tokenCredential;
}
/**
* Gets the authorization token used to communicate with the service.
* @member Synthesizer.prototype.authorizationToken
* @function
* @public
* @returns {string} Authorization token.
*/
get authorizationToken() {
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token);
}
/**
* Gets/Sets the authorization token used to communicate with the service.
* @member Synthesizer.prototype.authorizationToken
* @function
* @public
* @param {string} token - Authorization token.
*/
set authorizationToken(token) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token");
this.properties.setProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, token);
}
/**
* The collection of properties and their values defined for this Synthesizer.
* @member Synthesizer.prototype.properties
* @function
* @public
* @returns {PropertyCollection} The collection of properties and their values defined for this SpeechSynthesizer.
*/
get properties() {
return this.privProperties;
}
/**
* Indicates if auto detect source language is enabled
* @member Synthesizer.prototype.autoDetectSourceLanguage
* @function
* @public
* @returns {boolean} if auto detect source language is enabled
*/
get autoDetectSourceLanguage() {
return this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages) === Exports_js_1.AutoDetectSourceLanguagesOpenRangeOptionName;
}
buildSsml(text) {
const languageToDefaultVoice = {
["af-ZA"]: "af-ZA-AdriNeural",
["am-ET"]: "am-ET-AmehaNeural",
["ar-AE"]: "ar-AE-FatimaNeural",
["ar-BH"]: "ar-BH-AliNeural",
["ar-DZ"]: "ar-DZ-AminaNeural",
["ar-EG"]: "ar-EG-SalmaNeural",
["ar-IQ"]: "ar-IQ-BasselNeural",
["ar-JO"]: "ar-JO-SanaNeural",
["ar-KW"]: "ar-KW-FahedNeural",
["ar-LY"]: "ar-LY-ImanNeural",
["ar-MA"]: "ar-MA-JamalNeural",
["ar-QA"]: "ar-QA-AmalNeural",
["ar-SA"]: "ar-SA-HamedNeural",
["ar-SY"]: "ar-SY-AmanyNeural",
["ar-TN"]: "ar-TN-HediNeural",
["ar-YE"]: "ar-YE-MaryamNeural",
["bg-BG"]: "bg-BG-BorislavNeural",
["bn-BD"]: "bn-BD-NabanitaNeural",
["bn-IN"]: "bn-IN-BashkarNeural",
["ca-ES"]: "ca-ES-JoanaNeural",
["cs-CZ"]: "cs-CZ-AntoninNeural",
["cy-GB"]: "cy-GB-AledNeural",
["da-DK"]: "da-DK-ChristelNeural",
["de-AT"]: "de-AT-IngridNeural",
["de-CH"]: "de-CH-JanNeural",
["de-DE"]: "de-DE-KatjaNeural",
["el-GR"]: "el-GR-AthinaNeural",
["en-AU"]: "en-AU-NatashaNeural",
["en-CA"]: "en-CA-ClaraNeural",
["en-GB"]: "en-GB-LibbyNeural",
["en-HK"]: "en-HK-SamNeural",
["en-IE"]: "en-IE-ConnorNeural",
["en-IN"]: "en-IN-NeerjaNeural",
["en-KE"]: "en-KE-AsiliaNeural",
["en-NG"]: "en-NG-AbeoNeural",
["en-NZ"]: "en-NZ-MitchellNeural",
["en-PH"]: "en-PH-JamesNeural",
["en-SG"]: "en-SG-LunaNeural",
["en-TZ"]: "en-TZ-ElimuNeural",
["en-US"]: "en-US-AvaMultilingualNeural",
["en-ZA"]: "en-ZA-LeahNeural",
["es-AR"]: "es-AR-ElenaNeural",
["es-BO"]: "es-BO-MarceloNeural",
["es-CL"]: "es-CL-CatalinaNeural",
["es-CO"]: "es-CO-GonzaloNeural",
["es-CR"]: "es-CR-JuanNeural",
["es-CU"]: "es-CU-BelkysNeural",
["es-DO"]: "es-DO-EmilioNeural",
["es-EC"]: "es-EC-AndreaNeural",
["es-ES"]: "es-ES-AlvaroNeural",
["es-GQ"]: "es-GQ-JavierNeural",
["es-GT"]: "es-GT-AndresNeural",
["es-HN"]: "es-HN-CarlosNeural",
["es-MX"]: "es-MX-DaliaNeural",
["es-NI"]: "es-NI-FedericoNeural",
["es-PA"]: "es-PA-MargaritaNeural",
["es-PE"]: "es-PE-AlexNeural",
["es-PR"]: "es-PR-KarinaNeural",
["es-PY"]: "es-PY-MarioNeural",
["es-SV"]: "es-SV-LorenaNeural",
["es-US"]: "es-US-AlonsoNeural",
["es-UY"]: "es-UY-MateoNeural",
["es-VE"]: "es-VE-PaolaNeural",
["et-EE"]: "et-EE-AnuNeural",
["fa-IR"]: "fa-IR-DilaraNeural",
["fi-FI"]: "fi-FI-SelmaNeural",
["fil-PH"]: "fil-PH-AngeloNeural",
["fr-BE"]: "fr-BE-CharlineNeural",
["fr-CA"]: "fr-CA-SylvieNeural",
["fr-CH"]: "fr-CH-ArianeNeural",
["fr-FR"]: "fr-FR-DeniseNeural",
["ga-IE"]: "ga-IE-ColmNeural",
["gl-ES"]: "gl-ES-RoiNeural",
["gu-IN"]: "gu-IN-DhwaniNeural",
["he-IL"]: "he-IL-AvriNeural",
["hi-IN"]: "hi-IN-MadhurNeural",
["hr-HR"]: "hr-HR-GabrijelaNeural",
["hu-HU"]: "hu-HU-NoemiNeural",
["id-ID"]: "id-ID-ArdiNeural",
["is-IS"]: "is-IS-GudrunNeural",
["it-IT"]: "it-IT-IsabellaNeural",
["ja-JP"]: "ja-JP-NanamiNeural",
["jv-ID"]: "jv-ID-DimasNeural",
["kk-KZ"]: "kk-KZ-AigulNeural",
["km-KH"]: "km-KH-PisethNeural",
["kn-IN"]: "kn-IN-GaganNeural",
["ko-KR"]: "ko-KR-SunHiNeural",
["lo-LA"]: "lo-LA-ChanthavongNeural",
["lt-LT"]: "lt-LT-LeonasNeural",
["lv-LV"]: "lv-LV-EveritaNeural",
["mk-MK"]: "mk-MK-AleksandarNeural",
["ml-IN"]: "ml-IN-MidhunNeural",
["mr-IN"]: "mr-IN-AarohiNeural",
["ms-MY"]: "ms-MY-OsmanNeural",
["mt-MT"]: "mt-MT-GraceNeural",
["my-MM"]: "my-MM-NilarNeural",
["nb-NO"]: "nb-NO-PernilleNeural",
["nl-BE"]: "nl-BE-ArnaudNeural",
["nl-NL"]: "nl-NL-ColetteNeural",
["pl-PL"]: "pl-PL-AgnieszkaNeural",
["ps-AF"]: "ps-AF-GulNawazNeural",
["pt-BR"]: "pt-BR-FranciscaNeural",
["pt-PT"]: "pt-PT-DuarteNeural",
["ro-RO"]: "ro-RO-AlinaNeural",
["ru-RU"]: "ru-RU-SvetlanaNeural",
["si-LK"]: "si-LK-SameeraNeural",
["sk-SK"]: "sk-SK-LukasNeural",
["sl-SI"]: "sl-SI-PetraNeural",
["so-SO"]: "so-SO-MuuseNeural",
["sr-RS"]: "sr-RS-NicholasNeural",
["su-ID"]: "su-ID-JajangNeural",
["sv-SE"]: "sv-SE-SofieNeural",
["sw-KE"]: "sw-KE-RafikiNeural",
["sw-TZ"]: "sw-TZ-DaudiNeural",
["ta-IN"]: "ta-IN-PallaviNeural",
["ta-LK"]: "ta-LK-KumarNeural",
["ta-SG"]: "ta-SG-AnbuNeural",
["te-IN"]: "te-IN-MohanNeural",
["th-TH"]: "th-TH-PremwadeeNeural",
["tr-TR"]: "tr-TR-AhmetNeural",
["uk-UA"]: "uk-UA-OstapNeural",
["ur-IN"]: "ur-IN-GulNeural",
["ur-PK"]: "ur-PK-AsadNeural",
["uz-UZ"]: "uz-UZ-MadinaNeural",
["vi-VN"]: "vi-VN-HoaiMyNeural",
["zh-CN"]: "zh-CN-XiaoxiaoNeural",
["zh-HK"]: "zh-HK-HiuMaanNeural",
["zh-TW"]: "zh-TW-HsiaoChenNeural",
["zu-ZA"]: "zu-ZA-ThandoNeural"
};
let language = this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_SynthLanguage, "en-US");
let voice = this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_SynthVoice, "");
let ssml = _Synthesizer.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;
}
/**
* 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 Synthesizer.prototype.dispose
* @function
* @public
* @param {boolean} disposing - Flag to request disposal.
*/
async dispose(disposing) {
if (this.privDisposed) {
return;
}
if (disposing) {
if (this.privAdapter) {
await this.privAdapter.dispose();
}
}
this.privDisposed = true;
}
async adapterSpeak() {
if (!this.privDisposed && !this.privSynthesizing) {
this.privSynthesizing = true;
const request = await this.synthesisRequestQueue.dequeue();
return this.privAdapter.Speak(request.text, request.isSSML, request.requestId, request.cb, request.err, request.dataStream);
}
}
createSynthesizerConfig(speechConfig) {
return new Exports_js_1.SynthesizerConfig(speechConfig, this.privProperties);
}
// Does the generic synthesizer setup that is common across all synthesizer types.
implCommonSynthesizeSetup() {
let osPlatform = typeof window !== "undefined" ? "Browser" : "Node";
let osName = "unknown";
let osVersion = "unknown";
if (typeof navigator !== "undefined") {
osPlatform = osPlatform + "/" + navigator.platform;
osName = navigator.userAgent;
osVersion = navigator.appVersion;
}
const synthesizerConfig = this.createSynthesizerConfig(new Exports_js_1.SpeechServiceConfig(new Exports_js_1.Context(new Exports_js_1.OS(osPlatform, osName, osVersion))));
const subscriptionKey = this.privProperties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Key, void 0);
const authentication = subscriptionKey && subscriptionKey !== "" ? new Exports_js_1.CognitiveSubscriptionKeyAuthentication(subscriptionKey) : this.tokenCredential ? new Exports_js_1.CognitiveTokenAuthentication(async () => {
try {
const tokenResponse = await this.tokenCredential.getToken("https://cognitiveservices.azure.com/.default");
return tokenResponse?.token ?? "";
} catch (err) {
throw err;
}
}, async () => {
try {
const tokenResponse = await this.tokenCredential.getToken("https://cognitiveservices.azure.com/.default");
return tokenResponse?.token ?? "";
} catch (err) {
throw err;
}
}) : new Exports_js_1.CognitiveTokenAuthentication(() => {
const authorizationToken = this.privProperties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, void 0);
return Promise.resolve(authorizationToken);
}, () => {
const authorizationToken = this.privProperties.getProperty(Exports_js_3.PropertyId.SpeechServiceAuthorization_Token, void 0);
return Promise.resolve(authorizationToken);
});
this.privAdapter = this.createSynthesisAdapter(authentication, this.privConnectionFactory, synthesizerConfig);
this.privRestAdapter = this.createRestSynthesisAdapter(authentication, synthesizerConfig);
}
static XMLEncode(text) {
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}
};
exports.Synthesizer = Synthesizer;
var SynthesisRequest = class {
constructor(requestId, text, isSSML2, cb, err, dataStream) {
this.requestId = requestId;
this.text = text;
this.isSSML = isSSML2;
this.cb = cb;
this.err = err;
this.dataStream = dataStream;
}
};
exports.SynthesisRequest = SynthesisRequest;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesizer.js
var require_SpeechSynthesizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesizer = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var AudioFileWriter_js_1 = require_AudioFileWriter();
var AudioOutputFormat_js_1 = require_AudioOutputFormat();
var AudioOutputStream_js_1 = require_AudioOutputStream();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var Synthesizer_js_1 = require_Synthesizer();
var SpeechSynthesizer = class _SpeechSynthesizer extends Exports_js_3.Synthesizer {
/**
* 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.
*/
constructor(speechConfig, audioConfig) {
super(speechConfig);
if (audioConfig !== null) {
if (audioConfig === void 0) {
this.audioConfig = typeof window === "undefined" ? void 0 : Exports_js_3.AudioConfig.fromDefaultSpeakerOutput();
} else {
this.audioConfig = audioConfig;
}
}
this.privConnectionFactory = new Exports_js_1.SpeechSynthesisConnectionFactory();
this.implCommonSynthesizeSetup();
}
/**
* 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
*/
static FromConfig(speechConfig, autoDetectSourceLanguageConfig, audioConfig) {
const speechConfigImpl = speechConfig;
autoDetectSourceLanguageConfig.properties.mergeTo(speechConfigImpl.properties);
return new _SpeechSynthesizer(speechConfig, audioConfig);
}
/**
* 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.
*/
speakTextAsync(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.
*/
speakSsmlAsync(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.
*/
async getVoicesAsync(locale = "") {
return this.getVoices(locale);
}
/**
* Dispose of associated resources.
* @member SpeechSynthesizer.prototype.close
* @function
* @public
*/
close(cb, err) {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed);
(0, Exports_js_2.marshalPromiseToCallbacks)(this.dispose(true), cb, err);
}
/**
* @Internal
* Do not use externally, object returned will change without warning or notice.
*/
get internalData() {
return this.privAdapter;
}
//
// ################################################################################################################
// IMPLEMENTATION.
// ################################################################################################################
//
// Creates the synthesis adapter
createSynthesisAdapter(authentication, connectionFactory, synthesizerConfig) {
return new Exports_js_1.SpeechSynthesisAdapter(authentication, connectionFactory, synthesizerConfig, this, this.audioConfig);
}
createRestSynthesisAdapter(authentication, synthesizerConfig) {
return new Exports_js_1.SynthesisRestAdapter(synthesizerConfig, authentication);
}
implCommonSynthesizeSetup() {
super.implCommonSynthesizeSetup();
this.privAdapter.audioOutputFormat = AudioOutputFormat_js_1.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(Exports_js_3.SpeechSynthesisOutputFormat[this.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_SynthOutputFormat, void 0)]);
}
speakImpl(text, IsSsml, cb, err, dataStream) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed);
const requestId = (0, Exports_js_2.createNoDashGuid)();
let audioDestination;
if (dataStream instanceof Exports_js_3.PushAudioOutputStreamCallback) {
audioDestination = new AudioOutputStream_js_1.PushAudioOutputStreamImpl(dataStream);
} else if (dataStream instanceof Exports_js_3.PullAudioOutputStream) {
audioDestination = dataStream;
} else if (dataStream !== void 0) {
audioDestination = new AudioFileWriter_js_1.AudioFileWriter(dataStream);
} else {
audioDestination = void 0;
}
this.synthesisRequestQueue.enqueue(new Synthesizer_js_1.SynthesisRequest(requestId, text, IsSsml, (e) => {
this.privSynthesizing = false;
if (!!cb) {
try {
cb(e);
} catch (e2) {
if (!!err) {
err(e2);
}
}
}
cb = void 0;
this.adapterSpeak().catch(() => {
});
}, (e) => {
if (!!err) {
err(e);
}
}, audioDestination));
this.adapterSpeak().catch(() => {
});
} catch (error) {
if (!!err) {
if (error instanceof Error) {
const typedError = error;
err(typedError.name + ": " + typedError.message);
} else {
err(error);
}
}
this.dispose(true).catch(() => {
});
}
}
async getVoices(locale) {
const requestId = (0, Exports_js_2.createNoDashGuid)();
const response = await this.privRestAdapter.getVoicesList(requestId);
if (response.ok && Array.isArray(response.json)) {
let json = response.json;
if (!!locale && locale.length > 0) {
json = json.filter((item) => !!item.Locale && item.Locale.toLowerCase() === locale.toLowerCase());
}
return new Exports_js_3.SynthesisVoicesResult(requestId, json, void 0);
} else {
return new Exports_js_3.SynthesisVoicesResult(requestId, void 0, `Error: ${response.status}: ${response.statusText}`);
}
}
};
exports.SpeechSynthesizer = SpeechSynthesizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SynthesisResult.js
var require_SynthesisResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SynthesisResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisResult = void 0;
var SynthesisResult = class {
/**
* 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.
*/
constructor(resultId, reason, errorDetails, properties) {
this.privResultId = resultId;
this.privReason = reason;
this.privErrorDetails = errorDetails;
this.privProperties = properties;
}
/**
* Specifies the result identifier.
* @member SynthesisResult.prototype.resultId
* @function
* @public
* @returns {string} Specifies the result identifier.
*/
get resultId() {
return this.privResultId;
}
/**
* Specifies status of the result.
* @member SynthesisResult.prototype.reason
* @function
* @public
* @returns {ResultReason} Specifies status of the result.
*/
get reason() {
return this.privReason;
}
/**
* 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 errorDetails() {
return this.privErrorDetails;
}
/**
* 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 properties() {
return this.privProperties;
}
};
exports.SynthesisResult = SynthesisResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisResult.js
var require_SpeechSynthesisResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisResult = void 0;
var Exports_js_1 = require_Exports3();
var SpeechSynthesisResult = class extends Exports_js_1.SynthesisResult {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {string} resultId - The result id.
* @param {ResultReason} reason - The reason.
* @param {ArrayBuffer} audioData - The synthesized audio binary.
* @param {string} errorDetails - Error details, if provided.
* @param {PropertyCollection} properties - Additional properties, if provided.
* @param {number} audioDuration - The audio duration.
*/
constructor(resultId, reason, audioData, errorDetails, properties, audioDuration) {
super(resultId, reason, errorDetails, properties);
this.privAudioData = audioData;
this.privAudioDuration = audioDuration;
}
/**
* The synthesized audio data
* @member SpeechSynthesisResult.prototype.audioData
* @function
* @public
* @returns {ArrayBuffer} The synthesized audio data.
*/
get audioData() {
return this.privAudioData;
}
/**
* The time duration of synthesized audio, in ticks (100 nanoseconds).
* @member SpeechSynthesisResult.prototype.audioDuration
* @function
* @public
* @returns {number} The time duration of synthesized audio.
*/
get audioDuration() {
return this.privAudioDuration;
}
};
exports.SpeechSynthesisResult = SpeechSynthesisResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisEventArgs.js
var require_SpeechSynthesisEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisEventArgs = void 0;
var SpeechSynthesisEventArgs = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {SpeechSynthesisResult} result - The speech synthesis result.
*/
constructor(result) {
this.privResult = result;
}
/**
* Specifies the synthesis result.
* @member SpeechSynthesisEventArgs.prototype.result
* @function
* @public
* @returns {SpeechSynthesisResult} the synthesis result.
*/
get result() {
return this.privResult;
}
};
exports.SpeechSynthesisEventArgs = SpeechSynthesisEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisWordBoundaryEventArgs.js
var require_SpeechSynthesisWordBoundaryEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisWordBoundaryEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisWordBoundaryEventArgs = void 0;
var SpeechSynthesisWordBoundaryEventArgs = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {number} audioOffset - The audio offset.
* @param {number} duration - The audio duration.
* @param {string} text - The text.
* @param {number} wordLength - The length of the word.
* @param {number} textOffset - The text offset.
* @param {SpeechSynthesisBoundaryType} boundaryType - The boundary type
*/
constructor(audioOffset, duration, text, wordLength, textOffset, boundaryType) {
this.privAudioOffset = audioOffset;
this.privDuration = duration;
this.privText = text;
this.privWordLength = wordLength;
this.privTextOffset = textOffset;
this.privBoundaryType = boundaryType;
}
/**
* Specifies the audio offset.
* @member SpeechSynthesisWordBoundaryEventArgs.prototype.audioOffset
* @function
* @public
* @returns {number} the audio offset.
*/
get audioOffset() {
return this.privAudioOffset;
}
/**
* Specifies the duration, in ticks (100 nanoseconds).
* @member SpeechSynthesisWordBoundaryEventArgs.prototype.duration
* @function
* @public
* @returns {number} Duration in 100 nanosecond increments.
*/
get duration() {
return this.privDuration;
}
/**
* Specifies the text of the word boundary event.
* @member SpeechSynthesisWordBoundaryEventArgs.prototype.text
* @function
* @public
* @returns {string} the text.
*/
get text() {
return this.privText;
}
/**
* Specifies the word length
* @member SpeechSynthesisWordBoundaryEventArgs.prototype.wordLength
* @function
* @public
* @returns {number} the word length
*/
get wordLength() {
return this.privWordLength;
}
/**
* Specifies the text offset.
* @member SpeechSynthesisWordBoundaryEventArgs.prototype.textOffset
* @function
* @public
* @returns {number} the text offset.
*/
get textOffset() {
return this.privTextOffset;
}
/**
* Specifies the boundary type.
* @member SpeechSynthesisWordBoundaryEventArgs.prototype.boundaryType
* @function
* @public
* @returns {SpeechSynthesisBoundaryType} the boundary type.
*/
get boundaryType() {
return this.privBoundaryType;
}
};
exports.SpeechSynthesisWordBoundaryEventArgs = SpeechSynthesisWordBoundaryEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisBookmarkEventArgs.js
var require_SpeechSynthesisBookmarkEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisBookmarkEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisBookmarkEventArgs = void 0;
var SpeechSynthesisBookmarkEventArgs = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {number} audioOffset - The audio offset.
* @param {string} text - The bookmark text.
*/
constructor(audioOffset, text) {
this.privAudioOffset = audioOffset;
this.privText = text;
}
/**
* Specifies the audio offset.
* @member SpeechSynthesisBookmarkEventArgs.prototype.audioOffset
* @function
* @public
* @returns {number} the audio offset.
*/
get audioOffset() {
return this.privAudioOffset;
}
/**
* Specifies the bookmark.
* @member SpeechSynthesisBookmarkEventArgs.prototype.text
* @function
* @public
* @returns {string} the bookmark text.
*/
get text() {
return this.privText;
}
};
exports.SpeechSynthesisBookmarkEventArgs = SpeechSynthesisBookmarkEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisVisemeEventArgs.js
var require_SpeechSynthesisVisemeEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisVisemeEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisVisemeEventArgs = void 0;
var SpeechSynthesisVisemeEventArgs = class {
/**
* 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.
*/
constructor(audioOffset, visemeId, animation) {
this.privAudioOffset = audioOffset;
this.privVisemeId = visemeId;
this.privAnimation = animation;
}
/**
* Specifies the audio offset.
* @member SpeechSynthesisVisemeEventArgs.prototype.audioOffset
* @function
* @public
* @returns {number} the audio offset.
*/
get audioOffset() {
return this.privAudioOffset;
}
/**
* Specifies the viseme ID.
* @member SpeechSynthesisVisemeEventArgs.prototype.visemeId
* @function
* @public
* @returns {number} the viseme ID.
*/
get visemeId() {
return this.privVisemeId;
}
/**
* Specifies the animation.
* @member SpeechSynthesisVisemeEventArgs.prototype.animation
* @function
* @public
* @returns {string} the animation, could be in svg or other format.
*/
get animation() {
return this.privAnimation;
}
};
exports.SpeechSynthesisVisemeEventArgs = SpeechSynthesisVisemeEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisBoundaryType.js
var require_SpeechSynthesisBoundaryType = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SpeechSynthesisBoundaryType.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisBoundaryType = void 0;
var SpeechSynthesisBoundaryType;
(function(SpeechSynthesisBoundaryType2) {
SpeechSynthesisBoundaryType2["Word"] = "WordBoundary";
SpeechSynthesisBoundaryType2["Punctuation"] = "PunctuationBoundary";
SpeechSynthesisBoundaryType2["Sentence"] = "SentenceBoundary";
})(SpeechSynthesisBoundaryType = exports.SpeechSynthesisBoundaryType || (exports.SpeechSynthesisBoundaryType = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SynthesisVoicesResult.js
var require_SynthesisVoicesResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/SynthesisVoicesResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisVoicesResult = void 0;
var Exports_js_1 = require_Exports3();
var SynthesisVoicesResult = class extends Exports_js_1.SynthesisResult {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param requestId - result id for request.
* @param json - json payload from endpoint.
*/
constructor(requestId, json, errorDetails) {
if (Array.isArray(json)) {
super(requestId, Exports_js_1.ResultReason.VoicesListRetrieved, void 0, new Exports_js_1.PropertyCollection());
this.privVoices = [];
for (const item of json) {
this.privVoices.push(new Exports_js_1.VoiceInfo(item));
}
} else {
super(requestId, Exports_js_1.ResultReason.Canceled, errorDetails ? errorDetails : "Error information unavailable", new Exports_js_1.PropertyCollection());
}
}
/**
* The list of voices
* @member SynthesisVoicesResult.prototype.voices
* @function
* @public
* @returns {VoiceInfo[]} List of synthesized voices.
*/
get voices() {
return this.privVoices;
}
};
exports.SynthesisVoicesResult = SynthesisVoicesResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceInfo.js
var require_VoiceInfo = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/VoiceInfo.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceInfo = exports.SynthesisVoiceType = exports.SynthesisVoiceGender = void 0;
var SynthesisVoiceGender;
(function(SynthesisVoiceGender2) {
SynthesisVoiceGender2[SynthesisVoiceGender2["Unknown"] = 0] = "Unknown";
SynthesisVoiceGender2[SynthesisVoiceGender2["Female"] = 1] = "Female";
SynthesisVoiceGender2[SynthesisVoiceGender2["Male"] = 2] = "Male";
SynthesisVoiceGender2[SynthesisVoiceGender2["Neutral"] = 3] = "Neutral";
})(SynthesisVoiceGender = exports.SynthesisVoiceGender || (exports.SynthesisVoiceGender = {}));
var SynthesisVoiceType;
(function(SynthesisVoiceType2) {
SynthesisVoiceType2[SynthesisVoiceType2["Unknown"] = 0] = "Unknown";
SynthesisVoiceType2[SynthesisVoiceType2["OnlineNeural"] = 1] = "OnlineNeural";
SynthesisVoiceType2[SynthesisVoiceType2["OnlineStandard"] = 2] = "OnlineStandard";
SynthesisVoiceType2[SynthesisVoiceType2["OfflineNeural"] = 3] = "OfflineNeural";
SynthesisVoiceType2[SynthesisVoiceType2["OfflineStandard"] = 4] = "OfflineStandard";
SynthesisVoiceType2[SynthesisVoiceType2["OnlineNeuralHD"] = 5] = "OnlineNeuralHD";
})(SynthesisVoiceType = exports.SynthesisVoiceType || (exports.SynthesisVoiceType = {}));
var GENDER_LOOKUP = {
[SynthesisVoiceGender[SynthesisVoiceGender.Neutral]]: SynthesisVoiceGender.Neutral,
[SynthesisVoiceGender[SynthesisVoiceGender.Male]]: SynthesisVoiceGender.Male,
[SynthesisVoiceGender[SynthesisVoiceGender.Female]]: SynthesisVoiceGender.Female
};
var VOICE_TYPE_LOOKUP = {
Neural: SynthesisVoiceType.OnlineNeural,
NeuralHD: SynthesisVoiceType.OnlineNeuralHD
};
var VoiceInfo = class {
constructor(json) {
this.privStyleList = [];
if (!!json) {
this.privName = json.Name;
this.privLocale = json.Locale;
this.privShortName = json.ShortName;
this.privLocaleName = json.LocaleName;
this.privDisplayName = json.DisplayName;
this.privLocalName = json.LocalName;
this.privVoiceType = VOICE_TYPE_LOOKUP[json.VoiceType] || SynthesisVoiceType.Unknown;
this.privGender = GENDER_LOOKUP[json.Gender] || SynthesisVoiceGender.Unknown;
if (!!json.StyleList && Array.isArray(json.StyleList)) {
for (const style of json.StyleList) {
this.privStyleList.push(style);
}
}
this.privSampleRateHertz = json.SampleRateHertz;
this.privStatus = json.Status;
if (json.ExtendedPropertyMap) {
this.privExtendedPropertyMap = json.ExtendedPropertyMap;
}
this.privWordsPerMinute = json.WordsPerMinute;
if (Array.isArray(json.SecondaryLocaleList)) {
this.privSecondaryLocaleList = [...json.SecondaryLocaleList];
}
if (Array.isArray(json.RolePlayList)) {
this.privRolePlayList = [...json.RolePlayList];
}
if (json.VoiceTag) {
this.privVoiceTag = json.VoiceTag;
}
}
}
get name() {
return this.privName;
}
get locale() {
return this.privLocale;
}
get shortName() {
return this.privShortName;
}
get displayName() {
return this.privDisplayName;
}
get localName() {
return this.privLocalName;
}
get localeName() {
return this.privLocaleName;
}
get gender() {
return this.privGender;
}
get voiceType() {
return this.privVoiceType;
}
get styleList() {
return this.privStyleList;
}
get sampleRateHertz() {
return this.privSampleRateHertz;
}
get status() {
return this.privStatus;
}
get extendedPropertyMap() {
return this.privExtendedPropertyMap;
}
get wordsPerMinute() {
return this.privWordsPerMinute;
}
get secondaryLocaleList() {
return this.privSecondaryLocaleList;
}
get rolePlayList() {
return this.privRolePlayList;
}
get voiceTag() {
return this.privVoiceTag;
}
};
exports.VoiceInfo = VoiceInfo;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/SpeakerAudioDestination.js
var require_SpeakerAudioDestination = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Audio/SpeakerAudioDestination.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerAudioDestination = void 0;
var Exports_js_1 = require_Exports();
var AudioOutputStream_js_1 = require_AudioOutputStream();
var AudioStreamFormat_js_1 = require_AudioStreamFormat();
var MediaDurationPlaceholderSeconds = 60 * 30;
var AudioFormatToMimeType = {
[AudioStreamFormat_js_1.AudioFormatTag.PCM]: "audio/wav",
[AudioStreamFormat_js_1.AudioFormatTag.MuLaw]: "audio/x-wav",
[AudioStreamFormat_js_1.AudioFormatTag.MP3]: "audio/mpeg",
[AudioStreamFormat_js_1.AudioFormatTag.OGG_OPUS]: "audio/ogg",
[AudioStreamFormat_js_1.AudioFormatTag.WEBM_OPUS]: "audio/webm; codecs=opus",
[AudioStreamFormat_js_1.AudioFormatTag.ALaw]: "audio/x-wav",
[AudioStreamFormat_js_1.AudioFormatTag.FLAC]: "audio/flac",
[AudioStreamFormat_js_1.AudioFormatTag.AMR_WB]: "audio/amr-wb",
[AudioStreamFormat_js_1.AudioFormatTag.G722]: "audio/G722"
};
var SpeakerAudioDestination = class {
constructor(audioDestinationId) {
this.privPlaybackStarted = false;
this.privAppendingToBuffer = false;
this.privMediaSourceOpened = false;
this.privBytesReceived = 0;
this.privId = audioDestinationId ? audioDestinationId : (0, Exports_js_1.createNoDashGuid)();
this.privIsPaused = false;
this.privIsClosed = false;
}
id() {
return this.privId;
}
write(buffer, cb, err) {
if (this.privAudioBuffer !== void 0) {
this.privAudioBuffer.push(buffer);
this.updateSourceBuffer().then(() => {
if (!!cb) {
cb();
}
}, (error) => {
if (!!err) {
err(error);
}
});
} else if (this.privAudioOutputStream !== void 0) {
this.privAudioOutputStream.write(buffer);
this.privBytesReceived += buffer.byteLength;
}
}
close(cb, err) {
this.privIsClosed = true;
if (this.privSourceBuffer !== void 0) {
this.handleSourceBufferUpdateEnd().then(() => {
if (!!cb) {
cb();
}
}, (error) => {
if (!!err) {
err(error);
}
});
} else if (this.privAudioOutputStream !== void 0 && typeof window !== "undefined") {
if ((this.privFormat.formatTag === AudioStreamFormat_js_1.AudioFormatTag.PCM || this.privFormat.formatTag === AudioStreamFormat_js_1.AudioFormatTag.MuLaw || this.privFormat.formatTag === AudioStreamFormat_js_1.AudioFormatTag.ALaw) && this.privFormat.hasHeader === false) {
console.warn("Play back is not supported for raw PCM, mulaw or alaw format without header.");
if (!!this.onAudioEnd) {
this.onAudioEnd(this);
}
} else {
let receivedAudio = new ArrayBuffer(this.privBytesReceived);
this.privAudioOutputStream.read(receivedAudio).then(() => {
receivedAudio = this.privFormat.addHeader(receivedAudio);
const audioBlob = new Blob([receivedAudio], { type: AudioFormatToMimeType[this.privFormat.formatTag] });
this.privAudio.src = window.URL.createObjectURL(audioBlob);
this.notifyPlayback().then(() => {
if (!!cb) {
cb();
}
}, (error) => {
if (!!err) {
err(error);
}
});
}, (error) => {
if (!!err) {
err(error);
}
});
}
} else {
if (!!this.onAudioEnd) {
this.onAudioEnd(this);
}
}
}
set format(format2) {
if (typeof AudioContext !== "undefined" || typeof window !== "undefined" && typeof window.webkitAudioContext !== "undefined") {
this.privFormat = format2;
const mimeType = AudioFormatToMimeType[this.privFormat.formatTag];
if (mimeType === void 0) {
console.warn(`Unknown mimeType for format ${AudioStreamFormat_js_1.AudioFormatTag[this.privFormat.formatTag]}; playback is not supported.`);
} else if (typeof MediaSource !== "undefined" && MediaSource.isTypeSupported(mimeType)) {
this.privAudio = new Audio();
this.privAudioBuffer = [];
this.privMediaSource = new MediaSource();
this.privAudio.src = URL.createObjectURL(this.privMediaSource);
this.privAudio.load();
this.privMediaSource.onsourceopen = () => {
this.privMediaSourceOpened = true;
this.privMediaSource.duration = MediaDurationPlaceholderSeconds;
this.privSourceBuffer = this.privMediaSource.addSourceBuffer(mimeType);
this.privSourceBuffer.onupdate = () => {
this.updateSourceBuffer().catch((reason) => {
Exports_js_1.Events.instance.onEvent(new Exports_js_1.BackgroundEvent(reason));
});
};
this.privSourceBuffer.onupdateend = () => {
this.handleSourceBufferUpdateEnd().catch((reason) => {
Exports_js_1.Events.instance.onEvent(new Exports_js_1.BackgroundEvent(reason));
});
};
this.privSourceBuffer.onupdatestart = () => {
this.privAppendingToBuffer = false;
};
};
this.updateSourceBuffer().catch((reason) => {
Exports_js_1.Events.instance.onEvent(new Exports_js_1.BackgroundEvent(reason));
});
} else {
console.warn(`Format ${AudioStreamFormat_js_1.AudioFormatTag[this.privFormat.formatTag]} could not be played by MSE, streaming playback is not enabled.`);
this.privAudioOutputStream = new AudioOutputStream_js_1.PullAudioOutputStreamImpl();
this.privAudioOutputStream.format = this.privFormat;
this.privAudio = new Audio();
}
}
}
get volume() {
return this.privAudio?.volume ?? -1;
}
set volume(volume) {
if (!!this.privAudio) {
this.privAudio.volume = volume;
}
}
mute() {
if (!!this.privAudio) {
this.privAudio.muted = true;
}
}
unmute() {
if (!!this.privAudio) {
this.privAudio.muted = false;
}
}
get isClosed() {
return this.privIsClosed;
}
get currentTime() {
if (this.privAudio !== void 0) {
return this.privAudio.currentTime;
}
return -1;
}
pause() {
if (!this.privIsPaused && this.privAudio !== void 0) {
this.privAudio.pause();
this.privIsPaused = true;
}
}
resume(cb, err) {
if (this.privIsPaused && this.privAudio !== void 0) {
this.privAudio.play().then(() => {
if (!!cb) {
cb();
}
}, (error) => {
if (!!err) {
err(error);
}
});
this.privIsPaused = false;
}
}
get internalAudio() {
return this.privAudio;
}
async updateSourceBuffer() {
if (this.privAudioBuffer !== void 0 && this.privAudioBuffer.length > 0 && this.sourceBufferAvailable()) {
this.privAppendingToBuffer = true;
const binary = this.privAudioBuffer.shift();
try {
this.privSourceBuffer.appendBuffer(binary);
} catch (error) {
this.privAudioBuffer.unshift(binary);
console.log("buffer filled, pausing addition of binaries until space is made");
return;
}
await this.notifyPlayback();
} else if (this.canEndStream()) {
await this.handleSourceBufferUpdateEnd();
}
}
async handleSourceBufferUpdateEnd() {
if (this.canEndStream() && this.sourceBufferAvailable()) {
this.privMediaSource.endOfStream();
await this.notifyPlayback();
}
}
async notifyPlayback() {
if (!this.privPlaybackStarted && this.privAudio !== void 0) {
this.privPlaybackStarted = true;
if (!!this.onAudioStart) {
this.onAudioStart(this);
}
this.privAudio.onended = () => {
if (!!this.onAudioEnd) {
this.onAudioEnd(this);
}
};
if (!this.privIsPaused) {
await this.privAudio.play();
}
}
}
canEndStream() {
return this.isClosed && this.privSourceBuffer !== void 0 && this.privAudioBuffer.length === 0 && this.privMediaSourceOpened && !this.privAppendingToBuffer && this.privMediaSource.readyState === "open";
}
sourceBufferAvailable() {
return this.privSourceBuffer !== void 0 && !this.privSourceBuffer.updating;
}
};
exports.SpeakerAudioDestination = SpeakerAudioDestination;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ConversationTranscriptionCanceledEventArgs.js
var require_ConversationTranscriptionCanceledEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/ConversationTranscriptionCanceledEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranscriptionCanceledEventArgs = void 0;
var CancellationEventArgsBase_js_1 = require_CancellationEventArgsBase();
var ConversationTranscriptionCanceledEventArgs = class extends CancellationEventArgsBase_js_1.CancellationEventArgsBase {
};
exports.ConversationTranscriptionCanceledEventArgs = ConversationTranscriptionCanceledEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/MeetingTranscriptionCanceledEventArgs.js
var require_MeetingTranscriptionCanceledEventArgs2 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/MeetingTranscriptionCanceledEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MeetingTranscriptionCanceledEventArgs = void 0;
var CancellationEventArgsBase_js_1 = require_CancellationEventArgsBase();
var MeetingTranscriptionCanceledEventArgs = class extends CancellationEventArgsBase_js_1.CancellationEventArgsBase {
};
exports.MeetingTranscriptionCanceledEventArgs = MeetingTranscriptionCanceledEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PronunciationAssessmentGradingSystem.js
var require_PronunciationAssessmentGradingSystem = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PronunciationAssessmentGradingSystem.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PronunciationAssessmentGradingSystem = void 0;
var PronunciationAssessmentGradingSystem;
(function(PronunciationAssessmentGradingSystem2) {
PronunciationAssessmentGradingSystem2[PronunciationAssessmentGradingSystem2["FivePoint"] = 1] = "FivePoint";
PronunciationAssessmentGradingSystem2[PronunciationAssessmentGradingSystem2["HundredMark"] = 2] = "HundredMark";
})(PronunciationAssessmentGradingSystem = exports.PronunciationAssessmentGradingSystem || (exports.PronunciationAssessmentGradingSystem = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PronunciationAssessmentGranularity.js
var require_PronunciationAssessmentGranularity = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PronunciationAssessmentGranularity.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PronunciationAssessmentGranularity = void 0;
var PronunciationAssessmentGranularity;
(function(PronunciationAssessmentGranularity2) {
PronunciationAssessmentGranularity2[PronunciationAssessmentGranularity2["Phoneme"] = 1] = "Phoneme";
PronunciationAssessmentGranularity2[PronunciationAssessmentGranularity2["Word"] = 2] = "Word";
PronunciationAssessmentGranularity2[PronunciationAssessmentGranularity2["FullText"] = 3] = "FullText";
})(PronunciationAssessmentGranularity = exports.PronunciationAssessmentGranularity || (exports.PronunciationAssessmentGranularity = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PronunciationAssessmentConfig.js
var require_PronunciationAssessmentConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PronunciationAssessmentConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PronunciationAssessmentConfig = void 0;
var Contracts_js_1 = require_Contracts();
var Exports_js_1 = require_Exports3();
var PronunciationAssessmentConfig = class _PronunciationAssessmentConfig {
/**
* PronunciationAssessmentConfig constructor.
* @constructor
* @param {string} referenceText
* @param gradingSystem
* @param granularity
* @param enableMiscue
*/
constructor(referenceText, gradingSystem = Exports_js_1.PronunciationAssessmentGradingSystem.FivePoint, granularity = Exports_js_1.PronunciationAssessmentGranularity.Phoneme, enableMiscue = false) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(referenceText, "referenceText");
this.privProperties = new Exports_js_1.PropertyCollection();
this.privProperties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_ReferenceText, referenceText);
this.privProperties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_GradingSystem, Exports_js_1.PronunciationAssessmentGradingSystem[gradingSystem]);
this.privProperties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_Granularity, Exports_js_1.PronunciationAssessmentGranularity[granularity]);
this.privProperties.setProperty(Exports_js_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.
* This method is designed to support the pronunciation assessment parameters still in preview.
* Under normal circumstances, use the constructor instead.
*/
static fromJSON(json) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(json, "json");
const config = new _PronunciationAssessmentConfig("");
config.privProperties = new Exports_js_1.PropertyCollection();
config.properties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_Json, json);
return config;
}
toJSON() {
this.updateJson();
return this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_Params);
}
applyTo(recognizer) {
this.updateJson();
const recoBase = recognizer.internalData;
recoBase.expectContentAssessmentResponse = !!this.privContentAssessmentTopic;
recoBase.speechContext.setPronunciationAssessmentParams(this.properties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_Params), this.privContentAssessmentTopic, recoBase.isSpeakerDiarizationEnabled);
}
/**
* Gets the reference text.
* @member PronunciationAssessmentConfig.prototype.referenceText
* @function
* @public
* @returns {string} Reference text.
*/
get referenceText() {
return this.properties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_ReferenceText);
}
/**
* Gets/Sets the reference text.
* @member PronunciationAssessmentConfig.prototype.referenceText
* @function
* @public
* @param {string} referenceText - Reference text.
*/
set referenceText(referenceText) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(referenceText, "referenceText");
this.properties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_ReferenceText, referenceText);
}
/**
* 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 phonemeAlphabet(phonemeAlphabet) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(phonemeAlphabet, "phonemeAlphabet");
this.privPhonemeAlphabet = phonemeAlphabet;
}
/**
* Sets the boolean enableMiscue property.
* Added in version 1.26.0
* @member PronunciationAssessmentConfig.prototype.enableMiscue
* @function
* @public
* @param {boolean} enableMiscue - enable miscue.
*/
set enableMiscue(enableMiscue) {
const enableMiscueString = enableMiscue ? "true" : "false";
this.properties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_EnableMiscue, enableMiscueString);
}
/**
* Gets the boolean enableMiscue property.
* Added in version 1.26.0
* @member PronunciationAssessmentConfig.prototype.enableMiscue
* @function
* @public
* @return {boolean} enableMiscue - enable miscue.
*/
get enableMiscue() {
const enableMiscueString = this.properties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_EnableMiscue, "false");
return enableMiscueString.toLowerCase() === "true";
}
/**
* Sets the nbest phoneme count
* Added in version 1.20.0
* @member PronunciationAssessmentConfig.prototype.nbestPhonemeCount
* @function
* @public
* @param {number} nbestPhonemeCount - NBest phoneme count.
*/
set nbestPhonemeCount(nbestPhonemeCount) {
this.privNBestPhonemeCount = nbestPhonemeCount;
}
/**
* Enables the prosody assessment.
* Added in version 1.34.0
* @member PronunciationAssessmentConfig.prototype.enableProsodyAssessment
* @function
* @public
* @param {boolean} enableProsodyAssessment - enable prosody assessment.
*/
set enableProsodyAssessment(enableProsodyAssessment) {
this.privEnableProsodyAssessment = enableProsodyAssessment;
}
/**
* Enables content assessment and sets the topic.
* Added in version 1.34.0
* @member PronunciationAssessmentConfig.prototype.enableContentAssessmentWithTopic
* @function
* @public
* @param {string} topic - Topic for content assessment.
*/
enableContentAssessmentWithTopic(topic) {
this.privContentAssessmentTopic = topic;
}
/**
* @member PronunciationAssessmentConfig.prototype.properties
* @function
* @public
* @return {PropertyCollection} Properties of the config.
* @summary Gets a pronunciation assessment config properties
*/
get properties() {
return this.privProperties;
}
updateJson() {
const jsonString = this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_Json, "{}");
const paramsJson = JSON.parse(jsonString);
const referenceText = this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_ReferenceText);
if (referenceText) {
paramsJson.referenceText = referenceText;
}
const gradingSystem = this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_GradingSystem);
if (gradingSystem) {
paramsJson.gradingSystem = gradingSystem;
}
const granularity = this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_Granularity);
if (granularity) {
paramsJson.granularity = granularity;
}
if (this.privPhonemeAlphabet) {
paramsJson.phonemeAlphabet = this.privPhonemeAlphabet;
}
if (this.privNBestPhonemeCount) {
paramsJson.nbestPhonemeCount = this.privNBestPhonemeCount;
}
paramsJson.enableProsodyAssessment = this.privEnableProsodyAssessment;
paramsJson.dimension = "Comprehensive";
const enableMiscueString = this.privProperties.getProperty(Exports_js_1.PropertyId.PronunciationAssessment_EnableMiscue);
if (enableMiscueString) {
paramsJson.enableMiscue = this.enableMiscue;
}
this.privProperties.setProperty(Exports_js_1.PropertyId.PronunciationAssessment_Params, JSON.stringify(paramsJson));
}
};
exports.PronunciationAssessmentConfig = PronunciationAssessmentConfig;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PronunciationAssessmentResult.js
var require_PronunciationAssessmentResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/PronunciationAssessmentResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PronunciationAssessmentResult = exports.ContentAssessmentResult = void 0;
var Contracts_js_1 = require_Contracts();
var Exports_js_1 = require_Exports3();
var ContentAssessmentResult = class {
/**
* @Internal
* Do not use externally.
*/
constructor(detailResult) {
this.privPronJson = detailResult;
}
/**
* Correctness in using grammar and variety of sentence patterns.
* Grammatical errors are jointly evaluated by lexical accuracy,
* grammatical accuracy and diversity of sentence structures.
* @member ContentAssessmentResult.prototype.grammarScore
* @function
* @public
* @returns {number} Grammar score.
*/
get grammarScore() {
return this.privPronJson.ContentAssessment.GrammarScore;
}
/**
* Proficiency in lexical usage. It evaluates the speaker's effective usage
* of words and their appropriateness within the given context to express
* ideas accurately, as well as level of lexical complexity.
* @member ContentAssessmentResult.prototype.vocabularyScore
* @function
* @public
* @returns {number} Vocabulary score.
*/
get vocabularyScore() {
return this.privPronJson.ContentAssessment.VocabularyScore;
}
/**
* Level of understanding and engagement with the topic, which provides
* insights into the speaker’s ability to express their thoughts and ideas
* effectively and the ability to engage with the topic.
* @member ContentAssessmentResult.prototype.topicScore
* @function
* @public
* @returns {number} Topic score.
*/
get topicScore() {
return this.privPronJson.ContentAssessment.TopicScore;
}
};
exports.ContentAssessmentResult = ContentAssessmentResult;
var PronunciationAssessmentResult = class _PronunciationAssessmentResult {
constructor(jsonString) {
const j = JSON.parse(jsonString);
Contracts_js_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.
*/
static fromResult(result) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(result, "result");
const json = result.properties.getProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult);
Contracts_js_1.Contracts.throwIfNullOrUndefined(json, "json");
return new _PronunciationAssessmentResult(json);
}
/**
* Gets the detail result of pronunciation assessment.
* @member PronunciationAssessmentConfig.prototype.detailResult
* @function
* @public
* @returns {DetailResult} detail result.
*/
get detailResult() {
return this.privPronJson;
}
/**
* 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 accuracyScore() {
return this.detailResult.PronunciationAssessment?.AccuracyScore;
}
/**
* 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 pronunciationScore() {
return this.detailResult.PronunciationAssessment?.PronScore;
}
/**
* 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 completenessScore() {
return this.detailResult.PronunciationAssessment?.CompletenessScore;
}
/**
* The score indicating the fluency of the given speech.
* @member PronunciationAssessmentResult.prototype.fluencyScore
* @function
* @public
* @returns {number} Fluency score.
*/
get fluencyScore() {
return this.detailResult.PronunciationAssessment?.FluencyScore;
}
/**
* The prosody score, which indicates how nature of the given speech, including stress, intonation, speaking speed and rhythm.
* @member PronunciationAssessmentResult.prototype.prosodyScore
* @function
* @public
* @returns {number} Prosody score.
*/
get prosodyScore() {
return this.detailResult.PronunciationAssessment?.ProsodyScore;
}
/**
* The concent assessment result.
* Only available when content assessment is enabled.
* @member PronunciationAssessmentResult.prototype.contentAssessmentResult
* @function
* @public
* @returns {ContentAssessmentResult} Content assessment result.
*/
get contentAssessmentResult() {
if (this.detailResult.ContentAssessment === void 0) {
return void 0;
}
return new ContentAssessmentResult(this.detailResult);
}
};
exports.PronunciationAssessmentResult = PronunciationAssessmentResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AvatarConfig.js
var require_AvatarConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AvatarConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AvatarConfig = void 0;
var Contracts_js_1 = require_Contracts();
var Exports_js_1 = require_Exports3();
var AvatarConfig = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {string} character - The avatar character.
* @param {string} style - The avatar style.
* @param {AvatarVideoFormat} videoFormat - The talking avatar output video format.
*/
constructor(character, style, videoFormat) {
this.privCustomized = false;
this.privUseBuiltInVoice = false;
Contracts_js_1.Contracts.throwIfNullOrWhitespace(character, "character");
this.character = character;
this.style = style;
if (videoFormat === void 0) {
videoFormat = new Exports_js_1.AvatarVideoFormat();
}
this.videoFormat = videoFormat;
}
/**
* Indicates if the talking avatar is customized.
*/
get customized() {
return this.privCustomized;
}
/**
* Sets if the talking avatar is customized.
*/
set customized(value) {
this.privCustomized = value;
}
/**
* Indicates whether to use built-in voice for custom avatar.
*/
get useBuiltInVoice() {
return this.privUseBuiltInVoice;
}
/**
* Sets whether to use built-in voice for custom avatar.
*/
set useBuiltInVoice(value) {
this.privUseBuiltInVoice = value;
}
/**
* Gets the background color.
*/
get backgroundColor() {
return this.privBackgroundColor;
}
/**
* Sets the background color.
*/
set backgroundColor(value) {
this.privBackgroundColor = value;
}
/**
* Gets the background image.
*/
get backgroundImage() {
return this.privBackgroundImage;
}
/**
* Sets the background image.
* @param {URL} value - The background image.
*/
set backgroundImage(value) {
this.privBackgroundImage = value;
}
/**
* Gets the remote ICE servers.
* @remarks This method is designed to be used internally in the SDK.
* @returns {RTCIceServer[]} The remote ICE servers.
*/
get remoteIceServers() {
return this.privRemoteIceServers;
}
/**
* Sets the remote ICE servers.
* @remarks Normally, the ICE servers are gathered from the PeerConnection,
* set this property to override the ICE servers. E.g., the ICE servers are
* different in client and server side.
* @param {RTCIceServer[]} value - The remote ICE servers.
*/
set remoteIceServers(value) {
this.privRemoteIceServers = value;
}
};
exports.AvatarConfig = AvatarConfig;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AvatarEventArgs.js
var require_AvatarEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AvatarEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AvatarEventArgs = exports.AvatarEventTypes = void 0;
var AvatarEventTypes;
(function(AvatarEventTypes2) {
AvatarEventTypes2["SwitchedToSpeaking"] = "SwitchedToSpeaking";
AvatarEventTypes2["SwitchedToIdle"] = "SwitchedToIdle";
AvatarEventTypes2["SessionClosed"] = "SessionClosed";
})(AvatarEventTypes = exports.AvatarEventTypes || (exports.AvatarEventTypes = {}));
var AvatarEventArgs = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {number} audioOffset - The audio offset.
* @param {string} description - The description of the event.
*/
constructor(audioOffset, description) {
this.privOffset = audioOffset;
this.privDescription = description;
}
/**
* The type of the event.
* @public
* @returns {AvatarEventTypes} The type of the event.
*/
get type() {
return this.privType;
}
/**
* The time offset associated with this event.
* @public
* @returns {number} The time offset associated with this event.
*/
get offset() {
return this.privOffset;
}
/**
* The description of the event.
* @public
* @returns {string} The description of the event.
*/
get description() {
return this.privDescription;
}
};
exports.AvatarEventArgs = AvatarEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechSynthesisConnectionFactory.js
var require_SpeechSynthesisConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechSynthesisConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisConnectionFactory = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports3();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var Exports_js_3 = require_Exports7();
var HeaderNames_js_1 = require_HeaderNames();
var QueryParameterNames_js_1 = require_QueryParameterNames();
var SpeechSynthesisConnectionFactory = class {
constructor() {
this.synthesisUri = "/tts/cognitiveservices/websocket/v1";
}
async create(config, authInfo, connectionId) {
let endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, void 0);
const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, void 0);
const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region);
const endpointId = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId, void 0);
const hostPrefix = endpointId === void 0 ? "tts" : "voice";
const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + "." + hostPrefix + ".speech" + hostSuffix);
const queryParams = {};
const headers = {};
if (authInfo.token !== void 0 && authInfo.token !== "") {
headers[authInfo.headerName] = authInfo.token;
}
headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId;
if (endpointId !== void 0 && endpointId !== "") {
if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.CustomVoiceDeploymentId) === -1) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.CustomVoiceDeploymentId] = endpointId;
}
}
if (config.avatarEnabled) {
if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.EnableAvatar) === -1) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.EnableAvatar] = "true";
}
}
if (!!endpoint) {
const endpointUrl = new URL(endpoint);
const pathName = endpointUrl.pathname;
if (pathName === "" || pathName === "/") {
endpointUrl.pathname = this.synthesisUri;
endpoint = await ConnectionFactoryBase_js_1.ConnectionFactoryBase.getRedirectUrlFromEndpoint(endpointUrl.toString());
}
}
if (!endpoint) {
endpoint = host + this.synthesisUri;
}
config.parameters.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url, endpoint);
const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
return new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_3.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromParameters(config.parameters), enableCompression, connectionId);
}
};
exports.SpeechSynthesisConnectionFactory = SpeechSynthesisConnectionFactory;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AvatarSynthesizer.js
var require_AvatarSynthesizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AvatarSynthesizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AvatarSynthesizer = void 0;
var SpeechSynthesisConnectionFactory_js_1 = require_SpeechSynthesisConnectionFactory();
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var AudioOutputFormat_js_1 = require_AudioOutputFormat();
var Exports_js_3 = require_Exports3();
var Contracts_js_1 = require_Contracts();
var Synthesizer_js_1 = require_Synthesizer();
var AvatarSynthesizer = class extends Exports_js_3.Synthesizer {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {SpeechConfig} speechConfig - The speech config.
* @param {AvatarConfig} avatarConfig - The talking avatar config.
*/
constructor(speechConfig, avatarConfig) {
super(speechConfig);
Contracts_js_1.Contracts.throwIfNullOrUndefined(avatarConfig, "avatarConfig");
this.privConnectionFactory = new SpeechSynthesisConnectionFactory_js_1.SpeechSynthesisConnectionFactory();
this.privAvatarConfig = avatarConfig;
this.implCommonSynthesizeSetup();
}
implCommonSynthesizeSetup() {
super.implCommonSynthesizeSetup();
this.privAdapter.audioOutputFormat = AudioOutputFormat_js_1.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormat(Exports_js_3.SpeechSynthesisOutputFormat.Riff24Khz16BitMonoPcm);
}
/**
* Starts the talking avatar session and establishes the WebRTC connection.
* @member AvatarSynthesizer.prototype.startAvatarAsync
* @function
* @public
* @param {AvatarWebRTCConnectionInfo} peerConnection - The peer connection.
* @returns {Promise<SynthesisResult>} The promise of the connection result.
*/
async startAvatarAsync(peerConnection) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(peerConnection, "peerConnection");
this.privIceServers = peerConnection.getConfiguration().iceServers;
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privIceServers, "Ice servers must be set.");
const iceGatheringDone = new Exports_js_2.Deferred();
peerConnection.onicegatheringstatechange = () => {
Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: ice gathering state: " + peerConnection.iceGatheringState, Exports_js_2.EventType.Debug));
if (peerConnection.iceGatheringState === "complete") {
Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: ice gathering complete.", Exports_js_2.EventType.Info));
iceGatheringDone.resolve();
}
};
peerConnection.onicecandidate = (event) => {
if (event.candidate) {
Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: ice candidate: " + event.candidate.candidate, Exports_js_2.EventType.Debug));
} else {
Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: ice candidate: complete", Exports_js_2.EventType.Debug));
iceGatheringDone.resolve();
}
};
setTimeout(() => {
if (peerConnection.iceGatheringState !== "complete") {
Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: ice gathering timeout.", Exports_js_2.EventType.Warning));
iceGatheringDone.resolve();
}
}, 2e3);
const sdp = await peerConnection.createOffer();
await peerConnection.setLocalDescription(sdp);
await iceGatheringDone.promise;
Exports_js_2.Events.instance.onEvent(new Exports_js_2.PlatformEvent("peer connection: got local SDP.", Exports_js_2.EventType.Info));
this.privProperties.setProperty(Exports_js_3.PropertyId.TalkingAvatarService_WebRTC_SDP, JSON.stringify(peerConnection.localDescription));
const result = await this.speak("", false);
if (result.reason !== Exports_js_3.ResultReason.SynthesizingAudioCompleted) {
return new Exports_js_3.SynthesisResult(result.resultId, result.reason, result.errorDetails, result.properties);
}
const sdpAnswerString = atob(result.properties.getProperty(Exports_js_3.PropertyId.TalkingAvatarService_WebRTC_SDP));
const sdpAnswer = new RTCSessionDescription(JSON.parse(sdpAnswerString));
await peerConnection.setRemoteDescription(sdpAnswer);
return new Exports_js_3.SynthesisResult(result.resultId, result.reason, void 0, result.properties);
}
/**
* Speaks plain text asynchronously. The rendered audio and video will be sent via the WebRTC connection.
* @member AvatarSynthesizer.prototype.speakTextAsync
* @function
* @public
* @param {string} text - The plain text to speak.
* @returns {Promise<SynthesisResult>} The promise of the synthesis result.
*/
async speakTextAsync(text) {
const r = await this.speak(text, false);
return new Exports_js_3.SynthesisResult(r.resultId, r.reason, r.errorDetails, r.properties);
}
/**
* Speaks SSML asynchronously. The rendered audio and video will be sent via the WebRTC connection.
* @member AvatarSynthesizer.prototype.speakSsmlAsync
* @function
* @public
* @param {string} ssml - The SSML text to speak.
* @returns {Promise<SynthesisResult>} The promise of the synthesis result.
*/
async speakSsmlAsync(ssml) {
const r = await this.speak(ssml, true);
return new Exports_js_3.SynthesisResult(r.resultId, r.reason, r.errorDetails, r.properties);
}
/**
* Speaks text asynchronously. The avatar will switch to idle state.
* @member AvatarSynthesizer.prototype.stopSpeakingAsync
* @function
* @public
* @returns {Promise<void>} The promise of the void result.
*/
async stopSpeakingAsync() {
while (this.synthesisRequestQueue.length() > 0) {
const request = await this.synthesisRequestQueue.dequeue();
request.err("Synthesis is canceled by user.");
}
return this.privAdapter.stopSpeaking();
}
/**
* Stops the talking avatar session and closes the WebRTC connection.
* For now, this is the same as close().
* You need to create a new AvatarSynthesizer instance to start a new session.
* @member AvatarSynthesizer.prototype.stopAvatarAsync
* @function
* @public
* @returns {Promise<void>} The promise of the void result.
*/
async stopAvatarAsync() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposed);
return this.dispose(true);
}
/**
* Dispose of associated resources.
* @member AvatarSynthesizer.prototype.close
* @function
* @public
*/
async close() {
if (this.privDisposed) {
return;
}
return this.dispose(true);
}
/**
* Gets the ICE servers. Internal use only.
*/
get iceServers() {
return this.privIceServers;
}
// Creates the synthesis adapter
createSynthesisAdapter(authentication, connectionFactory, synthesizerConfig) {
return new Exports_js_1.AvatarSynthesisAdapter(authentication, connectionFactory, synthesizerConfig, this, this.privAvatarConfig);
}
createRestSynthesisAdapter(_authentication, _synthesizerConfig) {
return void 0;
}
createSynthesizerConfig(speechConfig) {
const config = super.createSynthesizerConfig(speechConfig);
config.avatarEnabled = true;
return config;
}
async speak(text, isSSML2) {
const requestId = (0, Exports_js_2.createNoDashGuid)();
const deferredResult = new Exports_js_2.Deferred();
this.synthesisRequestQueue.enqueue(new Synthesizer_js_1.SynthesisRequest(requestId, text, isSSML2, (e) => {
deferredResult.resolve(e);
this.privSynthesizing = false;
void this.adapterSpeak();
}, (e) => {
deferredResult.reject(e);
this.privSynthesizing = false;
}));
void this.adapterSpeak();
return deferredResult.promise;
}
};
exports.AvatarSynthesizer = AvatarSynthesizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AvatarVideoFormat.js
var require_AvatarVideoFormat = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AvatarVideoFormat.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AvatarVideoFormat = exports.Coordinate = void 0;
var Coordinate = class {
constructor(x, y) {
this.x = x;
this.y = y;
}
};
exports.Coordinate = Coordinate;
var AvatarVideoFormat = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {string} codec - The video codec.
* @param {number} bitrate - The video bitrate.
* @param {number} width - The video width.
* @param {number} height - The video height.
*/
constructor(codec = "H264", bitrate = 2e6, width = 1920, height = 1080) {
this.codec = codec;
this.bitrate = bitrate;
this.width = width;
this.height = height;
}
/**
* Sets the video crop range.
*/
setCropRange(topLeft, bottomRight) {
this.cropRange = {
bottomRight,
topLeft
};
}
};
exports.AvatarVideoFormat = AvatarVideoFormat;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AvatarWebRTCConnectionResult.js
var require_AvatarWebRTCConnectionResult = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/AvatarWebRTCConnectionResult.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AvatarWebRTCConnectionResult = void 0;
var Exports_js_1 = require_Exports3();
var AvatarWebRTCConnectionResult = class extends Exports_js_1.SynthesisResult {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param {RTCSessionDescriptionInit} SDPAnswer - The SDP answer of WebRTC connection.
* @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.
*/
constructor(SDPAnswer, resultId, reason, errorDetails, properties) {
super(resultId, reason, errorDetails, properties);
this.privSDPAnswer = SDPAnswer;
}
/**
* Specifies SDP (Session Description Protocol) answer of WebRTC connection.
* @member AvatarWebRTCConnectionResult.prototype.SDPAnswer
* @function
* @public
* @returns {RTCSessionDescriptionInit} Specifies the SDP answer of WebRTC connection.
*/
get SDPAnswer() {
return this.privSDPAnswer;
}
};
exports.AvatarWebRTCConnectionResult = AvatarWebRTCConnectionResult;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Diagnostics.js
var require_Diagnostics = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Diagnostics.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Diagnostics = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports();
var Diagnostics = class {
static SetLoggingLevel(logLevel) {
this.privListener = new Exports_js_1.ConsoleLoggingListener(logLevel);
Exports_js_2.Events.instance.attachConsoleListener(this.privListener);
}
static StartConsoleOutput() {
if (!!this.privListener) {
this.privListener.enableConsoleOutput = true;
}
}
static StopConsoleOutput() {
if (!!this.privListener) {
this.privListener.enableConsoleOutput = false;
}
}
static SetLogOutputPath(path) {
if (typeof window === "undefined") {
if (!!this.privListener) {
this.privListener.logPath = path;
}
} else {
throw new Error("File system logging not available in browser.");
}
}
static set onLogOutput(callback) {
if (!!this.privListener) {
this.privListener.logCallback = callback;
}
}
};
exports.Diagnostics = Diagnostics;
Diagnostics.privListener = void 0;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Exports.js
var require_Exports3 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/sdk/Exports.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConnectionEventArgs = exports.CancellationErrorCode = exports.CancellationDetails = exports.CancellationDetailsBase = exports.IntentRecognitionCanceledEventArgs = exports.TranslationRecognitionCanceledEventArgs = exports.NoMatchDetails = exports.NoMatchReason = exports.Translations = exports.TranslationRecognizer = exports.VoiceProfileType = exports.IntentRecognizer = exports.SpeechRecognizer = exports.Recognizer = exports.PropertyId = exports.PropertyCollection = exports.SpeechTranslationConfigImpl = exports.SpeechTranslationConfig = exports.SpeechConfigImpl = exports.SpeechConfig = exports.ResultReason = exports.TranslationSynthesisResult = exports.TranslationRecognitionResult = exports.TranslationSynthesisEventArgs = exports.TranslationRecognitionEventArgs = exports.SpeechRecognitionCanceledEventArgs = exports.MeetingTranscriptionEventArgs = exports.ConversationTranscriptionEventArgs = exports.SpeechRecognitionEventArgs = exports.LanguageUnderstandingModel = exports.IntentRecognitionResult = exports.SpeechRecognitionResult = exports.RecognitionResult = exports.IntentRecognitionEventArgs = exports.OutputFormat = exports.RecognitionEventArgs = exports.SessionEventArgs = exports.KeywordRecognitionModel = exports.PushAudioOutputStreamCallback = exports.PullAudioInputStreamCallback = exports.CancellationReason = exports.PushAudioOutputStream = exports.PullAudioOutputStream = exports.AudioOutputStream = exports.PushAudioInputStream = exports.PullAudioInputStream = exports.AudioInputStream = exports.AudioFormatTag = exports.AudioStreamFormat = exports.AudioConfig = void 0;
exports.SpeechSynthesisEventArgs = exports.SpeechSynthesisResult = exports.SynthesisResult = exports.SpeechSynthesizer = exports.SpeechSynthesisOutputFormat = exports.Synthesizer = exports.User = exports.ParticipantChangedReason = exports.Participant = exports.MeetingTranscriber = exports.Meeting = exports.ConversationTranscriptionResult = exports.ConversationTranscriber = exports.ConversationTranslator = exports.ConversationTranslationResult = exports.ConversationTranslationEventArgs = exports.ConversationTranslationCanceledEventArgs = exports.ConversationParticipantsChangedEventArgs = exports.ConversationExpirationEventArgs = exports.Conversation = exports.SpeakerRecognitionCancellationDetails = exports.SpeakerRecognitionResultType = exports.SpeakerRecognitionResult = exports.SourceLanguageConfig = exports.AutoDetectSourceLanguageResult = exports.AutoDetectSourceLanguageConfig = exports.SpeakerVerificationModel = exports.SpeakerIdentificationModel = exports.SpeakerRecognizer = exports.VoiceProfileClient = exports.VoiceProfilePhraseResult = exports.VoiceProfileCancellationDetails = exports.VoiceProfileResult = exports.VoiceProfileEnrollmentCancellationDetails = exports.VoiceProfileEnrollmentResult = exports.VoiceProfile = exports.ConnectionMessage = exports.ConnectionMessageEventArgs = exports.BaseAudioPlayer = exports.ProfanityOption = exports.ServicePropertyChannel = exports.TurnStatusReceivedEventArgs = exports.ActivityReceivedEventArgs = exports.DialogServiceConnector = exports.CustomCommandsConfig = exports.BotFrameworkConfig = exports.DialogServiceConfig = exports.PhraseListGrammar = exports.Connection = exports.ServiceEventArgs = void 0;
exports.LogLevel = exports.Diagnostics = exports.AvatarWebRTCConnectionResult = exports.Coordinate = exports.AvatarVideoFormat = exports.AvatarSynthesizer = exports.AvatarEventArgs = exports.AvatarConfig = exports.LanguageIdMode = exports.PronunciationAssessmentResult = exports.PronunciationAssessmentConfig = exports.PronunciationAssessmentGranularity = exports.PronunciationAssessmentGradingSystem = exports.MeetingTranscriptionCanceledEventArgs = exports.ConversationTranscriptionCanceledEventArgs = exports.SpeakerAudioDestination = exports.VoiceInfo = exports.SynthesisVoiceType = exports.SynthesisVoiceGender = exports.SynthesisVoicesResult = exports.SpeechSynthesisBoundaryType = exports.SpeechSynthesisVisemeEventArgs = exports.SpeechSynthesisBookmarkEventArgs = exports.SpeechSynthesisWordBoundaryEventArgs = void 0;
var AudioConfig_js_1 = require_AudioConfig();
Object.defineProperty(exports, "AudioConfig", { enumerable: true, get: function() {
return AudioConfig_js_1.AudioConfig;
} });
var AudioStreamFormat_js_1 = require_AudioStreamFormat();
Object.defineProperty(exports, "AudioStreamFormat", { enumerable: true, get: function() {
return AudioStreamFormat_js_1.AudioStreamFormat;
} });
Object.defineProperty(exports, "AudioFormatTag", { enumerable: true, get: function() {
return AudioStreamFormat_js_1.AudioFormatTag;
} });
var AudioInputStream_js_1 = require_AudioInputStream();
Object.defineProperty(exports, "AudioInputStream", { enumerable: true, get: function() {
return AudioInputStream_js_1.AudioInputStream;
} });
Object.defineProperty(exports, "PullAudioInputStream", { enumerable: true, get: function() {
return AudioInputStream_js_1.PullAudioInputStream;
} });
Object.defineProperty(exports, "PushAudioInputStream", { enumerable: true, get: function() {
return AudioInputStream_js_1.PushAudioInputStream;
} });
var AudioOutputStream_js_1 = require_AudioOutputStream();
Object.defineProperty(exports, "AudioOutputStream", { enumerable: true, get: function() {
return AudioOutputStream_js_1.AudioOutputStream;
} });
Object.defineProperty(exports, "PullAudioOutputStream", { enumerable: true, get: function() {
return AudioOutputStream_js_1.PullAudioOutputStream;
} });
Object.defineProperty(exports, "PushAudioOutputStream", { enumerable: true, get: function() {
return AudioOutputStream_js_1.PushAudioOutputStream;
} });
var CancellationReason_js_1 = require_CancellationReason();
Object.defineProperty(exports, "CancellationReason", { enumerable: true, get: function() {
return CancellationReason_js_1.CancellationReason;
} });
var PullAudioInputStreamCallback_js_1 = require_PullAudioInputStreamCallback();
Object.defineProperty(exports, "PullAudioInputStreamCallback", { enumerable: true, get: function() {
return PullAudioInputStreamCallback_js_1.PullAudioInputStreamCallback;
} });
var PushAudioOutputStreamCallback_js_1 = require_PushAudioOutputStreamCallback();
Object.defineProperty(exports, "PushAudioOutputStreamCallback", { enumerable: true, get: function() {
return PushAudioOutputStreamCallback_js_1.PushAudioOutputStreamCallback;
} });
var KeywordRecognitionModel_js_1 = require_KeywordRecognitionModel();
Object.defineProperty(exports, "KeywordRecognitionModel", { enumerable: true, get: function() {
return KeywordRecognitionModel_js_1.KeywordRecognitionModel;
} });
var SessionEventArgs_js_1 = require_SessionEventArgs();
Object.defineProperty(exports, "SessionEventArgs", { enumerable: true, get: function() {
return SessionEventArgs_js_1.SessionEventArgs;
} });
var RecognitionEventArgs_js_1 = require_RecognitionEventArgs();
Object.defineProperty(exports, "RecognitionEventArgs", { enumerable: true, get: function() {
return RecognitionEventArgs_js_1.RecognitionEventArgs;
} });
var OutputFormat_js_1 = require_OutputFormat();
Object.defineProperty(exports, "OutputFormat", { enumerable: true, get: function() {
return OutputFormat_js_1.OutputFormat;
} });
var IntentRecognitionEventArgs_js_1 = require_IntentRecognitionEventArgs();
Object.defineProperty(exports, "IntentRecognitionEventArgs", { enumerable: true, get: function() {
return IntentRecognitionEventArgs_js_1.IntentRecognitionEventArgs;
} });
var RecognitionResult_js_1 = require_RecognitionResult();
Object.defineProperty(exports, "RecognitionResult", { enumerable: true, get: function() {
return RecognitionResult_js_1.RecognitionResult;
} });
var SpeechRecognitionResult_js_1 = require_SpeechRecognitionResult();
Object.defineProperty(exports, "SpeechRecognitionResult", { enumerable: true, get: function() {
return SpeechRecognitionResult_js_1.SpeechRecognitionResult;
} });
var IntentRecognitionResult_js_1 = require_IntentRecognitionResult();
Object.defineProperty(exports, "IntentRecognitionResult", { enumerable: true, get: function() {
return IntentRecognitionResult_js_1.IntentRecognitionResult;
} });
var LanguageUnderstandingModel_js_1 = require_LanguageUnderstandingModel();
Object.defineProperty(exports, "LanguageUnderstandingModel", { enumerable: true, get: function() {
return LanguageUnderstandingModel_js_1.LanguageUnderstandingModel;
} });
var SpeechRecognitionEventArgs_js_1 = require_SpeechRecognitionEventArgs();
Object.defineProperty(exports, "SpeechRecognitionEventArgs", { enumerable: true, get: function() {
return SpeechRecognitionEventArgs_js_1.SpeechRecognitionEventArgs;
} });
Object.defineProperty(exports, "ConversationTranscriptionEventArgs", { enumerable: true, get: function() {
return SpeechRecognitionEventArgs_js_1.ConversationTranscriptionEventArgs;
} });
Object.defineProperty(exports, "MeetingTranscriptionEventArgs", { enumerable: true, get: function() {
return SpeechRecognitionEventArgs_js_1.MeetingTranscriptionEventArgs;
} });
var SpeechRecognitionCanceledEventArgs_js_1 = require_SpeechRecognitionCanceledEventArgs();
Object.defineProperty(exports, "SpeechRecognitionCanceledEventArgs", { enumerable: true, get: function() {
return SpeechRecognitionCanceledEventArgs_js_1.SpeechRecognitionCanceledEventArgs;
} });
var TranslationRecognitionEventArgs_js_1 = require_TranslationRecognitionEventArgs();
Object.defineProperty(exports, "TranslationRecognitionEventArgs", { enumerable: true, get: function() {
return TranslationRecognitionEventArgs_js_1.TranslationRecognitionEventArgs;
} });
var TranslationSynthesisEventArgs_js_1 = require_TranslationSynthesisEventArgs();
Object.defineProperty(exports, "TranslationSynthesisEventArgs", { enumerable: true, get: function() {
return TranslationSynthesisEventArgs_js_1.TranslationSynthesisEventArgs;
} });
var TranslationRecognitionResult_js_1 = require_TranslationRecognitionResult();
Object.defineProperty(exports, "TranslationRecognitionResult", { enumerable: true, get: function() {
return TranslationRecognitionResult_js_1.TranslationRecognitionResult;
} });
var TranslationSynthesisResult_js_1 = require_TranslationSynthesisResult();
Object.defineProperty(exports, "TranslationSynthesisResult", { enumerable: true, get: function() {
return TranslationSynthesisResult_js_1.TranslationSynthesisResult;
} });
var ResultReason_js_1 = require_ResultReason();
Object.defineProperty(exports, "ResultReason", { enumerable: true, get: function() {
return ResultReason_js_1.ResultReason;
} });
var SpeechConfig_js_1 = require_SpeechConfig();
Object.defineProperty(exports, "SpeechConfig", { enumerable: true, get: function() {
return SpeechConfig_js_1.SpeechConfig;
} });
Object.defineProperty(exports, "SpeechConfigImpl", { enumerable: true, get: function() {
return SpeechConfig_js_1.SpeechConfigImpl;
} });
var SpeechTranslationConfig_js_1 = require_SpeechTranslationConfig();
Object.defineProperty(exports, "SpeechTranslationConfig", { enumerable: true, get: function() {
return SpeechTranslationConfig_js_1.SpeechTranslationConfig;
} });
Object.defineProperty(exports, "SpeechTranslationConfigImpl", { enumerable: true, get: function() {
return SpeechTranslationConfig_js_1.SpeechTranslationConfigImpl;
} });
var PropertyCollection_js_1 = require_PropertyCollection();
Object.defineProperty(exports, "PropertyCollection", { enumerable: true, get: function() {
return PropertyCollection_js_1.PropertyCollection;
} });
var PropertyId_js_1 = require_PropertyId();
Object.defineProperty(exports, "PropertyId", { enumerable: true, get: function() {
return PropertyId_js_1.PropertyId;
} });
var Recognizer_js_1 = require_Recognizer();
Object.defineProperty(exports, "Recognizer", { enumerable: true, get: function() {
return Recognizer_js_1.Recognizer;
} });
var SpeechRecognizer_js_1 = require_SpeechRecognizer();
Object.defineProperty(exports, "SpeechRecognizer", { enumerable: true, get: function() {
return SpeechRecognizer_js_1.SpeechRecognizer;
} });
var IntentRecognizer_js_1 = require_IntentRecognizer();
Object.defineProperty(exports, "IntentRecognizer", { enumerable: true, get: function() {
return IntentRecognizer_js_1.IntentRecognizer;
} });
var VoiceProfileType_js_1 = require_VoiceProfileType();
Object.defineProperty(exports, "VoiceProfileType", { enumerable: true, get: function() {
return VoiceProfileType_js_1.VoiceProfileType;
} });
var TranslationRecognizer_js_1 = require_TranslationRecognizer();
Object.defineProperty(exports, "TranslationRecognizer", { enumerable: true, get: function() {
return TranslationRecognizer_js_1.TranslationRecognizer;
} });
var Translations_js_1 = require_Translations();
Object.defineProperty(exports, "Translations", { enumerable: true, get: function() {
return Translations_js_1.Translations;
} });
var NoMatchReason_js_1 = require_NoMatchReason();
Object.defineProperty(exports, "NoMatchReason", { enumerable: true, get: function() {
return NoMatchReason_js_1.NoMatchReason;
} });
var NoMatchDetails_js_1 = require_NoMatchDetails();
Object.defineProperty(exports, "NoMatchDetails", { enumerable: true, get: function() {
return NoMatchDetails_js_1.NoMatchDetails;
} });
var TranslationRecognitionCanceledEventArgs_js_1 = require_TranslationRecognitionCanceledEventArgs();
Object.defineProperty(exports, "TranslationRecognitionCanceledEventArgs", { enumerable: true, get: function() {
return TranslationRecognitionCanceledEventArgs_js_1.TranslationRecognitionCanceledEventArgs;
} });
var IntentRecognitionCanceledEventArgs_js_1 = require_IntentRecognitionCanceledEventArgs();
Object.defineProperty(exports, "IntentRecognitionCanceledEventArgs", { enumerable: true, get: function() {
return IntentRecognitionCanceledEventArgs_js_1.IntentRecognitionCanceledEventArgs;
} });
var CancellationDetailsBase_js_1 = require_CancellationDetailsBase();
Object.defineProperty(exports, "CancellationDetailsBase", { enumerable: true, get: function() {
return CancellationDetailsBase_js_1.CancellationDetailsBase;
} });
var CancellationDetails_js_1 = require_CancellationDetails();
Object.defineProperty(exports, "CancellationDetails", { enumerable: true, get: function() {
return CancellationDetails_js_1.CancellationDetails;
} });
var CancellationErrorCodes_js_1 = require_CancellationErrorCodes();
Object.defineProperty(exports, "CancellationErrorCode", { enumerable: true, get: function() {
return CancellationErrorCodes_js_1.CancellationErrorCode;
} });
var ConnectionEventArgs_js_1 = require_ConnectionEventArgs();
Object.defineProperty(exports, "ConnectionEventArgs", { enumerable: true, get: function() {
return ConnectionEventArgs_js_1.ConnectionEventArgs;
} });
var ServiceEventArgs_js_1 = require_ServiceEventArgs();
Object.defineProperty(exports, "ServiceEventArgs", { enumerable: true, get: function() {
return ServiceEventArgs_js_1.ServiceEventArgs;
} });
var Connection_js_1 = require_Connection();
Object.defineProperty(exports, "Connection", { enumerable: true, get: function() {
return Connection_js_1.Connection;
} });
var PhraseListGrammar_js_1 = require_PhraseListGrammar();
Object.defineProperty(exports, "PhraseListGrammar", { enumerable: true, get: function() {
return PhraseListGrammar_js_1.PhraseListGrammar;
} });
var DialogServiceConfig_js_1 = require_DialogServiceConfig();
Object.defineProperty(exports, "DialogServiceConfig", { enumerable: true, get: function() {
return DialogServiceConfig_js_1.DialogServiceConfig;
} });
var BotFrameworkConfig_js_1 = require_BotFrameworkConfig();
Object.defineProperty(exports, "BotFrameworkConfig", { enumerable: true, get: function() {
return BotFrameworkConfig_js_1.BotFrameworkConfig;
} });
var CustomCommandsConfig_js_1 = require_CustomCommandsConfig();
Object.defineProperty(exports, "CustomCommandsConfig", { enumerable: true, get: function() {
return CustomCommandsConfig_js_1.CustomCommandsConfig;
} });
var DialogServiceConnector_js_1 = require_DialogServiceConnector();
Object.defineProperty(exports, "DialogServiceConnector", { enumerable: true, get: function() {
return DialogServiceConnector_js_1.DialogServiceConnector;
} });
var ActivityReceivedEventArgs_js_1 = require_ActivityReceivedEventArgs();
Object.defineProperty(exports, "ActivityReceivedEventArgs", { enumerable: true, get: function() {
return ActivityReceivedEventArgs_js_1.ActivityReceivedEventArgs;
} });
var TurnStatusReceivedEventArgs_js_1 = require_TurnStatusReceivedEventArgs();
Object.defineProperty(exports, "TurnStatusReceivedEventArgs", { enumerable: true, get: function() {
return TurnStatusReceivedEventArgs_js_1.TurnStatusReceivedEventArgs;
} });
var ServicePropertyChannel_js_1 = require_ServicePropertyChannel();
Object.defineProperty(exports, "ServicePropertyChannel", { enumerable: true, get: function() {
return ServicePropertyChannel_js_1.ServicePropertyChannel;
} });
var ProfanityOption_js_1 = require_ProfanityOption();
Object.defineProperty(exports, "ProfanityOption", { enumerable: true, get: function() {
return ProfanityOption_js_1.ProfanityOption;
} });
var BaseAudioPlayer_js_1 = require_BaseAudioPlayer();
Object.defineProperty(exports, "BaseAudioPlayer", { enumerable: true, get: function() {
return BaseAudioPlayer_js_1.BaseAudioPlayer;
} });
var ConnectionMessageEventArgs_js_1 = require_ConnectionMessageEventArgs();
Object.defineProperty(exports, "ConnectionMessageEventArgs", { enumerable: true, get: function() {
return ConnectionMessageEventArgs_js_1.ConnectionMessageEventArgs;
} });
var ConnectionMessage_js_1 = require_ConnectionMessage2();
Object.defineProperty(exports, "ConnectionMessage", { enumerable: true, get: function() {
return ConnectionMessage_js_1.ConnectionMessage;
} });
var VoiceProfile_js_1 = require_VoiceProfile();
Object.defineProperty(exports, "VoiceProfile", { enumerable: true, get: function() {
return VoiceProfile_js_1.VoiceProfile;
} });
var VoiceProfileEnrollmentResult_js_1 = require_VoiceProfileEnrollmentResult();
Object.defineProperty(exports, "VoiceProfileEnrollmentResult", { enumerable: true, get: function() {
return VoiceProfileEnrollmentResult_js_1.VoiceProfileEnrollmentResult;
} });
Object.defineProperty(exports, "VoiceProfileEnrollmentCancellationDetails", { enumerable: true, get: function() {
return VoiceProfileEnrollmentResult_js_1.VoiceProfileEnrollmentCancellationDetails;
} });
var VoiceProfileResult_js_1 = require_VoiceProfileResult();
Object.defineProperty(exports, "VoiceProfileResult", { enumerable: true, get: function() {
return VoiceProfileResult_js_1.VoiceProfileResult;
} });
Object.defineProperty(exports, "VoiceProfileCancellationDetails", { enumerable: true, get: function() {
return VoiceProfileResult_js_1.VoiceProfileCancellationDetails;
} });
var VoiceProfilePhraseResult_js_1 = require_VoiceProfilePhraseResult();
Object.defineProperty(exports, "VoiceProfilePhraseResult", { enumerable: true, get: function() {
return VoiceProfilePhraseResult_js_1.VoiceProfilePhraseResult;
} });
var VoiceProfileClient_js_1 = require_VoiceProfileClient();
Object.defineProperty(exports, "VoiceProfileClient", { enumerable: true, get: function() {
return VoiceProfileClient_js_1.VoiceProfileClient;
} });
var SpeakerRecognizer_js_1 = require_SpeakerRecognizer();
Object.defineProperty(exports, "SpeakerRecognizer", { enumerable: true, get: function() {
return SpeakerRecognizer_js_1.SpeakerRecognizer;
} });
var SpeakerIdentificationModel_js_1 = require_SpeakerIdentificationModel();
Object.defineProperty(exports, "SpeakerIdentificationModel", { enumerable: true, get: function() {
return SpeakerIdentificationModel_js_1.SpeakerIdentificationModel;
} });
var SpeakerVerificationModel_js_1 = require_SpeakerVerificationModel();
Object.defineProperty(exports, "SpeakerVerificationModel", { enumerable: true, get: function() {
return SpeakerVerificationModel_js_1.SpeakerVerificationModel;
} });
var AutoDetectSourceLanguageConfig_js_1 = require_AutoDetectSourceLanguageConfig();
Object.defineProperty(exports, "AutoDetectSourceLanguageConfig", { enumerable: true, get: function() {
return AutoDetectSourceLanguageConfig_js_1.AutoDetectSourceLanguageConfig;
} });
var AutoDetectSourceLanguageResult_js_1 = require_AutoDetectSourceLanguageResult();
Object.defineProperty(exports, "AutoDetectSourceLanguageResult", { enumerable: true, get: function() {
return AutoDetectSourceLanguageResult_js_1.AutoDetectSourceLanguageResult;
} });
var SourceLanguageConfig_js_1 = require_SourceLanguageConfig();
Object.defineProperty(exports, "SourceLanguageConfig", { enumerable: true, get: function() {
return SourceLanguageConfig_js_1.SourceLanguageConfig;
} });
var SpeakerRecognitionResult_js_1 = require_SpeakerRecognitionResult();
Object.defineProperty(exports, "SpeakerRecognitionResult", { enumerable: true, get: function() {
return SpeakerRecognitionResult_js_1.SpeakerRecognitionResult;
} });
Object.defineProperty(exports, "SpeakerRecognitionResultType", { enumerable: true, get: function() {
return SpeakerRecognitionResult_js_1.SpeakerRecognitionResultType;
} });
Object.defineProperty(exports, "SpeakerRecognitionCancellationDetails", { enumerable: true, get: function() {
return SpeakerRecognitionResult_js_1.SpeakerRecognitionCancellationDetails;
} });
var Exports_js_1 = require_Exports2();
Object.defineProperty(exports, "Conversation", { enumerable: true, get: function() {
return Exports_js_1.Conversation;
} });
Object.defineProperty(exports, "ConversationExpirationEventArgs", { enumerable: true, get: function() {
return Exports_js_1.ConversationExpirationEventArgs;
} });
Object.defineProperty(exports, "ConversationParticipantsChangedEventArgs", { enumerable: true, get: function() {
return Exports_js_1.ConversationParticipantsChangedEventArgs;
} });
Object.defineProperty(exports, "ConversationTranslationCanceledEventArgs", { enumerable: true, get: function() {
return Exports_js_1.ConversationTranslationCanceledEventArgs;
} });
Object.defineProperty(exports, "ConversationTranslationEventArgs", { enumerable: true, get: function() {
return Exports_js_1.ConversationTranslationEventArgs;
} });
Object.defineProperty(exports, "ConversationTranslationResult", { enumerable: true, get: function() {
return Exports_js_1.ConversationTranslationResult;
} });
Object.defineProperty(exports, "ConversationTranslator", { enumerable: true, get: function() {
return Exports_js_1.ConversationTranslator;
} });
Object.defineProperty(exports, "ConversationTranscriber", { enumerable: true, get: function() {
return Exports_js_1.ConversationTranscriber;
} });
Object.defineProperty(exports, "ConversationTranscriptionResult", { enumerable: true, get: function() {
return Exports_js_1.ConversationTranscriptionResult;
} });
Object.defineProperty(exports, "Meeting", { enumerable: true, get: function() {
return Exports_js_1.Meeting;
} });
Object.defineProperty(exports, "MeetingTranscriber", { enumerable: true, get: function() {
return Exports_js_1.MeetingTranscriber;
} });
Object.defineProperty(exports, "Participant", { enumerable: true, get: function() {
return Exports_js_1.Participant;
} });
Object.defineProperty(exports, "ParticipantChangedReason", { enumerable: true, get: function() {
return Exports_js_1.ParticipantChangedReason;
} });
Object.defineProperty(exports, "User", { enumerable: true, get: function() {
return Exports_js_1.User;
} });
var Synthesizer_js_1 = require_Synthesizer();
Object.defineProperty(exports, "Synthesizer", { enumerable: true, get: function() {
return Synthesizer_js_1.Synthesizer;
} });
var SpeechSynthesisOutputFormat_js_1 = require_SpeechSynthesisOutputFormat();
Object.defineProperty(exports, "SpeechSynthesisOutputFormat", { enumerable: true, get: function() {
return SpeechSynthesisOutputFormat_js_1.SpeechSynthesisOutputFormat;
} });
var SpeechSynthesizer_js_1 = require_SpeechSynthesizer();
Object.defineProperty(exports, "SpeechSynthesizer", { enumerable: true, get: function() {
return SpeechSynthesizer_js_1.SpeechSynthesizer;
} });
var SynthesisResult_js_1 = require_SynthesisResult();
Object.defineProperty(exports, "SynthesisResult", { enumerable: true, get: function() {
return SynthesisResult_js_1.SynthesisResult;
} });
var SpeechSynthesisResult_js_1 = require_SpeechSynthesisResult();
Object.defineProperty(exports, "SpeechSynthesisResult", { enumerable: true, get: function() {
return SpeechSynthesisResult_js_1.SpeechSynthesisResult;
} });
var SpeechSynthesisEventArgs_js_1 = require_SpeechSynthesisEventArgs();
Object.defineProperty(exports, "SpeechSynthesisEventArgs", { enumerable: true, get: function() {
return SpeechSynthesisEventArgs_js_1.SpeechSynthesisEventArgs;
} });
var SpeechSynthesisWordBoundaryEventArgs_js_1 = require_SpeechSynthesisWordBoundaryEventArgs();
Object.defineProperty(exports, "SpeechSynthesisWordBoundaryEventArgs", { enumerable: true, get: function() {
return SpeechSynthesisWordBoundaryEventArgs_js_1.SpeechSynthesisWordBoundaryEventArgs;
} });
var SpeechSynthesisBookmarkEventArgs_js_1 = require_SpeechSynthesisBookmarkEventArgs();
Object.defineProperty(exports, "SpeechSynthesisBookmarkEventArgs", { enumerable: true, get: function() {
return SpeechSynthesisBookmarkEventArgs_js_1.SpeechSynthesisBookmarkEventArgs;
} });
var SpeechSynthesisVisemeEventArgs_js_1 = require_SpeechSynthesisVisemeEventArgs();
Object.defineProperty(exports, "SpeechSynthesisVisemeEventArgs", { enumerable: true, get: function() {
return SpeechSynthesisVisemeEventArgs_js_1.SpeechSynthesisVisemeEventArgs;
} });
var SpeechSynthesisBoundaryType_js_1 = require_SpeechSynthesisBoundaryType();
Object.defineProperty(exports, "SpeechSynthesisBoundaryType", { enumerable: true, get: function() {
return SpeechSynthesisBoundaryType_js_1.SpeechSynthesisBoundaryType;
} });
var SynthesisVoicesResult_js_1 = require_SynthesisVoicesResult();
Object.defineProperty(exports, "SynthesisVoicesResult", { enumerable: true, get: function() {
return SynthesisVoicesResult_js_1.SynthesisVoicesResult;
} });
var VoiceInfo_js_1 = require_VoiceInfo();
Object.defineProperty(exports, "SynthesisVoiceGender", { enumerable: true, get: function() {
return VoiceInfo_js_1.SynthesisVoiceGender;
} });
Object.defineProperty(exports, "SynthesisVoiceType", { enumerable: true, get: function() {
return VoiceInfo_js_1.SynthesisVoiceType;
} });
Object.defineProperty(exports, "VoiceInfo", { enumerable: true, get: function() {
return VoiceInfo_js_1.VoiceInfo;
} });
var SpeakerAudioDestination_js_1 = require_SpeakerAudioDestination();
Object.defineProperty(exports, "SpeakerAudioDestination", { enumerable: true, get: function() {
return SpeakerAudioDestination_js_1.SpeakerAudioDestination;
} });
var ConversationTranscriptionCanceledEventArgs_js_1 = require_ConversationTranscriptionCanceledEventArgs();
Object.defineProperty(exports, "ConversationTranscriptionCanceledEventArgs", { enumerable: true, get: function() {
return ConversationTranscriptionCanceledEventArgs_js_1.ConversationTranscriptionCanceledEventArgs;
} });
var MeetingTranscriptionCanceledEventArgs_js_1 = require_MeetingTranscriptionCanceledEventArgs2();
Object.defineProperty(exports, "MeetingTranscriptionCanceledEventArgs", { enumerable: true, get: function() {
return MeetingTranscriptionCanceledEventArgs_js_1.MeetingTranscriptionCanceledEventArgs;
} });
var PronunciationAssessmentGradingSystem_js_1 = require_PronunciationAssessmentGradingSystem();
Object.defineProperty(exports, "PronunciationAssessmentGradingSystem", { enumerable: true, get: function() {
return PronunciationAssessmentGradingSystem_js_1.PronunciationAssessmentGradingSystem;
} });
var PronunciationAssessmentGranularity_js_1 = require_PronunciationAssessmentGranularity();
Object.defineProperty(exports, "PronunciationAssessmentGranularity", { enumerable: true, get: function() {
return PronunciationAssessmentGranularity_js_1.PronunciationAssessmentGranularity;
} });
var PronunciationAssessmentConfig_js_1 = require_PronunciationAssessmentConfig();
Object.defineProperty(exports, "PronunciationAssessmentConfig", { enumerable: true, get: function() {
return PronunciationAssessmentConfig_js_1.PronunciationAssessmentConfig;
} });
var PronunciationAssessmentResult_js_1 = require_PronunciationAssessmentResult();
Object.defineProperty(exports, "PronunciationAssessmentResult", { enumerable: true, get: function() {
return PronunciationAssessmentResult_js_1.PronunciationAssessmentResult;
} });
var LanguageIdMode_js_1 = require_LanguageIdMode();
Object.defineProperty(exports, "LanguageIdMode", { enumerable: true, get: function() {
return LanguageIdMode_js_1.LanguageIdMode;
} });
var AvatarConfig_js_1 = require_AvatarConfig();
Object.defineProperty(exports, "AvatarConfig", { enumerable: true, get: function() {
return AvatarConfig_js_1.AvatarConfig;
} });
var AvatarEventArgs_js_1 = require_AvatarEventArgs();
Object.defineProperty(exports, "AvatarEventArgs", { enumerable: true, get: function() {
return AvatarEventArgs_js_1.AvatarEventArgs;
} });
var AvatarSynthesizer_js_1 = require_AvatarSynthesizer();
Object.defineProperty(exports, "AvatarSynthesizer", { enumerable: true, get: function() {
return AvatarSynthesizer_js_1.AvatarSynthesizer;
} });
var AvatarVideoFormat_js_1 = require_AvatarVideoFormat();
Object.defineProperty(exports, "AvatarVideoFormat", { enumerable: true, get: function() {
return AvatarVideoFormat_js_1.AvatarVideoFormat;
} });
Object.defineProperty(exports, "Coordinate", { enumerable: true, get: function() {
return AvatarVideoFormat_js_1.Coordinate;
} });
var AvatarWebRTCConnectionResult_js_1 = require_AvatarWebRTCConnectionResult();
Object.defineProperty(exports, "AvatarWebRTCConnectionResult", { enumerable: true, get: function() {
return AvatarWebRTCConnectionResult_js_1.AvatarWebRTCConnectionResult;
} });
var Diagnostics_js_1 = require_Diagnostics();
Object.defineProperty(exports, "Diagnostics", { enumerable: true, get: function() {
return Diagnostics_js_1.Diagnostics;
} });
var LogLevel_js_1 = require_LogLevel();
Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function() {
return LogLevel_js_1.LogLevel;
} });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/ProxyInfo.js
var require_ProxyInfo = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/ProxyInfo.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyInfo = void 0;
var Exports_js_1 = require_Exports3();
var ProxyInfo = class _ProxyInfo {
constructor(proxyHostName, proxyPort, proxyUserName, proxyPassword) {
this.privProxyHostName = proxyHostName;
this.privProxyPort = proxyPort;
this.privProxyUserName = proxyUserName;
this.privProxyPassword = proxyPassword;
}
static fromParameters(parameters) {
return new _ProxyInfo(parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyHostName), parseInt(parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyPort), 10), parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyUserName), parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_ProxyPassword));
}
static fromRecognizerConfig(config) {
return this.fromParameters(config.parameters);
}
get HostName() {
return this.privProxyHostName;
}
get Port() {
return this.privProxyPort;
}
get UserName() {
return this.privProxyUserName;
}
get Password() {
return this.privProxyPassword;
}
};
exports.ProxyInfo = ProxyInfo;
}
});
// ../../node_modules/bent/src/core.js
var require_core = __commonJS({
"../../node_modules/bent/src/core.js"(exports, module) {
"use strict";
var encodings = /* @__PURE__ */ new Set(["json", "buffer", "string"]);
module.exports = (mkrequest) => (...args) => {
const statusCodes = /* @__PURE__ */ 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);
};
}
});
// ../../node_modules/bent/src/browser.js
var require_browser2 = __commonJS({
"../../node_modules/bent/src/browser.js"(exports, module) {
"use strict";
var core = require_core();
var StatusError = 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 });
this.headers = {};
for (const [key, value] of res.headers.entries()) {
this.headers[key.toLowerCase()] = value;
}
}
};
var 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") {
} 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);
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/RestMessageAdapter.js
var require_RestMessageAdapter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/RestMessageAdapter.js"(exports) {
"use strict";
var __importDefault = exports && exports.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RestMessageAdapter = exports.RestRequestType = void 0;
var bent_1 = __importDefault(require_browser2());
var Exports_js_1 = require_Exports();
var RestRequestType;
(function(RestRequestType2) {
RestRequestType2["Get"] = "GET";
RestRequestType2["Post"] = "POST";
RestRequestType2["Delete"] = "DELETE";
RestRequestType2["File"] = "file";
})(RestRequestType = exports.RestRequestType || (exports.RestRequestType = {}));
var RestMessageAdapter = class {
constructor(configParams) {
if (!configParams) {
throw new Exports_js_1.ArgumentNullError("configParams");
}
this.privHeaders = configParams.headers;
this.privIgnoreCache = configParams.ignoreCache;
}
static extractHeaderValue(headerKey, headers) {
let headerValue = "";
try {
const arr = headers.trim().split(/[\r\n]+/);
const headerMap = {};
arr.forEach((line) => {
const parts = line.split(": ");
const header = parts.shift().toLowerCase();
const value = parts.join(": ");
headerMap[header] = value;
});
headerValue = headerMap[headerKey.toLowerCase()];
} catch (e) {
}
return headerValue;
}
set options(configParams) {
this.privHeaders = configParams.headers;
this.privIgnoreCache = configParams.ignoreCache;
}
setHeaders(key, value) {
this.privHeaders[key] = value;
}
request(method, uri, queryParams = {}, body = null) {
const responseReceivedDeferral = new Exports_js_1.Deferred();
const requestCommand = method === RestRequestType.File ? "POST" : method;
const handleRestResponse = (data, j = {}) => {
const 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
};
};
const send = (postData) => {
const sendRequest = (0, bent_1.default)(uri, requestCommand, this.privHeaders, 200, 201, 202, 204, 400, 401, 402, 403, 404);
const params = this.queryParams(queryParams) === "" ? "" : `?${this.queryParams(queryParams)}`;
sendRequest(params, postData).then(async (data) => {
if (method === RestRequestType.Delete || data.statusCode === 204) {
responseReceivedDeferral.resolve(handleRestResponse(data));
} else {
try {
const j = await data.json();
responseReceivedDeferral.resolve(handleRestResponse(data, j));
} catch {
responseReceivedDeferral.resolve(handleRestResponse(data));
}
}
}).catch((error) => {
responseReceivedDeferral.reject(error);
});
};
if (this.privIgnoreCache) {
this.privHeaders["Cache-Control"] = "no-cache";
}
if (method === RestRequestType.Post && body) {
this.privHeaders["content-type"] = "application/json";
this.privHeaders["Content-Type"] = "application/json";
}
send(body);
return responseReceivedDeferral.promise;
}
queryParams(params = {}) {
return Object.keys(params).map((k) => encodeURIComponent(k) + "=" + encodeURIComponent(params[k])).join("&");
}
};
exports.RestMessageAdapter = RestMessageAdapter;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/RestConfigBase.js
var require_RestConfigBase = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/RestConfigBase.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RestConfigBase = void 0;
var RestConfigBase = class _RestConfigBase {
static get requestOptions() {
return _RestConfigBase.privDefaultRequestOptions;
}
static get configParams() {
return _RestConfigBase.privDefaultParams;
}
static get restErrors() {
return _RestConfigBase.privRestErrors;
}
};
exports.RestConfigBase = RestConfigBase;
RestConfigBase.privDefaultRequestOptions = {
headers: {
Accept: "application/json"
},
ignoreCache: false,
timeout: 1e4
};
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"
};
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/Exports.js
var require_Exports4 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.browser/Exports.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() {
return m[k];
} });
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require_ConsoleLoggingListener(), exports);
__exportStar(require_IRecorder(), exports);
__exportStar(require_MicAudioSource(), exports);
__exportStar(require_FileAudioSource(), exports);
__exportStar(require_PCMRecorder(), exports);
__exportStar(require_WebsocketConnection(), exports);
__exportStar(require_WebsocketMessageAdapter(), exports);
__exportStar(require_ReplayableAudioNode(), exports);
__exportStar(require_ProxyInfo(), exports);
__exportStar(require_RestMessageAdapter(), exports);
__exportStar(require_RestConfigBase(), exports);
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/IntentConnectionFactory.js
var require_IntentConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/IntentConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentConnectionFactory = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports3();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var Exports_js_3 = require_Exports7();
var HeaderNames_js_1 = require_HeaderNames();
var IntentConnectionFactory = class extends ConnectionFactoryBase_js_1.ConnectionFactoryBase {
create(config, authInfo, connectionId) {
let endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint);
if (!endpoint) {
const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_IntentRegion);
const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region);
const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".sr.speech" + hostSuffix);
endpoint = host + "/speech/recognition/interactive/cognitiveservices/v1";
}
const queryParams = {
format: "simple",
language: config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage)
};
this.setCommonUrlParams(config, queryParams, endpoint);
const headers = {};
if (authInfo.token !== void 0 && authInfo.token !== "") {
headers[authInfo.headerName] = authInfo.token;
}
headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId;
config.parameters.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url, endpoint);
const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
return Promise.resolve(new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_3.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId));
}
getSpeechRegionFromIntentRegion(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;
}
}
};
exports.IntentConnectionFactory = IntentConnectionFactory;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeakerRecognitionConnectionFactory.js
var require_SpeakerRecognitionConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeakerRecognitionConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceProfileConnectionFactory = exports.SpeakerRecognitionConnectionFactory = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports3();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var Exports_js_3 = require_Exports7();
var HeaderNames_js_1 = require_HeaderNames();
var SpeakerRecognitionConnectionFactoryBase = class extends ConnectionFactoryBase_js_1.ConnectionFactoryBase {
create(config, authInfo, endpointPath, connectionId) {
let endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint);
if (!endpoint) {
const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region);
const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region);
const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, `wss://${region}.spr-frontend.speech${hostSuffix}`);
const scenario = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_SpeakerIdMode, "TextIndependentIdentification");
endpoint = `${host}/speaker/ws/${this.scenarioToPath(scenario)}/${endpointPath}`;
}
const queryParams = {
format: "simple",
language: config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage)
};
this.setCommonUrlParams(config, queryParams, endpoint);
const headers = {};
if (authInfo.token !== void 0 && authInfo.token !== "") {
headers[authInfo.headerName] = authInfo.token;
}
headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId;
headers[HeaderNames_js_1.HeaderNames.SpIDAuthKey] = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key);
config.parameters.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url, endpoint);
const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
return Promise.resolve(new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_3.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId));
}
scenarioToPath(mode) {
switch (mode) {
case "TextIndependentVerification":
case "2":
return "verification/text-independent";
case "TextDependentVerification":
case "1":
return "verification/text-dependent";
default:
return "identification/text-independent";
}
}
};
var SpeakerRecognitionConnectionFactory = class extends SpeakerRecognitionConnectionFactoryBase {
create(config, authInfo, connectionId) {
return super.create(config, authInfo, "recognition", connectionId);
}
};
exports.SpeakerRecognitionConnectionFactory = SpeakerRecognitionConnectionFactory;
var VoiceProfileConnectionFactory = class extends SpeakerRecognitionConnectionFactoryBase {
create(config, authInfo, connectionId) {
return super.create(config, authInfo, "profile", connectionId);
}
};
exports.VoiceProfileConnectionFactory = VoiceProfileConnectionFactory;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/RecognitionEvents.js
var require_RecognitionEvents = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/RecognitionEvents.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecognitionEndedEvent = exports.RecognitionCompletionStatus = exports.RecognitionStartedEvent = exports.ConnectingToServiceEvent = exports.ListeningStartedEvent = exports.RecognitionTriggeredEvent = exports.SpeechRecognitionEvent = void 0;
var Exports_js_1 = require_Exports();
var SpeechRecognitionEvent2 = class extends Exports_js_1.PlatformEvent {
constructor(eventName, requestId, sessionId, eventType = Exports_js_1.EventType.Info) {
super(eventName, eventType);
this.privRequestId = requestId;
this.privSessionId = sessionId;
}
get requestId() {
return this.privRequestId;
}
get sessionId() {
return this.privSessionId;
}
};
exports.SpeechRecognitionEvent = SpeechRecognitionEvent2;
var RecognitionTriggeredEvent = class extends SpeechRecognitionEvent2 {
constructor(requestId, sessionId, audioSourceId, audioNodeId) {
super("RecognitionTriggeredEvent", requestId, sessionId);
this.privAudioSourceId = audioSourceId;
this.privAudioNodeId = audioNodeId;
}
get audioSourceId() {
return this.privAudioSourceId;
}
get audioNodeId() {
return this.privAudioNodeId;
}
};
exports.RecognitionTriggeredEvent = RecognitionTriggeredEvent;
var ListeningStartedEvent = class extends SpeechRecognitionEvent2 {
constructor(requestId, sessionId, audioSourceId, audioNodeId) {
super("ListeningStartedEvent", requestId, sessionId);
this.privAudioSourceId = audioSourceId;
this.privAudioNodeId = audioNodeId;
}
get audioSourceId() {
return this.privAudioSourceId;
}
get audioNodeId() {
return this.privAudioNodeId;
}
};
exports.ListeningStartedEvent = ListeningStartedEvent;
var ConnectingToServiceEvent = class extends SpeechRecognitionEvent2 {
constructor(requestId, authFetchEventid, sessionId) {
super("ConnectingToServiceEvent", requestId, sessionId);
this.privAuthFetchEventid = authFetchEventid;
}
get authFetchEventid() {
return this.privAuthFetchEventid;
}
};
exports.ConnectingToServiceEvent = ConnectingToServiceEvent;
var RecognitionStartedEvent = class extends SpeechRecognitionEvent2 {
constructor(requestId, audioSourceId, audioNodeId, authFetchEventId, sessionId) {
super("RecognitionStartedEvent", requestId, sessionId);
this.privAudioSourceId = audioSourceId;
this.privAudioNodeId = audioNodeId;
this.privAuthFetchEventId = authFetchEventId;
}
get audioSourceId() {
return this.privAudioSourceId;
}
get audioNodeId() {
return this.privAudioNodeId;
}
get authFetchEventId() {
return this.privAuthFetchEventId;
}
};
exports.RecognitionStartedEvent = RecognitionStartedEvent;
var RecognitionCompletionStatus;
(function(RecognitionCompletionStatus2) {
RecognitionCompletionStatus2[RecognitionCompletionStatus2["Success"] = 0] = "Success";
RecognitionCompletionStatus2[RecognitionCompletionStatus2["AudioSourceError"] = 1] = "AudioSourceError";
RecognitionCompletionStatus2[RecognitionCompletionStatus2["AudioSourceTimeout"] = 2] = "AudioSourceTimeout";
RecognitionCompletionStatus2[RecognitionCompletionStatus2["AuthTokenFetchError"] = 3] = "AuthTokenFetchError";
RecognitionCompletionStatus2[RecognitionCompletionStatus2["AuthTokenFetchTimeout"] = 4] = "AuthTokenFetchTimeout";
RecognitionCompletionStatus2[RecognitionCompletionStatus2["UnAuthorized"] = 5] = "UnAuthorized";
RecognitionCompletionStatus2[RecognitionCompletionStatus2["ConnectTimeout"] = 6] = "ConnectTimeout";
RecognitionCompletionStatus2[RecognitionCompletionStatus2["ConnectError"] = 7] = "ConnectError";
RecognitionCompletionStatus2[RecognitionCompletionStatus2["ClientRecognitionActivityTimeout"] = 8] = "ClientRecognitionActivityTimeout";
RecognitionCompletionStatus2[RecognitionCompletionStatus2["UnknownError"] = 9] = "UnknownError";
})(RecognitionCompletionStatus = exports.RecognitionCompletionStatus || (exports.RecognitionCompletionStatus = {}));
var RecognitionEndedEvent = class extends SpeechRecognitionEvent2 {
constructor(requestId, audioSourceId, audioNodeId, authFetchEventId, sessionId, serviceTag, status, error) {
super("RecognitionEndedEvent", requestId, sessionId, status === RecognitionCompletionStatus.Success ? Exports_js_1.EventType.Info : Exports_js_1.EventType.Error);
this.privAudioSourceId = audioSourceId;
this.privAudioNodeId = audioNodeId;
this.privAuthFetchEventId = authFetchEventId;
this.privStatus = status;
this.privError = error;
this.privServiceTag = serviceTag;
}
get audioSourceId() {
return this.privAudioSourceId;
}
get audioNodeId() {
return this.privAudioNodeId;
}
get authFetchEventId() {
return this.privAuthFetchEventId;
}
get serviceTag() {
return this.privServiceTag;
}
get status() {
return this.privStatus;
}
get error() {
return this.privError;
}
};
exports.RecognitionEndedEvent = RecognitionEndedEvent;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechConnectionMessage.Internal.js
var require_SpeechConnectionMessage_Internal = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechConnectionMessage.Internal.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechConnectionMessage = void 0;
var Exports_js_1 = require_Exports();
var HeaderNames_js_1 = require_HeaderNames();
var SpeechConnectionMessage = class _SpeechConnectionMessage extends Exports_js_1.ConnectionMessage {
constructor(messageType, path, requestId, contentType, body, streamId, additionalHeaders, id) {
if (!path) {
throw new Exports_js_1.ArgumentNullError("path");
}
if (!requestId) {
throw new Exports_js_1.ArgumentNullError("requestId");
}
const headers = {};
headers[HeaderNames_js_1.HeaderNames.Path] = path;
headers[HeaderNames_js_1.HeaderNames.RequestId] = requestId;
headers[HeaderNames_js_1.HeaderNames.RequestTimestamp] = (/* @__PURE__ */ new Date()).toISOString();
if (contentType) {
headers[HeaderNames_js_1.HeaderNames.ContentType] = contentType;
}
if (streamId) {
headers[HeaderNames_js_1.HeaderNames.RequestStreamId] = streamId;
}
if (additionalHeaders) {
for (const headerName in additionalHeaders) {
if (headerName) {
headers[headerName] = additionalHeaders[headerName];
}
}
}
if (id) {
super(messageType, body, headers, id);
} else {
super(messageType, body, headers);
}
this.privPath = path;
this.privRequestId = requestId;
this.privContentType = contentType;
this.privStreamId = streamId;
this.privAdditionalHeaders = additionalHeaders;
}
get path() {
return this.privPath;
}
get requestId() {
return this.privRequestId;
}
get contentType() {
return this.privContentType;
}
get streamId() {
return this.privStreamId;
}
get additionalHeaders() {
return this.privAdditionalHeaders;
}
static fromConnectionMessage(message) {
let path = null;
let requestId = null;
let contentType = null;
let streamId = null;
const additionalHeaders = {};
if (message.headers) {
for (const headerName in message.headers) {
if (headerName) {
if (headerName.toLowerCase() === HeaderNames_js_1.HeaderNames.Path.toLowerCase()) {
path = message.headers[headerName];
} else if (headerName.toLowerCase() === HeaderNames_js_1.HeaderNames.RequestId.toLowerCase()) {
requestId = message.headers[headerName];
} else if (headerName.toLowerCase() === HeaderNames_js_1.HeaderNames.ContentType.toLowerCase()) {
contentType = message.headers[headerName];
} else if (headerName.toLowerCase() === HeaderNames_js_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);
}
};
exports.SpeechConnectionMessage = SpeechConnectionMessage;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseDetection/Segmentation.js
var require_Segmentation = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseDetection/Segmentation.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SegmentationMode = void 0;
var SegmentationMode;
(function(SegmentationMode2) {
SegmentationMode2["Normal"] = "Normal";
SegmentationMode2["Disabled"] = "Disabled";
SegmentationMode2["Custom"] = "Custom";
SegmentationMode2["Semantic"] = "Semantic";
})(SegmentationMode = exports.SegmentationMode || (exports.SegmentationMode = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/Translation/OnSuccess.js
var require_OnSuccess = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/Translation/OnSuccess.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NextAction = void 0;
var NextAction;
(function(NextAction2) {
NextAction2["None"] = "None";
NextAction2["Synthesize"] = "Synthesize";
})(NextAction = exports.NextAction || (exports.NextAction = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/Translation/InterimResults.js
var require_InterimResults = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/Translation/InterimResults.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Mode = void 0;
var Mode;
(function(Mode2) {
Mode2["None"] = "None";
Mode2["Always"] = "Always";
})(Mode = exports.Mode || (exports.Mode = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/LanguageId/LanguageIdContext.js
var require_LanguageIdContext = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/LanguageId/LanguageIdContext.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LanguageIdDetectionPriority = exports.LanguageIdDetectionMode = void 0;
var LanguageIdDetectionMode;
(function(LanguageIdDetectionMode2) {
LanguageIdDetectionMode2["DetectAtAudioStart"] = "DetectAtAudioStart";
LanguageIdDetectionMode2["DetectContinuous"] = "DetectContinuous";
LanguageIdDetectionMode2["DetectSegments"] = "DetectSegments";
})(LanguageIdDetectionMode = exports.LanguageIdDetectionMode || (exports.LanguageIdDetectionMode = {}));
var LanguageIdDetectionPriority;
(function(LanguageIdDetectionPriority2) {
LanguageIdDetectionPriority2["Auto"] = "Auto";
LanguageIdDetectionPriority2["PrioritizeLatency"] = "PrioritizeLatency";
LanguageIdDetectionPriority2["PrioritizeAccuracy"] = "PrioritizeAccuracy";
})(LanguageIdDetectionPriority = exports.LanguageIdDetectionPriority || (exports.LanguageIdDetectionPriority = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/LanguageId/OnSuccess.js
var require_OnSuccess2 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/LanguageId/OnSuccess.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NextAction = void 0;
var NextAction;
(function(NextAction2) {
NextAction2["Recognize"] = "Recognize";
NextAction2["None"] = "None";
})(NextAction = exports.NextAction || (exports.NextAction = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/LanguageId/OnUnknown.js
var require_OnUnknown = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/LanguageId/OnUnknown.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OnUnknownAction = void 0;
var OnUnknownAction;
(function(OnUnknownAction2) {
OnUnknownAction2["RecognizeWithDefaultLanguage"] = "RecognizeWithDefaultLanguage";
OnUnknownAction2["None"] = "None";
})(OnUnknownAction = exports.OnUnknownAction || (exports.OnUnknownAction = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseOutput/InterimResults.js
var require_InterimResults2 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseOutput/InterimResults.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResultType = void 0;
var ResultType;
(function(ResultType2) {
ResultType2["Auto"] = "Auto";
ResultType2["StableFragment"] = "StableFragment";
ResultType2["Hypothesis"] = "Hypothesis";
ResultType2["None"] = "None";
})(ResultType = exports.ResultType || (exports.ResultType = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseOutput/PhraseResults.js
var require_PhraseResults = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseOutput/PhraseResults.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PhraseResultOutputType = void 0;
var PhraseResultOutputType;
(function(PhraseResultOutputType2) {
PhraseResultOutputType2["Always"] = "Always";
PhraseResultOutputType2["None"] = "None";
})(PhraseResultOutputType = exports.PhraseResultOutputType || (exports.PhraseResultOutputType = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseDetection/OnSuccess.js
var require_OnSuccess3 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseDetection/OnSuccess.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NextAction = void 0;
var NextAction;
(function(NextAction2) {
NextAction2["None"] = "None";
NextAction2["Translate"] = "Translate";
})(NextAction = exports.NextAction || (exports.NextAction = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceRecognizerBase.js
var require_ServiceRecognizerBase = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceRecognizerBase.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceRecognizerBase = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports();
var Exports_js_3 = require_Exports3();
var Exports_js_4 = require_Exports7();
var SpeechConnectionMessage_Internal_js_1 = require_SpeechConnectionMessage_Internal();
var Segmentation_js_1 = require_Segmentation();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var OnSuccess_js_1 = require_OnSuccess();
var InterimResults_js_1 = require_InterimResults();
var LanguageIdContext_js_1 = require_LanguageIdContext();
var OnSuccess_js_2 = require_OnSuccess2();
var OnUnknown_js_1 = require_OnUnknown();
var InterimResults_js_2 = require_InterimResults2();
var PhraseResults_js_1 = require_PhraseResults();
var OnSuccess_js_3 = require_OnSuccess3();
var ServiceRecognizerBase = class _ServiceRecognizerBase {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) {
this.privConnectionConfigurationPromise = void 0;
this.privConnectionPromise = void 0;
this.privSetTimeout = setTimeout;
this.privIsLiveAudio = false;
this.privAverageBytesPerMs = 0;
this.privEnableSpeakerId = false;
this.privExpectContentAssessmentResponse = false;
this.recognizeOverride = void 0;
this.recognizeSpeaker = void 0;
this.disconnectOverride = void 0;
this.receiveMessageOverride = void 0;
this.sendPrePayloadJSONOverride = void 0;
this.postConnectImplOverride = void 0;
this.configConnectionOverride = void 0;
this.handleSpeechPhraseMessage = void 0;
this.handleSpeechHypothesisMessage = void 0;
if (!authentication) {
throw new Exports_js_2.ArgumentNullError("authentication");
}
if (!connectionFactory) {
throw new Exports_js_2.ArgumentNullError("connectionFactory");
}
if (!audioSource) {
throw new Exports_js_2.ArgumentNullError("audioSource");
}
if (!recognizerConfig) {
throw new Exports_js_2.ArgumentNullError("recognizerConfig");
}
this.privEnableSpeakerId = recognizerConfig.isSpeakerDiarizationEnabled;
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_js_4.RequestSession(this.privAudioSource.id());
this.privConnectionEvents = new Exports_js_2.EventSource();
this.privServiceEvents = new Exports_js_2.EventSource();
this.privDynamicGrammar = new Exports_js_4.DynamicGrammarBuilder();
this.privSpeechContext = new Exports_js_4.SpeechContext(this.privDynamicGrammar);
this.privAgentConfig = new Exports_js_4.AgentConfig();
const webWorkerLoadType = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.WebWorkerLoadType, "on").toLowerCase();
if (webWorkerLoadType === "on" && typeof Blob !== "undefined" && typeof Worker !== "undefined") {
this.privSetTimeout = Exports_js_2.Timeout.setTimeout;
} else {
if (typeof window !== "undefined") {
this.privSetTimeout = window.setTimeout.bind(window);
}
if (typeof globalThis !== "undefined") {
this.privSetTimeout = globalThis.setTimeout.bind(globalThis);
}
}
this.connectionEvents.attach((connectionEvent) => {
if (connectionEvent.name === "ConnectionClosedEvent") {
const connectionClosedEvent = connectionEvent;
if (connectionClosedEvent.statusCode === 1003 || connectionClosedEvent.statusCode === 1007 || connectionClosedEvent.statusCode === 1002 || connectionClosedEvent.statusCode === 4e3 || this.privRequestSession.numConnectionAttempts > this.privRecognizerConfig.maxRetryCount) {
void this.cancelRecognitionLocal(Exports_js_3.CancellationReason.Error, connectionClosedEvent.statusCode === 1007 ? Exports_js_3.CancellationErrorCode.BadRequestParameters : Exports_js_3.CancellationErrorCode.ConnectionFailure, `${connectionClosedEvent.reason} websocket error code: ${connectionClosedEvent.statusCode}`);
}
}
});
if (this.privEnableSpeakerId) {
this.privDiarizationSessionId = (0, Exports_js_2.createNoDashGuid)();
}
}
setTranslationJson() {
const targetLanguages = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, void 0);
if (targetLanguages !== void 0) {
const languages = targetLanguages.split(",");
const translationVoice = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice, void 0);
const categoryId = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationCategoryId, void 0);
const action = translationVoice !== void 0 ? OnSuccess_js_1.NextAction.Synthesize : OnSuccess_js_1.NextAction.None;
this.privSpeechContext.getContext().translation = {
onPassthrough: { action },
onSuccess: { action },
output: {
includePassThroughResults: true,
interimResults: { mode: InterimResults_js_1.Mode.Always }
},
targetLanguages: languages
};
if (categoryId !== void 0) {
this.privSpeechContext.getContext().translation.category = categoryId;
}
if (translationVoice !== void 0) {
const languageToVoiceMap = {};
for (const lang of languages) {
languageToVoiceMap[lang] = translationVoice;
}
this.privSpeechContext.getContext().synthesis = {
defaultVoices: languageToVoiceMap
};
}
const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {};
phraseDetection.onSuccess = { action: OnSuccess_js_3.NextAction.Translate };
phraseDetection.onInterim = { action: OnSuccess_js_3.NextAction.Translate };
this.privSpeechContext.getContext().phraseDetection = phraseDetection;
}
}
setSpeechSegmentationTimeoutJson() {
const speechSegmentationSilenceTimeoutMs = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.Speech_SegmentationSilenceTimeoutMs, void 0);
const speechSegmentationMaximumTimeMs = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.Speech_SegmentationMaximumTimeMs, void 0);
const speechSegmentationStrategy = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.Speech_SegmentationStrategy, void 0);
const segmentation = {
mode: Segmentation_js_1.SegmentationMode.Normal
};
let configuredSegment = false;
if (speechSegmentationStrategy !== void 0) {
configuredSegment = true;
let segMode = Segmentation_js_1.SegmentationMode.Normal;
switch (speechSegmentationStrategy.toLowerCase()) {
case "default":
break;
case "time":
segMode = Segmentation_js_1.SegmentationMode.Custom;
break;
case "semantic":
segMode = Segmentation_js_1.SegmentationMode.Semantic;
break;
}
segmentation.mode = segMode;
}
if (speechSegmentationSilenceTimeoutMs !== void 0) {
configuredSegment = true;
const segmentationSilenceTimeoutMs = parseInt(speechSegmentationSilenceTimeoutMs, 10);
segmentation.mode = Segmentation_js_1.SegmentationMode.Custom;
segmentation.segmentationSilenceTimeoutMs = segmentationSilenceTimeoutMs;
}
if (speechSegmentationMaximumTimeMs !== void 0) {
configuredSegment = true;
const segmentationMaximumTimeMs = parseInt(speechSegmentationMaximumTimeMs, 10);
segmentation.mode = Segmentation_js_1.SegmentationMode.Custom;
segmentation.segmentationForcedTimeoutMs = segmentationMaximumTimeMs;
}
if (configuredSegment) {
const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {};
phraseDetection.mode = this.recognitionMode;
switch (this.recognitionMode) {
case PhraseDetectionContext_js_1.RecognitionMode.Conversation:
phraseDetection.conversation = phraseDetection.conversation ?? { segmentation: {} };
phraseDetection.conversation.segmentation = segmentation;
break;
case PhraseDetectionContext_js_1.RecognitionMode.Interactive:
phraseDetection.interactive = phraseDetection.interactive ?? { segmentation: {} };
phraseDetection.interactive.segmentation = segmentation;
break;
case PhraseDetectionContext_js_1.RecognitionMode.Dictation:
phraseDetection.dictation = phraseDetection.dictation ?? {};
phraseDetection.dictation.segmentation = segmentation;
break;
}
this.privSpeechContext.getContext().phraseDetection = phraseDetection;
}
}
setLanguageIdJson() {
const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {};
if (this.privRecognizerConfig.autoDetectSourceLanguages !== void 0) {
const sourceLanguages = this.privRecognizerConfig.autoDetectSourceLanguages.split(",");
if (sourceLanguages.length === 1 && sourceLanguages[0] === Exports_js_4.AutoDetectSourceLanguagesOpenRangeOptionName) {
sourceLanguages[0] = "UND";
}
let speechContextLidMode;
if (this.privRecognizerConfig.languageIdMode === "Continuous") {
speechContextLidMode = LanguageIdContext_js_1.LanguageIdDetectionMode.DetectContinuous;
} else {
speechContextLidMode = LanguageIdContext_js_1.LanguageIdDetectionMode.DetectAtAudioStart;
}
this.privSpeechContext.getContext().languageId = {
languages: sourceLanguages,
mode: speechContextLidMode,
onSuccess: { action: OnSuccess_js_2.NextAction.Recognize },
onUnknown: { action: OnUnknown_js_1.OnUnknownAction.None },
priority: LanguageIdContext_js_1.LanguageIdDetectionPriority.PrioritizeLatency
};
this.privSpeechContext.getContext().phraseOutput = {
interimResults: {
resultType: InterimResults_js_2.ResultType.Auto
},
phraseResults: {
resultType: PhraseResults_js_1.PhraseResultOutputType.Always
}
};
const customModels = this.privRecognizerConfig.sourceLanguageModels;
if (customModels !== void 0) {
phraseDetection.customModels = customModels;
phraseDetection.onInterim = { action: OnSuccess_js_3.NextAction.None };
phraseDetection.onSuccess = { action: OnSuccess_js_3.NextAction.None };
}
}
this.privSpeechContext.getContext().phraseDetection = phraseDetection;
}
setOutputDetailLevelJson() {
if (this.privEnableSpeakerId) {
const requestWordLevelTimestamps = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "false").toLowerCase();
if (requestWordLevelTimestamps === "true") {
this.privSpeechContext.setWordLevelTimings();
} else {
const outputFormat = this.privRecognizerConfig.parameters.getProperty(Exports_js_4.OutputFormatPropertyName, Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]).toLowerCase();
if (outputFormat === Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Detailed].toLocaleLowerCase()) {
this.privSpeechContext.setDetailedOutputFormat();
}
}
}
}
get isSpeakerDiarizationEnabled() {
return this.privEnableSpeakerId;
}
get audioSource() {
return this.privAudioSource;
}
get speechContext() {
return this.privSpeechContext;
}
get dynamicGrammar() {
return this.privDynamicGrammar;
}
get agentConfig() {
return this.privAgentConfig;
}
set conversationTranslatorToken(token) {
this.privRecognizerConfig.parameters.setProperty(Exports_js_3.PropertyId.ConversationTranslator_Token, token);
}
set voiceProfileType(type) {
this.privRecognizerConfig.parameters.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_SpeakerIdMode, type);
}
set authentication(auth) {
this.privAuthentication = auth;
}
isDisposed() {
return this.privIsDisposed;
}
async dispose(reason) {
this.privIsDisposed = true;
if (this.privConnectionPromise !== void 0) {
try {
const connection = await this.privConnectionPromise;
await connection.dispose(reason);
} catch (error) {
return;
}
}
}
get connectionEvents() {
return this.privConnectionEvents;
}
get serviceEvents() {
return this.privServiceEvents;
}
get recognitionMode() {
return this.privRecognizerConfig.recognitionMode;
}
async recognize(recoMode, successCallback, errorCallBack) {
if (this.recognizeOverride !== void 0) {
await this.recognizeOverride(recoMode, successCallback, errorCallBack);
return;
}
this.privConnectionConfigurationPromise = void 0;
this.privRecognizerConfig.recognitionMode = recoMode;
if (this.privRecognizerConfig.recognitionEndpointVersion === "2") {
const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {};
phraseDetection.mode = recoMode;
this.privSpeechContext.getContext().phraseDetection = phraseDetection;
}
this.setLanguageIdJson();
this.setTranslationJson();
if (this.privRecognizerConfig.autoDetectSourceLanguages !== void 0 && this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, void 0) !== void 0) {
this.setupTranslationWithLanguageId();
}
this.setSpeechSegmentationTimeoutJson();
this.setOutputDetailLevelJson();
this.privSuccessCallback = successCallback;
this.privErrorCallback = errorCallBack;
this.privRequestSession.startNewRecognition();
this.privRequestSession.listenForServiceTelemetry(this.privAudioSource.events);
const conPromise = this.connectImpl();
let audioNode;
try {
const audioStreamNode = await this.audioSource.attach(this.privRequestSession.audioNodeId);
const format2 = await this.audioSource.format;
const deviceInfo = await this.audioSource.deviceInfo;
this.privIsLiveAudio = deviceInfo.type && deviceInfo.type === Exports_js_4.type.Microphones;
audioNode = new Exports_js_1.ReplayableAudioNode(audioStreamNode, format2.avgBytesPerSec);
await this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false);
this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo };
} catch (error) {
await this.privRequestSession.onStopRecognizing();
throw error;
}
try {
await conPromise;
} catch (error) {
await this.cancelRecognitionLocal(Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.ConnectionFailure, error);
return;
}
const sessionStartEventArgs = new Exports_js_3.SessionEventArgs(this.privRequestSession.sessionId);
if (!!this.privRecognizer.sessionStarted) {
this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs);
}
void this.receiveMessage();
const audioSendPromise = this.sendAudio(audioNode);
audioSendPromise.catch(async (error) => {
await this.cancelRecognitionLocal(Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.RuntimeError, error);
});
return;
}
async stopRecognizing() {
if (this.privRequestSession.isRecognizing) {
try {
await this.audioSource.turnOff();
await this.sendFinalAudio();
await this.privRequestSession.onStopRecognizing();
await this.privRequestSession.turnCompletionPromise;
} finally {
await this.privRequestSession.dispose();
}
}
return;
}
async connect() {
await this.connectImpl();
return Promise.resolve();
}
connectAsync(cb, err) {
this.connectImpl().then(() => {
try {
if (!!cb) {
cb();
}
} catch (e) {
if (!!err) {
err(e);
}
}
}, (reason) => {
try {
if (!!err) {
err(reason);
}
} catch (error) {
}
});
}
async disconnect() {
await this.cancelRecognitionLocal(Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.NoError, "Disconnecting");
if (this.disconnectOverride !== void 0) {
await this.disconnectOverride();
}
if (this.privConnectionPromise !== void 0) {
try {
await (await this.privConnectionPromise).dispose();
} catch (error) {
}
}
this.privConnectionPromise = void 0;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
sendMessage(message) {
return;
}
async sendNetworkMessage(path, payload) {
const type = typeof payload === "string" ? Exports_js_2.MessageType.Text : Exports_js_2.MessageType.Binary;
const contentType = typeof payload === "string" ? "application/json" : "";
const connection = await this.fetchConnection();
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(type, path, this.privRequestSession.requestId, contentType, payload));
}
set activityTemplate(messagePayload) {
this.privActivityTemplate = messagePayload;
}
get activityTemplate() {
return this.privActivityTemplate;
}
set expectContentAssessmentResponse(value) {
this.privExpectContentAssessmentResponse = value;
}
async sendTelemetryData() {
const telemetryData = this.privRequestSession.getTelemetry();
if (_ServiceRecognizerBase.telemetryDataEnabled !== true || this.privIsDisposed || null === telemetryData) {
return;
}
if (!!_ServiceRecognizerBase.telemetryData) {
try {
_ServiceRecognizerBase.telemetryData(telemetryData);
} catch {
}
}
const connection = await this.fetchConnection();
await connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "telemetry", this.privRequestSession.requestId, "application/json", telemetryData));
}
// Cancels recognition.
async cancelRecognitionLocal(cancellationReason, errorCode, error) {
if (!!this.privRequestSession.isRecognizing) {
await this.privRequestSession.onStopRecognizing();
this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, cancellationReason, errorCode, error);
}
}
async receiveMessage() {
try {
if (this.privIsDisposed) {
return;
}
let connection = await this.fetchConnection();
const message = await connection.read();
if (this.receiveMessageOverride !== void 0) {
return this.receiveMessageOverride();
}
if (!message) {
return this.receiveMessage();
}
this.privServiceHasSentMessage = true;
const connectionMessage = SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage.fromConnectionMessage(message);
if (connectionMessage.requestId.toLowerCase() === this.privRequestSession.requestId.toLowerCase()) {
switch (connectionMessage.path.toLowerCase()) {
case "turn.start":
this.privMustReportEndOfStream = true;
this.privRequestSession.onServiceTurnStartResponse();
break;
case "speech.startdetected":
const speechStartDetected = Exports_js_4.SpeechDetected.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
const speechStartEventArgs = new Exports_js_3.RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId);
if (!!this.privRecognizer.speechStartDetected) {
this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs);
}
break;
case "speech.enddetected":
let json;
if (connectionMessage.textBody.length > 0) {
json = connectionMessage.textBody;
} else {
json = "{ Offset: 0 }";
}
const speechStopDetected = Exports_js_4.SpeechDetected.fromJSON(json, this.privRequestSession.currentTurnAudioOffset);
const speechStopEventArgs = new Exports_js_3.RecognitionEventArgs(speechStopDetected.Offset + this.privRequestSession.currentTurnAudioOffset, this.privRequestSession.sessionId);
if (!!this.privRecognizer.speechEndDetected) {
this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs);
}
break;
case "turn.end":
await this.sendTelemetryData();
if (this.privRequestSession.isSpeechEnded && this.privMustReportEndOfStream) {
this.privMustReportEndOfStream = false;
await this.cancelRecognitionLocal(Exports_js_3.CancellationReason.EndOfStream, Exports_js_3.CancellationErrorCode.NoError, void 0);
}
const sessionStopEventArgs = new Exports_js_3.SessionEventArgs(this.privRequestSession.sessionId);
await this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition);
if (!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing) {
if (!!this.privRecognizer.sessionStopped) {
this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs);
}
return;
} else {
connection = await this.fetchConnection();
await this.sendPrePayloadJSON(connection);
}
break;
default:
if (!await this.processTypeSpecificMessages(connectionMessage)) {
if (!!this.privServiceEvents) {
this.serviceEvents.onEvent(new Exports_js_2.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));
}
}
}
}
return this.receiveMessage();
} catch (error) {
return null;
}
}
updateSpeakerDiarizationAudioOffset() {
const bytesSent = this.privRequestSession.recognitionBytesSent;
const audioOffsetMs = this.privAverageBytesPerMs !== 0 ? bytesSent / this.privAverageBytesPerMs : 0;
this.privSpeechContext.setSpeakerDiarizationAudioOffsetMs(audioOffsetMs);
}
sendSpeechContext(connection, generateNewRequestId) {
if (this.privEnableSpeakerId) {
this.updateSpeakerDiarizationAudioOffset();
}
const speechContextJson = this.speechContext.toJSON();
if (generateNewRequestId) {
this.privRequestSession.onSpeechContext();
}
if (speechContextJson) {
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "speech.context", this.privRequestSession.requestId, "application/json", speechContextJson));
}
return;
}
setupTranslationWithLanguageId() {
const targetLanguages = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationToLanguages, void 0);
const hasLanguageId = this.privRecognizerConfig.autoDetectSourceLanguages !== void 0;
if (targetLanguages !== void 0 && hasLanguageId) {
this.privSpeechContext.getContext().phraseOutput = {
interimResults: {
resultType: InterimResults_js_2.ResultType.None
},
phraseResults: {
resultType: PhraseResults_js_1.PhraseResultOutputType.None
}
};
const translationContext = this.privSpeechContext.getContext().translation;
if (translationContext) {
const customModels = this.privRecognizerConfig.sourceLanguageModels;
if (customModels !== void 0 && customModels.length > 0) {
const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {};
phraseDetection.customModels = customModels;
this.privSpeechContext.getContext().phraseDetection = phraseDetection;
}
const translationVoice = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_TranslationVoice, void 0);
if (translationVoice !== void 0) {
translationContext.onSuccess = { action: OnSuccess_js_1.NextAction.Synthesize };
translationContext.onPassthrough = { action: OnSuccess_js_1.NextAction.Synthesize };
}
}
}
}
noOp() {
return;
}
// Encapsulated for derived service recognizers that need to send additional JSON
async sendPrePayloadJSON(connection, generateNewRequestId = true) {
if (this.sendPrePayloadJSONOverride !== void 0) {
return this.sendPrePayloadJSONOverride(connection);
}
await this.sendSpeechContext(connection, generateNewRequestId);
await this.sendWaveHeader(connection);
return;
}
async sendWaveHeader(connection) {
const format2 = await this.audioSource.format;
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Binary, "audio", this.privRequestSession.requestId, "audio/x-wav", format2.header));
}
// Establishes a websocket connection to the end point.
connectImpl() {
if (this.privConnectionPromise !== void 0) {
return this.privConnectionPromise.then((connection) => {
if (connection.state() === Exports_js_2.ConnectionState.Disconnected) {
this.privConnectionId = null;
this.privConnectionPromise = void 0;
this.privServiceHasSentMessage = false;
return this.connectImpl();
}
return this.privConnectionPromise;
}, () => {
this.privConnectionId = null;
this.privConnectionPromise = void 0;
this.privServiceHasSentMessage = false;
return this.connectImpl();
});
}
this.privConnectionPromise = this.retryableConnect();
this.privConnectionPromise.catch(() => {
});
if (this.postConnectImplOverride !== void 0) {
return this.postConnectImplOverride(this.privConnectionPromise);
}
return this.privConnectionPromise;
}
sendSpeechServiceConfig(connection, requestSession, SpeechServiceConfigJson) {
requestSession.onSpeechContext();
if (_ServiceRecognizerBase.telemetryDataEnabled !== true) {
const withTelemetry = JSON.parse(SpeechServiceConfigJson);
const replacement = {
context: {
system: withTelemetry.context.system
}
};
SpeechServiceConfigJson = JSON.stringify(replacement);
}
if (this.privRecognizerConfig.parameters.getProperty("f0f5debc-f8c9-4892-ac4b-90a7ab359fd2", "false").toLowerCase() === "true") {
const 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_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "speech.config", requestSession.requestId, "application/json", SpeechServiceConfigJson));
}
return;
}
async fetchConnection() {
if (this.privConnectionConfigurationPromise !== void 0) {
return this.privConnectionConfigurationPromise.then((connection) => {
if (connection.state() === Exports_js_2.ConnectionState.Disconnected) {
this.privConnectionId = null;
this.privConnectionConfigurationPromise = void 0;
this.privServiceHasSentMessage = false;
return this.fetchConnection();
}
return this.privConnectionConfigurationPromise;
}, () => {
this.privConnectionId = null;
this.privConnectionConfigurationPromise = void 0;
this.privServiceHasSentMessage = false;
return this.fetchConnection();
});
}
this.privConnectionConfigurationPromise = this.configureConnection();
return await this.privConnectionConfigurationPromise;
}
async sendAudio(audioStreamNode) {
const audioFormat = await this.audioSource.format;
this.privAverageBytesPerMs = audioFormat.avgBytesPerSec / 1e3;
let nextSendTime = Date.now();
const fastLaneSizeMs = this.privRecognizerConfig.parameters.getProperty("SPEECH-TransmitLengthBeforThrottleMs", "5000");
const maxSendUnthrottledBytes = audioFormat.avgBytesPerSec / 1e3 * parseInt(fastLaneSizeMs, 10);
const startRecogNumber = this.privRequestSession.recogNumber;
const readAndUploadCycle = async () => {
if (!this.privIsDisposed && !this.privRequestSession.isSpeechEnded && this.privRequestSession.isRecognizing && this.privRequestSession.recogNumber === startRecogNumber) {
const connection = await this.fetchConnection();
const audioStreamChunk = await audioStreamNode.read();
if (this.privRequestSession.isSpeechEnded) {
return;
}
let payload;
let sendDelay;
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) {
await this.delay(sendDelay);
}
if (payload !== null) {
nextSendTime = Date.now() + payload.byteLength * 1e3 / (audioFormat.avgBytesPerSec * 2);
}
if (!this.privIsDisposed && !this.privRequestSession.isSpeechEnded && this.privRequestSession.isRecognizing && this.privRequestSession.recogNumber === startRecogNumber) {
connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Binary, "audio", this.privRequestSession.requestId, null, payload)).catch(() => {
this.privRequestSession.onServiceTurnEndResponse(this.privRecognizerConfig.isContinuousRecognition).catch(() => {
});
});
if (!audioStreamChunk?.isEnd) {
return readAndUploadCycle();
} else {
if (!this.privIsLiveAudio) {
this.privRequestSession.onSpeechEnded();
}
}
}
}
};
return readAndUploadCycle();
}
async retryableConnect() {
let isUnAuthorized = false;
this.privAuthFetchEventId = (0, Exports_js_2.createNoDashGuid)();
const sessionId = this.privRequestSession.sessionId;
this.privConnectionId = sessionId !== void 0 ? sessionId : (0, Exports_js_2.createNoDashGuid)();
this.privRequestSession.onPreConnectionStart(this.privAuthFetchEventId, this.privConnectionId);
let lastStatusCode = 0;
let lastReason = "";
while (this.privRequestSession.numConnectionAttempts <= this.privRecognizerConfig.maxRetryCount) {
this.privRequestSession.onRetryConnection();
const authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId);
const auth = await authPromise;
await this.privRequestSession.onAuthCompleted(false);
const connection = await this.privConnectionFactory.create(this.privRecognizerConfig, auth, this.privConnectionId);
this.privRequestSession.listenForServiceTelemetry(connection.events);
connection.events.attach((event) => {
this.connectionEvents.onEvent(event);
});
const response = await connection.open();
if (response.statusCode === 200) {
await this.privRequestSession.onConnectionEstablishCompleted(response.statusCode);
return Promise.resolve(connection);
} else if (response.statusCode === 1006) {
isUnAuthorized = true;
}
lastStatusCode = response.statusCode;
lastReason = response.reason;
}
await this.privRequestSession.onConnectionEstablishCompleted(lastStatusCode, lastReason);
return Promise.reject(`Unable to contact server. StatusCode: ${lastStatusCode}, ${this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Endpoint)} Reason: ${lastReason}`);
}
delay(delayMs) {
return new Promise((resolve) => this.privSetTimeout(resolve, delayMs));
}
writeBufferToConsole(buffer) {
let out = "Buffer Size: ";
if (null === buffer) {
out += "null";
} else {
const readView = new Uint8Array(buffer);
out += `${buffer.byteLength}\r
`;
for (let i = 0; i < buffer.byteLength; i++) {
out += readView[i].toString(16).padStart(2, "0") + " ";
if ((i + 1) % 16 === 0) {
console.info(out);
out = "";
}
}
}
console.info(out);
}
async sendFinalAudio() {
const connection = await this.fetchConnection();
await connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Binary, "audio", this.privRequestSession.requestId, null, null));
return;
}
// Takes an established websocket connection to the endpoint and sends speech configuration information.
async configureConnection() {
const connection = await this.connectImpl();
if (this.configConnectionOverride !== void 0) {
return this.configConnectionOverride(connection);
}
await this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize());
await this.sendPrePayloadJSON(connection, false);
return connection;
}
};
exports.ServiceRecognizerBase = ServiceRecognizerBase;
ServiceRecognizerBase.telemetryDataEnabled = true;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ConversationServiceRecognizer.js
var require_ConversationServiceRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ConversationServiceRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationServiceRecognizer = void 0;
var Exports_js_1 = require_Exports3();
var Exports_js_2 = require_Exports7();
var ConversationServiceRecognizer = class extends Exports_js_2.ServiceRecognizerBase {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) {
super(authentication, connectionFactory, audioSource, recognizerConfig, recognizer);
this.handleSpeechPhraseMessage = async (textBody) => this.handleSpeechPhrase(textBody);
this.handleSpeechHypothesisMessage = (textBody) => this.handleSpeechHypothesis(textBody);
}
processTypeSpecificMessages(connectionMessage) {
void connectionMessage;
return;
}
handleRecognizedCallback(result, offset, sessionId) {
void result;
void offset;
void sessionId;
return;
}
handleRecognizingCallback(result, duration, sessionId) {
void result;
void duration;
void sessionId;
return;
}
async processSpeechMessages(connectionMessage) {
let processed = false;
switch (connectionMessage.path.toLowerCase()) {
case "speech.hypothesis":
case "speech.fragment":
if (!!this.handleSpeechHypothesisMessage) {
this.handleSpeechHypothesisMessage(connectionMessage.textBody);
}
processed = true;
break;
case "speech.phrase":
if (!!this.handleSpeechPhraseMessage) {
await this.handleSpeechPhraseMessage(connectionMessage.textBody);
}
processed = true;
break;
default:
break;
}
return processed;
}
cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
void sessionId;
void requestId;
void cancellationReason;
void errorCode;
void error;
}
async handleSpeechPhrase(textBody) {
const simple = Exports_js_2.SimpleSpeechPhrase.fromJSON(textBody, this.privRequestSession.currentTurnAudioOffset);
const resultReason = Exports_js_2.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus);
let result;
const resultProps = new Exports_js_1.PropertyCollection();
resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, textBody);
this.privRequestSession.onPhraseRecognized(simple.Offset + simple.Duration);
if (Exports_js_1.ResultReason.Canceled === resultReason) {
const cancelReason = Exports_js_2.EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus);
const cancellationErrorCode = Exports_js_2.EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus);
await this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_js_2.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode));
} else {
if (simple.RecognitionStatus !== Exports_js_2.RecognitionStatus.EndOfDictation) {
if (this.privRecognizerConfig.parameters.getProperty(Exports_js_2.OutputFormatPropertyName) === Exports_js_1.OutputFormat[Exports_js_1.OutputFormat.Simple]) {
result = new Exports_js_1.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, simple.DisplayText, simple.Duration, simple.Offset, simple.Language, simple.LanguageDetectionConfidence, simple.SpeakerId, void 0, simple.asJson(), resultProps);
} else {
const detailed = Exports_js_2.DetailedSpeechPhrase.fromJSON(textBody, this.privRequestSession.currentTurnAudioOffset);
result = new Exports_js_1.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, detailed.Text, detailed.Duration, detailed.Offset, detailed.Language, detailed.LanguageDetectionConfidence, detailed.SpeakerId, void 0, detailed.asJson(), resultProps);
}
this.handleRecognizedCallback(result, result.offset, this.privRequestSession.sessionId);
}
}
}
handleSpeechHypothesis(textBody) {
const hypothesis = Exports_js_2.SpeechHypothesis.fromJSON(textBody, this.privRequestSession.currentTurnAudioOffset);
const resultProps = new Exports_js_1.PropertyCollection();
resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, textBody);
const result = new Exports_js_1.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_js_1.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, hypothesis.Offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, hypothesis.SpeakerId, void 0, hypothesis.asJson(), resultProps);
this.privRequestSession.onHypothesis(hypothesis.Offset);
this.handleRecognizingCallback(result, hypothesis.Duration, this.privRequestSession.sessionId);
}
};
exports.ConversationServiceRecognizer = ConversationServiceRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/RecognizerConfig.js
var require_RecognizerConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/RecognizerConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecognizerConfig = exports.SpeechResultFormat = void 0;
var Exports_js_1 = require_Exports3();
var Exports_js_2 = require_Exports7();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var SpeechResultFormat;
(function(SpeechResultFormat2) {
SpeechResultFormat2[SpeechResultFormat2["Simple"] = 0] = "Simple";
SpeechResultFormat2[SpeechResultFormat2["Detailed"] = 1] = "Detailed";
})(SpeechResultFormat = exports.SpeechResultFormat || (exports.SpeechResultFormat = {}));
var RecognizerConfig = class {
constructor(speechServiceConfig, parameters) {
this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new Exports_js_2.SpeechServiceConfig(new Exports_js_2.Context(null));
this.privParameters = parameters;
this.privMaxRetryCount = parseInt(parameters.getProperty("SPEECH-Error-MaxRetryCount", "4"), 10);
this.privLanguageIdMode = parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_LanguageIdMode, void 0);
this.privEnableSpeakerId = false;
}
get parameters() {
return this.privParameters;
}
get recognitionMode() {
return this.privRecognitionMode;
}
set recognitionMode(value) {
this.privRecognitionMode = value;
this.privRecognitionActivityTimeout = value === PhraseDetectionContext_js_1.RecognitionMode.Interactive ? 8e3 : 25e3;
this.privSpeechServiceConfig.Recognition = PhraseDetectionContext_js_1.RecognitionMode[value];
}
get SpeechServiceConfig() {
return this.privSpeechServiceConfig;
}
get recognitionActivityTimeout() {
return this.privRecognitionActivityTimeout;
}
get isContinuousRecognition() {
return this.privRecognitionMode !== PhraseDetectionContext_js_1.RecognitionMode.Interactive;
}
get languageIdMode() {
return this.privLanguageIdMode;
}
get autoDetectSourceLanguages() {
return this.parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_AutoDetectSourceLanguages, void 0);
}
get recognitionEndpointVersion() {
return this.parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, "2");
}
set recognitionEndpointVersion(version) {
this.parameters.setProperty(Exports_js_1.PropertyId.SpeechServiceConnection_RecognitionEndpointVersion, version);
}
get sourceLanguageModels() {
const models = [];
let modelsExist = false;
if (this.autoDetectSourceLanguages !== void 0) {
for (const language of this.autoDetectSourceLanguages.split(",")) {
const customProperty = language + Exports_js_1.PropertyId.SpeechServiceConnection_EndpointId.toString();
const modelId = this.parameters.getProperty(customProperty, void 0);
if (modelId !== void 0) {
models.push({ language, endpoint: modelId });
modelsExist = true;
} else {
models.push({ language, endpoint: "" });
}
}
}
return modelsExist ? models : void 0;
}
get maxRetryCount() {
return this.privMaxRetryCount;
}
get isSpeakerDiarizationEnabled() {
return this.privEnableSpeakerId;
}
set isSpeakerDiarizationEnabled(value) {
this.privEnableSpeakerId = value;
}
};
exports.RecognizerConfig = RecognizerConfig;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechServiceInterfaces.js
var require_SpeechServiceInterfaces = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechServiceInterfaces.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/WebsocketMessageFormatter.js
var require_WebsocketMessageFormatter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/WebsocketMessageFormatter.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebsocketMessageFormatter = void 0;
var Exports_js_1 = require_Exports();
var CRLF = "\r\n";
var WebsocketMessageFormatter = class {
toConnectionMessage(message) {
const deferral = new Exports_js_1.Deferred();
try {
if (message.messageType === Exports_js_1.MessageType.Text) {
const textMessage = message.textContent;
let headers = {};
let body = null;
if (textMessage) {
const 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_js_1.ConnectionMessage(message.messageType, body, headers, message.id));
} else if (message.messageType === Exports_js_1.MessageType.Binary) {
const binaryMessage = message.binaryContent;
let headers = {};
let body = null;
if (!binaryMessage || binaryMessage.byteLength < 2) {
throw new Error("Invalid binary message format. Header length missing.");
}
const dataView = new DataView(binaryMessage);
const headerLength = dataView.getInt16(0);
if (binaryMessage.byteLength < headerLength + 2) {
throw new Error("Invalid binary message format. Header content missing.");
}
let headersString = "";
for (let 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_js_1.ConnectionMessage(message.messageType, body, headers, message.id));
}
} catch (e) {
deferral.reject(`Error formatting the message. Error: ${e}`);
}
return deferral.promise;
}
fromConnectionMessage(message) {
const deferral = new Exports_js_1.Deferred();
try {
if (message.messageType === Exports_js_1.MessageType.Text) {
const payload = `${this.makeHeaders(message)}${CRLF}${message.textBody ? message.textBody : ""}`;
deferral.resolve(new Exports_js_1.RawWebsocketMessage(Exports_js_1.MessageType.Text, payload, message.id));
} else if (message.messageType === Exports_js_1.MessageType.Binary) {
const headersString = this.makeHeaders(message);
const content = message.binaryBody;
const headerBuffer = this.stringToArrayBuffer(headersString);
const headerInt8Array = new Int8Array(headerBuffer);
const headerLength = headerInt8Array.byteLength;
const payloadInt8Array = new Int8Array(2 + headerLength + (content ? content.byteLength : 0));
payloadInt8Array[0] = headerLength >> 8 & 255;
payloadInt8Array[1] = headerLength & 255;
payloadInt8Array.set(headerInt8Array, 2);
if (content) {
const bodyInt8Array = new Int8Array(content);
payloadInt8Array.set(bodyInt8Array, 2 + headerLength);
}
const payload = payloadInt8Array.buffer;
deferral.resolve(new Exports_js_1.RawWebsocketMessage(Exports_js_1.MessageType.Binary, payload, message.id));
}
} catch (e) {
deferral.reject(`Error formatting the message. ${e}`);
}
return deferral.promise;
}
makeHeaders(message) {
let headersString = "";
if (message.headers) {
for (const header in message.headers) {
if (header) {
headersString += `${header}: ${message.headers[header]}${CRLF}`;
}
}
}
return headersString;
}
parseHeaders(headersString) {
const headers = {};
if (headersString) {
const headerMatches = headersString.match(/[^\r\n]+/g);
if (headers) {
for (const header of headerMatches) {
if (header) {
const separatorIndex = header.indexOf(":");
const headerName = separatorIndex > 0 ? header.substr(0, separatorIndex).trim().toLowerCase() : header;
const headerValue = separatorIndex > 0 && header.length > separatorIndex + 1 ? header.substr(separatorIndex + 1).trim() : "";
headers[headerName] = headerValue;
}
}
}
}
return headers;
}
stringToArrayBuffer(str) {
const buffer = new ArrayBuffer(str.length);
const view = new DataView(buffer);
for (let i = 0; i < str.length; i++) {
view.setUint8(i, str.charCodeAt(i));
}
return buffer;
}
};
exports.WebsocketMessageFormatter = WebsocketMessageFormatter;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechConnectionFactory.js
var require_SpeechConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechConnectionFactory = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports7();
var Exports_js_3 = require_Exports3();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var Exports_js_4 = require_Exports7();
var HeaderNames_js_1 = require_HeaderNames();
var QueryParameterNames_js_1 = require_QueryParameterNames();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var SpeechConnectionFactory = class extends ConnectionFactoryBase_js_1.ConnectionFactoryBase {
constructor() {
super(...arguments);
this.interactiveRelativeUri = "/speech/recognition/interactive/cognitiveservices/v1";
this.conversationRelativeUri = "/speech/recognition/conversation/cognitiveservices/v1";
this.dictationRelativeUri = "/speech/recognition/dictation/cognitiveservices/v1";
this.universalUri = "/stt/speech/universal/v";
}
async create(config, authInfo, connectionId) {
let endpoint = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Endpoint, void 0);
const region = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Region, void 0);
const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region);
const host = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".stt.speech" + hostSuffix);
const queryParams = {};
const endpointId = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_EndpointId, void 0);
const language = config.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage, void 0);
if (endpointId) {
if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId) === -1) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId] = endpointId;
}
} else if (language) {
if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.Language) === -1) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.Language] = language;
}
}
if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.Format) === -1) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.Format] = config.parameters.getProperty(Exports_js_2.OutputFormatPropertyName, Exports_js_3.OutputFormat[Exports_js_3.OutputFormat.Simple]).toLowerCase();
}
if (config.autoDetectSourceLanguages !== void 0) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.EnableLanguageId] = "true";
}
this.setCommonUrlParams(config, queryParams, endpoint);
if (!!endpoint) {
const endpointUrl = new URL(endpoint);
const pathName = endpointUrl.pathname;
if (pathName === "" || pathName === "/") {
endpointUrl.pathname = this.universalUri + config.recognitionEndpointVersion;
endpoint = await ConnectionFactoryBase_js_1.ConnectionFactoryBase.getRedirectUrlFromEndpoint(endpointUrl.toString());
}
}
if (!endpoint) {
switch (config.recognitionMode) {
case PhraseDetectionContext_js_1.RecognitionMode.Conversation:
if (config.parameters.getProperty(Exports_js_2.ForceDictationPropertyName, "false") === "true") {
endpoint = host + this.dictationRelativeUri;
} else {
if (config.recognitionEndpointVersion !== void 0 && parseInt(config.recognitionEndpointVersion, 10) > 1) {
endpoint = `${host}${this.universalUri}${config.recognitionEndpointVersion}`;
} else {
endpoint = host + this.conversationRelativeUri;
}
}
break;
case PhraseDetectionContext_js_1.RecognitionMode.Dictation:
endpoint = host + this.dictationRelativeUri;
break;
default:
if (config.recognitionEndpointVersion !== void 0 && parseInt(config.recognitionEndpointVersion, 10) > 1) {
endpoint = `${host}${this.universalUri}${config.recognitionEndpointVersion}`;
} else {
endpoint = host + this.interactiveRelativeUri;
}
break;
}
}
const headers = {};
if (authInfo.token !== void 0 && authInfo.token !== "") {
headers[authInfo.headerName] = authInfo.token;
}
headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId;
headers.connectionId = connectionId;
const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
const webSocketConnection = new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_4.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);
const uri = webSocketConnection.uri;
config.parameters.setProperty(Exports_js_3.PropertyId.SpeechServiceConnection_Url, uri);
return webSocketConnection;
}
};
exports.SpeechConnectionFactory = SpeechConnectionFactory;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ConversationTranscriberConnectionFactory.js
var require_ConversationTranscriberConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ConversationTranscriberConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranscriberConnectionFactory = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports3();
var Exports_js_3 = require_Exports7();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var Exports_js_4 = require_Exports7();
var HeaderNames_js_1 = require_HeaderNames();
var QueryParameterNames_js_1 = require_QueryParameterNames();
var ConversationTranscriberConnectionFactory = class extends ConnectionFactoryBase_js_1.ConnectionFactoryBase {
constructor() {
super(...arguments);
this.universalUri = "/stt/speech/universal/v2";
}
async create(config, authInfo, connectionId) {
let endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, void 0);
const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, void 0);
const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region);
const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, "wss://" + region + ".stt.speech" + hostSuffix);
const queryParams = {};
const endpointId = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId, void 0);
const language = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, void 0);
if (endpointId) {
if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId) === -1) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId] = endpointId;
}
} else if (language) {
if (!endpoint || endpoint.search(QueryParameterNames_js_1.QueryParameterNames.Language) === -1) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.Language] = language;
}
}
if (config.autoDetectSourceLanguages !== void 0) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.EnableLanguageId] = "true";
}
this.setV2UrlParams(config, queryParams, endpoint);
if (!!endpoint) {
const endpointUrl = new URL(endpoint);
const pathName = endpointUrl.pathname;
if (pathName === "" || pathName === "/") {
endpointUrl.pathname = this.universalUri;
endpoint = await ConnectionFactoryBase_js_1.ConnectionFactoryBase.getRedirectUrlFromEndpoint(endpointUrl.toString());
}
}
if (!endpoint) {
endpoint = `${host}${this.universalUri}`;
}
const headers = {};
if (authInfo.token !== void 0 && authInfo.token !== "") {
headers[authInfo.headerName] = authInfo.token;
}
headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId;
const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
const webSocketConnection = new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_4.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);
const uri = webSocketConnection.uri;
config.parameters.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url, uri);
return webSocketConnection;
}
setV2UrlParams(config, queryParams, endpoint) {
const propertyIdToParameterMap = /* @__PURE__ */ new Map([
[Exports_js_2.PropertyId.Speech_SegmentationSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.SegmentationSilenceTimeoutMs],
[Exports_js_2.PropertyId.SpeechServiceConnection_EnableAudioLogging, QueryParameterNames_js_1.QueryParameterNames.EnableAudioLogging],
[Exports_js_2.PropertyId.SpeechServiceConnection_EndSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.EndSilenceTimeoutMs],
[Exports_js_2.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs, QueryParameterNames_js_1.QueryParameterNames.InitialSilenceTimeoutMs],
[Exports_js_2.PropertyId.SpeechServiceResponse_PostProcessingOption, QueryParameterNames_js_1.QueryParameterNames.Postprocessing],
[Exports_js_2.PropertyId.SpeechServiceResponse_ProfanityOption, QueryParameterNames_js_1.QueryParameterNames.Profanity],
[Exports_js_2.PropertyId.SpeechServiceResponse_StablePartialResultThreshold, QueryParameterNames_js_1.QueryParameterNames.StableIntermediateThreshold]
]);
propertyIdToParameterMap.forEach((parameterName, propertyId) => {
this.setUrlParameter(propertyId, parameterName, config, queryParams, endpoint);
});
const serviceProperties = JSON.parse(config.parameters.getProperty(Exports_js_3.ServicePropertiesPropertyName, "{}"));
Object.keys(serviceProperties).forEach((value) => {
queryParams[value] = serviceProperties[value];
});
}
};
exports.ConversationTranscriberConnectionFactory = ConversationTranscriberConnectionFactory;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/TranscriberConnectionFactory.js
var require_TranscriberConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/TranscriberConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranscriberConnectionFactory = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports3();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var Exports_js_3 = require_Exports7();
var HeaderNames_js_1 = require_HeaderNames();
var QueryParameterNames_js_1 = require_QueryParameterNames();
var TranscriberConnectionFactory = class extends ConnectionFactoryBase_js_1.ConnectionFactoryBase {
constructor() {
super(...arguments);
this.multiaudioRelativeUri = "/speech/recognition/multiaudio";
}
create(config, authInfo, connectionId) {
let endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, void 0);
const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, "centralus");
const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region);
const hostDefault = "wss://transcribe." + region + ".cts.speech" + hostSuffix + this.multiaudioRelativeUri;
const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, hostDefault);
const queryParams = {};
this.setQueryParams(queryParams, config, endpoint);
if (!endpoint) {
endpoint = host;
}
const headers = {};
if (authInfo.token !== void 0 && authInfo.token !== "") {
headers[authInfo.headerName] = authInfo.token;
}
headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId;
config.parameters.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url, endpoint);
const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
return Promise.resolve(new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_3.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId));
}
setQueryParams(queryParams, config, endpointUrl) {
const endpointId = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_EndpointId, void 0);
const language = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, void 0);
if (endpointId && !(QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId in queryParams)) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.CustomSpeechDeploymentId] = endpointId;
}
if (language && !(QueryParameterNames_js_1.QueryParameterNames.Language in queryParams)) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.Language] = language;
}
const wordLevelTimings = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps, "false").toLowerCase() === "true";
const detailed = config.parameters.getProperty(Exports_js_3.OutputFormatPropertyName, Exports_js_2.OutputFormat[Exports_js_2.OutputFormat.Simple]) !== Exports_js_2.OutputFormat[Exports_js_2.OutputFormat.Simple];
if (wordLevelTimings || detailed) {
queryParams[QueryParameterNames_js_1.QueryParameterNames.Format] = Exports_js_2.OutputFormat[Exports_js_2.OutputFormat.Detailed].toLowerCase();
}
this.setCommonUrlParams(config, queryParams, endpointUrl);
}
};
exports.TranscriberConnectionFactory = TranscriberConnectionFactory;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/TranslationConnectionFactory.js
var require_TranslationConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/TranslationConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationConnectionFactory = void 0;
var Exports_js_1 = require_Exports4();
var StringUtils_js_1 = require_StringUtils();
var Exports_js_2 = require_Exports3();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var Exports_js_3 = require_Exports7();
var HeaderNames_js_1 = require_HeaderNames();
var QueryParameterNames_js_1 = require_QueryParameterNames();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var TranslationConnectionFactory = class extends ConnectionFactoryBase_js_1.ConnectionFactoryBase {
constructor() {
super(...arguments);
this.universalUri = "/stt/speech/universal/v2";
this.translationV1Uri = "/speech/translation/cognitiveservices/v1";
}
async create(config, authInfo, connectionId) {
let endpoint = this.getEndpointUrl(config);
const queryParams = {};
this.setQueryParams(queryParams, config, endpoint);
if (!!endpoint) {
const endpointUrl = new URL(endpoint);
const pathName = endpointUrl.pathname;
if (pathName === "" || pathName === "/") {
endpointUrl.pathname = this.universalUri;
endpoint = await ConnectionFactoryBase_js_1.ConnectionFactoryBase.getRedirectUrlFromEndpoint(endpointUrl.toString());
}
}
const headers = {};
if (authInfo.token !== void 0 && authInfo.token !== "") {
headers[authInfo.headerName] = authInfo.token;
}
headers[HeaderNames_js_1.HeaderNames.ConnectionId] = connectionId;
config.parameters.setProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url, endpoint);
const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
const webSocketConnection = new Exports_js_1.WebsocketConnection(endpoint, queryParams, headers, new Exports_js_3.WebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId);
return webSocketConnection;
}
getEndpointUrl(config, returnRegionPlaceholder) {
const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region);
const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region);
let endpointUrl = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, void 0);
if (endpointUrl) {
if (returnRegionPlaceholder === true) {
return endpointUrl;
}
return StringUtils_js_1.StringUtils.formatString(endpointUrl, { region });
}
const forceV1Endpoint = config.parameters.getProperty("SPEECH-ForceV1Endpoint", "false") === "true";
if (forceV1Endpoint) {
const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, "wss://{region}.s2s.speech" + hostSuffix);
endpointUrl = host + this.translationV1Uri;
} else {
const host = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, "wss://{region}.stt.speech" + hostSuffix);
endpointUrl = host + this.universalUri;
}
if (returnRegionPlaceholder === true) {
return endpointUrl;
}
return StringUtils_js_1.StringUtils.formatString(endpointUrl, { region });
}
setQueryParams(queryParams, config, endpointUrl) {
queryParams.from = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage);
queryParams.to = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationToLanguages);
queryParams.scenario = config.recognitionMode === PhraseDetectionContext_js_1.RecognitionMode.Interactive ? "interactive" : config.recognitionMode === PhraseDetectionContext_js_1.RecognitionMode.Conversation ? "conversation" : "";
this.setCommonUrlParams(config, queryParams, endpointUrl);
this.setUrlParameter(Exports_js_2.PropertyId.SpeechServiceResponse_TranslationRequestStablePartialResult, QueryParameterNames_js_1.QueryParameterNames.StableTranslation, config, queryParams, endpointUrl);
const translationVoice = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_TranslationVoice, void 0);
if (translationVoice !== void 0) {
queryParams.voice = translationVoice;
queryParams.features = "requireVoice";
}
}
};
exports.TranslationConnectionFactory = TranslationConnectionFactory;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/EnumTranslation.js
var require_EnumTranslation = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/EnumTranslation.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnumTranslation = void 0;
var Exports_js_1 = require_Exports3();
var Exports_js_2 = require_Exports7();
var EnumTranslation = class {
static implTranslateRecognitionResult(recognitionStatus, expectEndOfDictation = false) {
let reason = Exports_js_1.ResultReason.Canceled;
switch (recognitionStatus) {
case Exports_js_2.RecognitionStatus.Success:
reason = Exports_js_1.ResultReason.RecognizedSpeech;
break;
case Exports_js_2.RecognitionStatus.EndOfDictation:
reason = expectEndOfDictation ? Exports_js_1.ResultReason.RecognizedSpeech : Exports_js_1.ResultReason.NoMatch;
break;
case Exports_js_2.RecognitionStatus.NoMatch:
case Exports_js_2.RecognitionStatus.InitialSilenceTimeout:
case Exports_js_2.RecognitionStatus.BabbleTimeout:
reason = Exports_js_1.ResultReason.NoMatch;
break;
case Exports_js_2.RecognitionStatus.Error:
case Exports_js_2.RecognitionStatus.BadRequest:
case Exports_js_2.RecognitionStatus.Forbidden:
default:
reason = Exports_js_1.ResultReason.Canceled;
break;
}
return reason;
}
static implTranslateCancelResult(recognitionStatus) {
let reason = Exports_js_1.CancellationReason.EndOfStream;
switch (recognitionStatus) {
case Exports_js_2.RecognitionStatus.Success:
case Exports_js_2.RecognitionStatus.EndOfDictation:
case Exports_js_2.RecognitionStatus.NoMatch:
reason = Exports_js_1.CancellationReason.EndOfStream;
break;
case Exports_js_2.RecognitionStatus.InitialSilenceTimeout:
case Exports_js_2.RecognitionStatus.BabbleTimeout:
case Exports_js_2.RecognitionStatus.Error:
case Exports_js_2.RecognitionStatus.BadRequest:
case Exports_js_2.RecognitionStatus.Forbidden:
default:
reason = Exports_js_1.CancellationReason.Error;
break;
}
return reason;
}
static implTranslateCancelErrorCode(recognitionStatus) {
let reason = Exports_js_1.CancellationErrorCode.NoError;
switch (recognitionStatus) {
case Exports_js_2.RecognitionStatus.Error:
reason = Exports_js_1.CancellationErrorCode.ServiceError;
break;
case Exports_js_2.RecognitionStatus.TooManyRequests:
reason = Exports_js_1.CancellationErrorCode.TooManyRequests;
break;
case Exports_js_2.RecognitionStatus.BadRequest:
reason = Exports_js_1.CancellationErrorCode.BadRequestParameters;
break;
case Exports_js_2.RecognitionStatus.Forbidden:
reason = Exports_js_1.CancellationErrorCode.Forbidden;
break;
default:
reason = Exports_js_1.CancellationErrorCode.NoError;
break;
}
return reason;
}
static implTranslateErrorDetails(cancellationErrorCode) {
let errorDetails = "The speech service encountered an internal error and could not continue.";
switch (cancellationErrorCode) {
case Exports_js_1.CancellationErrorCode.Forbidden:
errorDetails = "The recognizer is using a free subscription that ran out of quota.";
break;
case Exports_js_1.CancellationErrorCode.BadRequestParameters:
errorDetails = "Invalid parameter or unsupported audio format in the request.";
break;
case Exports_js_1.CancellationErrorCode.TooManyRequests:
errorDetails = "The number of parallel requests exceeded the number of allowed concurrent transcriptions.";
break;
default:
break;
}
return errorDetails;
}
};
exports.EnumTranslation = EnumTranslation;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/Enums.js
var require_Enums = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/Enums.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecognitionStatus = exports.SynthesisStatus = void 0;
var SynthesisStatus;
(function(SynthesisStatus2) {
SynthesisStatus2[SynthesisStatus2["Success"] = 0] = "Success";
SynthesisStatus2[SynthesisStatus2["SynthesisEnd"] = 1] = "SynthesisEnd";
SynthesisStatus2[SynthesisStatus2["Error"] = 2] = "Error";
})(SynthesisStatus = exports.SynthesisStatus || (exports.SynthesisStatus = {}));
var RecognitionStatus;
(function(RecognitionStatus2) {
RecognitionStatus2[RecognitionStatus2["Success"] = 0] = "Success";
RecognitionStatus2[RecognitionStatus2["NoMatch"] = 1] = "NoMatch";
RecognitionStatus2[RecognitionStatus2["InitialSilenceTimeout"] = 2] = "InitialSilenceTimeout";
RecognitionStatus2[RecognitionStatus2["BabbleTimeout"] = 3] = "BabbleTimeout";
RecognitionStatus2[RecognitionStatus2["Error"] = 4] = "Error";
RecognitionStatus2[RecognitionStatus2["EndOfDictation"] = 5] = "EndOfDictation";
RecognitionStatus2[RecognitionStatus2["TooManyRequests"] = 6] = "TooManyRequests";
RecognitionStatus2[RecognitionStatus2["BadRequest"] = 7] = "BadRequest";
RecognitionStatus2[RecognitionStatus2["Forbidden"] = 8] = "Forbidden";
})(RecognitionStatus = exports.RecognitionStatus || (exports.RecognitionStatus = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/TranslationSynthesisEnd.js
var require_TranslationSynthesisEnd = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/TranslationSynthesisEnd.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationSynthesisEnd = void 0;
var Exports_js_1 = require_Exports7();
var TranslationSynthesisEnd = class _TranslationSynthesisEnd {
constructor(json) {
this.privSynthesisEnd = JSON.parse(json);
if (!!this.privSynthesisEnd.SynthesisStatus) {
this.privSynthesisEnd.SynthesisStatus = Exports_js_1.SynthesisStatus[this.privSynthesisEnd.SynthesisStatus];
}
if (!!this.privSynthesisEnd.Status) {
this.privSynthesisEnd.SynthesisStatus = Exports_js_1.SynthesisStatus[this.privSynthesisEnd.Status];
}
}
static fromJSON(json) {
return new _TranslationSynthesisEnd(json);
}
get SynthesisStatus() {
return this.privSynthesisEnd.SynthesisStatus;
}
get FailureReason() {
return this.privSynthesisEnd.FailureReason;
}
};
exports.TranslationSynthesisEnd = TranslationSynthesisEnd;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/TranslationHypothesis.js
var require_TranslationHypothesis = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/TranslationHypothesis.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationHypothesis = void 0;
var Contracts_js_1 = require_Contracts();
var TranslationStatus_js_1 = require_TranslationStatus();
var TranslationHypothesis = class _TranslationHypothesis {
constructor(hypothesis, baseOffset) {
this.privTranslationHypothesis = hypothesis;
this.privTranslationHypothesis.Offset += baseOffset;
this.privTranslationHypothesis.Translation.TranslationStatus = this.mapTranslationStatus(this.privTranslationHypothesis.Translation.TranslationStatus);
}
static fromJSON(json, baseOffset) {
return new _TranslationHypothesis(JSON.parse(json), baseOffset);
}
static fromTranslationResponse(translationHypothesis, baseOffset) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(translationHypothesis, "translationHypothesis");
const hypothesis = translationHypothesis.SpeechHypothesis;
translationHypothesis.SpeechHypothesis = void 0;
hypothesis.Translation = translationHypothesis;
return new _TranslationHypothesis(hypothesis, baseOffset);
}
get Duration() {
return this.privTranslationHypothesis.Duration;
}
get Offset() {
return this.privTranslationHypothesis.Offset;
}
get Text() {
return this.privTranslationHypothesis.Text;
}
get Translation() {
return this.privTranslationHypothesis.Translation;
}
get Language() {
return this.privTranslationHypothesis.PrimaryLanguage?.Language;
}
asJson() {
const jsonObj = { ...this.privTranslationHypothesis };
return jsonObj.Translation !== void 0 ? JSON.stringify({
...jsonObj,
TranslationStatus: TranslationStatus_js_1.TranslationStatus[jsonObj.Translation.TranslationStatus]
}) : JSON.stringify(jsonObj);
}
mapTranslationStatus(status) {
if (typeof status === "string") {
return TranslationStatus_js_1.TranslationStatus[status];
} else if (typeof status === "number") {
return status;
}
}
};
exports.TranslationHypothesis = TranslationHypothesis;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/TranslationPhrase.js
var require_TranslationPhrase = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/TranslationPhrase.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationPhrase = void 0;
var Contracts_js_1 = require_Contracts();
var Exports_js_1 = require_Exports7();
var TranslationStatus_js_1 = require_TranslationStatus();
var TranslationPhrase = class _TranslationPhrase {
constructor(phrase, baseOffset) {
this.privTranslationPhrase = phrase;
this.privTranslationPhrase.Offset += baseOffset;
this.privTranslationPhrase.RecognitionStatus = this.mapRecognitionStatus(this.privTranslationPhrase.RecognitionStatus);
if (this.privTranslationPhrase.Translation !== void 0) {
this.privTranslationPhrase.Translation.TranslationStatus = this.mapTranslationStatus(this.privTranslationPhrase.Translation.TranslationStatus);
}
}
static fromJSON(json, baseOffset) {
return new _TranslationPhrase(JSON.parse(json), baseOffset);
}
static fromTranslationResponse(translationResponse, baseOffset) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(translationResponse, "translationResponse");
const phrase = translationResponse.SpeechPhrase;
translationResponse.SpeechPhrase = void 0;
phrase.Translation = translationResponse;
phrase.Text = phrase.DisplayText;
return new _TranslationPhrase(phrase, baseOffset);
}
get RecognitionStatus() {
return this.privTranslationPhrase.RecognitionStatus;
}
get Offset() {
return this.privTranslationPhrase.Offset;
}
get Duration() {
return this.privTranslationPhrase.Duration;
}
get Text() {
return this.privTranslationPhrase.Text;
}
get Language() {
return this.privTranslationPhrase.PrimaryLanguage?.Language;
}
get Confidence() {
return this.privTranslationPhrase.PrimaryLanguage?.Confidence;
}
get Translation() {
return this.privTranslationPhrase.Translation;
}
asJson() {
const jsonObj = { ...this.privTranslationPhrase };
const serializedObj = {
...jsonObj,
RecognitionStatus: Exports_js_1.RecognitionStatus[jsonObj.RecognitionStatus]
};
if (jsonObj.Translation) {
serializedObj.Translation = {
...jsonObj.Translation,
TranslationStatus: TranslationStatus_js_1.TranslationStatus[jsonObj.Translation.TranslationStatus]
};
}
return JSON.stringify(serializedObj);
}
mapRecognitionStatus(status) {
if (typeof status === "string") {
return Exports_js_1.RecognitionStatus[status];
} else if (typeof status === "number") {
return status;
}
}
mapTranslationStatus(status) {
if (typeof status === "string") {
return TranslationStatus_js_1.TranslationStatus[status];
} else if (typeof status === "number") {
return status;
}
}
};
exports.TranslationPhrase = TranslationPhrase;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/TranslationServiceRecognizer.js
var require_TranslationServiceRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/TranslationServiceRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranslationServiceRecognizer = void 0;
var Exports_js_1 = require_Exports();
var Exports_js_2 = require_Exports3();
var Exports_js_3 = require_Exports7();
var TranslationServiceRecognizer = class extends Exports_js_3.ConversationServiceRecognizer {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, translationRecognizer) {
super(authentication, connectionFactory, audioSource, recognizerConfig, translationRecognizer);
this.privTranslationRecognizer = translationRecognizer;
this.connectionEvents.attach((connectionEvent) => {
if (connectionEvent.name === "ConnectionEstablishedEvent") {
this.privTranslationRecognizer.onConnection();
}
});
}
async processTypeSpecificMessages(connectionMessage) {
const resultProps = new Exports_js_2.PropertyCollection();
let processed = await this.processSpeechMessages(connectionMessage);
if (processed) {
return true;
}
const handleTranslationPhrase = async (translatedPhrase) => {
resultProps.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_JsonResult, translatedPhrase.asJson());
this.privRequestSession.onPhraseRecognized(translatedPhrase.Offset + translatedPhrase.Duration);
if (translatedPhrase.RecognitionStatus === Exports_js_3.RecognitionStatus.Success) {
const result = this.fireEventForResult(translatedPhrase, resultProps);
if (!!this.privTranslationRecognizer.recognized) {
try {
this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, result);
} catch (error) {
}
}
if (!!this.privSuccessCallback) {
try {
this.privSuccessCallback(result.result);
} catch (e) {
if (!!this.privErrorCallback) {
this.privErrorCallback(e);
}
}
this.privSuccessCallback = void 0;
this.privErrorCallback = void 0;
}
} else {
const reason = Exports_js_3.EnumTranslation.implTranslateRecognitionResult(translatedPhrase.RecognitionStatus);
const result = new Exports_js_2.TranslationRecognitionResult(void 0, this.privRequestSession.requestId, reason, translatedPhrase.Text, translatedPhrase.Duration, translatedPhrase.Offset, translatedPhrase.Language, translatedPhrase.Confidence, void 0, translatedPhrase.asJson(), resultProps);
if (reason === Exports_js_2.ResultReason.Canceled) {
const cancelReason = Exports_js_3.EnumTranslation.implTranslateCancelResult(translatedPhrase.RecognitionStatus);
const cancellationErrorCode = Exports_js_3.EnumTranslation.implTranslateCancelErrorCode(translatedPhrase.RecognitionStatus);
await this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_js_3.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode));
} else {
if (translatedPhrase.RecognitionStatus !== Exports_js_3.RecognitionStatus.EndOfDictation) {
const ev = new Exports_js_2.TranslationRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);
if (!!this.privTranslationRecognizer.recognized) {
try {
this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, ev);
} catch (error) {
}
}
if (!!this.privSuccessCallback) {
try {
this.privSuccessCallback(result);
} catch (e) {
if (!!this.privErrorCallback) {
this.privErrorCallback(e);
}
}
this.privSuccessCallback = void 0;
this.privErrorCallback = void 0;
}
}
}
processed = true;
}
};
const handleTranslationHypothesis = (hypothesis) => {
resultProps.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_JsonResult, hypothesis.asJson());
const result = this.fireEventForResult(hypothesis, resultProps);
this.privRequestSession.onHypothesis(result.offset);
if (!!this.privTranslationRecognizer.recognizing) {
try {
this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer, result);
} catch (error) {
}
}
processed = true;
};
if (connectionMessage.messageType === Exports_js_1.MessageType.Text) {
resultProps.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
}
switch (connectionMessage.path.toLowerCase()) {
case "translation.hypothesis":
handleTranslationHypothesis(Exports_js_3.TranslationHypothesis.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset));
break;
case "translation.response":
const phrase = JSON.parse(connectionMessage.textBody);
if (!!phrase.SpeechPhrase) {
await handleTranslationPhrase(Exports_js_3.TranslationPhrase.fromTranslationResponse(phrase, this.privRequestSession.currentTurnAudioOffset));
} else {
const hypothesis = JSON.parse(connectionMessage.textBody);
if (!!hypothesis.SpeechHypothesis) {
handleTranslationHypothesis(Exports_js_3.TranslationHypothesis.fromTranslationResponse(hypothesis, this.privRequestSession.currentTurnAudioOffset));
}
}
break;
case "translation.phrase":
await handleTranslationPhrase(Exports_js_3.TranslationPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset));
break;
case "translation.synthesis":
case "audio":
this.sendSynthesisAudio(connectionMessage.binaryBody, this.privRequestSession.sessionId);
processed = true;
break;
case "audio.end":
case "translation.synthesis.end":
const synthEnd = Exports_js_3.TranslationSynthesisEnd.fromJSON(connectionMessage.textBody);
switch (synthEnd.SynthesisStatus) {
case Exports_js_3.SynthesisStatus.Error:
if (!!this.privTranslationRecognizer.synthesizing) {
const result = new Exports_js_2.TranslationSynthesisResult(Exports_js_2.ResultReason.Canceled, void 0);
const retEvent = new Exports_js_2.TranslationSynthesisEventArgs(result, this.privRequestSession.sessionId);
try {
this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent);
} catch (error) {
}
}
if (!!this.privTranslationRecognizer.canceled) {
const canceledResult = new Exports_js_2.TranslationRecognitionCanceledEventArgs(this.privRequestSession.sessionId, Exports_js_2.CancellationReason.Error, synthEnd.FailureReason, Exports_js_2.CancellationErrorCode.ServiceError, null);
try {
this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, canceledResult);
} catch (error) {
}
}
break;
case Exports_js_3.SynthesisStatus.Success:
this.sendSynthesisAudio(void 0, this.privRequestSession.sessionId);
break;
default:
break;
}
processed = true;
break;
default:
break;
}
return processed;
}
// Cancels recognition.
cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
const properties = new Exports_js_2.PropertyCollection();
properties.setProperty(Exports_js_3.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[errorCode]);
if (!!this.privTranslationRecognizer.canceled) {
const cancelEvent = new Exports_js_2.TranslationRecognitionCanceledEventArgs(sessionId, cancellationReason, error, errorCode, void 0);
try {
this.privTranslationRecognizer.canceled(this.privTranslationRecognizer, cancelEvent);
} catch {
}
}
if (!!this.privSuccessCallback) {
const result = new Exports_js_2.TranslationRecognitionResult(
void 0,
// Translations
requestId,
Exports_js_2.ResultReason.Canceled,
void 0,
// Text
void 0,
// Druation
void 0,
// Offset
void 0,
// Language
void 0,
// LanguageDetectionConfidence
error,
void 0,
// Json
properties
);
try {
this.privSuccessCallback(result);
this.privSuccessCallback = void 0;
} catch {
}
}
}
handleRecognizingCallback(result, offset, sessionId) {
try {
const ev = new Exports_js_2.TranslationRecognitionEventArgs(Exports_js_2.TranslationRecognitionResult.fromSpeechRecognitionResult(result), offset, sessionId);
this.privTranslationRecognizer.recognizing(this.privTranslationRecognizer, ev);
} catch (error) {
}
}
handleRecognizedCallback(result, offset, sessionId) {
try {
const ev = new Exports_js_2.TranslationRecognitionEventArgs(Exports_js_2.TranslationRecognitionResult.fromSpeechRecognitionResult(result), offset, sessionId);
this.privTranslationRecognizer.recognized(this.privTranslationRecognizer, ev);
} catch (error) {
}
}
fireEventForResult(serviceResult, properties) {
let translations;
if (void 0 !== serviceResult.Translation.Translations) {
translations = new Exports_js_2.Translations();
for (const translation of serviceResult.Translation.Translations) {
translations.set(translation.Language, translation.Text || translation.DisplayText);
}
}
let resultReason;
let confidence;
if (serviceResult instanceof Exports_js_3.TranslationPhrase) {
if (!!serviceResult.Translation && serviceResult.Translation.TranslationStatus === Exports_js_1.TranslationStatus.Success) {
resultReason = Exports_js_2.ResultReason.TranslatedSpeech;
} else {
resultReason = Exports_js_2.ResultReason.RecognizedSpeech;
}
confidence = serviceResult.Confidence;
} else {
resultReason = Exports_js_2.ResultReason.TranslatingSpeech;
}
const language = serviceResult.Language;
const result = new Exports_js_2.TranslationRecognitionResult(translations, this.privRequestSession.requestId, resultReason, serviceResult.Text, serviceResult.Duration, serviceResult.Offset, language, confidence, serviceResult.Translation.FailureReason, serviceResult.asJson(), properties);
const ev = new Exports_js_2.TranslationRecognitionEventArgs(result, serviceResult.Offset, this.privRequestSession.sessionId);
return ev;
}
sendSynthesisAudio(audio, sessionId) {
const reason = void 0 === audio ? Exports_js_2.ResultReason.SynthesizingAudioCompleted : Exports_js_2.ResultReason.SynthesizingAudio;
const result = new Exports_js_2.TranslationSynthesisResult(reason, audio);
const retEvent = new Exports_js_2.TranslationSynthesisEventArgs(result, sessionId);
if (!!this.privTranslationRecognizer.synthesizing) {
try {
this.privTranslationRecognizer.synthesizing(this.privTranslationRecognizer, retEvent);
} catch (error) {
}
}
}
};
exports.TranslationServiceRecognizer = TranslationServiceRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SpeechDetected.js
var require_SpeechDetected = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SpeechDetected.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechDetected = void 0;
var SpeechDetected = class _SpeechDetected {
constructor(json, baseOffset) {
this.privSpeechStartDetected = JSON.parse(json);
this.privSpeechStartDetected.Offset += baseOffset;
}
static fromJSON(json, baseOffset) {
return new _SpeechDetected(json, baseOffset);
}
get Offset() {
return this.privSpeechStartDetected.Offset;
}
};
exports.SpeechDetected = SpeechDetected;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SpeechHypothesis.js
var require_SpeechHypothesis = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SpeechHypothesis.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechHypothesis = void 0;
var SpeechHypothesis = class _SpeechHypothesis {
constructor(json, baseOffset) {
this.privSpeechHypothesis = JSON.parse(json);
this.updateOffset(baseOffset);
}
static fromJSON(json, baseOffset) {
return new _SpeechHypothesis(json, baseOffset);
}
updateOffset(baseOffset) {
this.privSpeechHypothesis.Offset += baseOffset;
}
asJson() {
return JSON.stringify(this.privSpeechHypothesis);
}
get Text() {
return this.privSpeechHypothesis.Text;
}
get Offset() {
return this.privSpeechHypothesis.Offset;
}
get Duration() {
return this.privSpeechHypothesis.Duration;
}
get Language() {
return this.privSpeechHypothesis.PrimaryLanguage === void 0 ? void 0 : this.privSpeechHypothesis.PrimaryLanguage.Language;
}
get LanguageDetectionConfidence() {
return this.privSpeechHypothesis.PrimaryLanguage === void 0 ? void 0 : this.privSpeechHypothesis.PrimaryLanguage.Confidence;
}
get SpeakerId() {
return this.privSpeechHypothesis.SpeakerId;
}
};
exports.SpeechHypothesis = SpeechHypothesis;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SpeechKeyword.js
var require_SpeechKeyword = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SpeechKeyword.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechKeyword = void 0;
var SpeechKeyword = class _SpeechKeyword {
constructor(json, baseOffset) {
this.privSpeechKeyword = JSON.parse(json);
this.privSpeechKeyword.Offset += baseOffset;
}
static fromJSON(json, baseOffset) {
return new _SpeechKeyword(json, baseOffset);
}
get Status() {
return this.privSpeechKeyword.Status;
}
get Text() {
return this.privSpeechKeyword.Text;
}
get Offset() {
return this.privSpeechKeyword.Offset;
}
get Duration() {
return this.privSpeechKeyword.Duration;
}
asJson() {
return JSON.stringify(this.privSpeechKeyword);
}
};
exports.SpeechKeyword = SpeechKeyword;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechServiceRecognizer.js
var require_SpeechServiceRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechServiceRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechServiceRecognizer = void 0;
var Exports_js_1 = require_Exports3();
var Exports_js_2 = require_Exports7();
var SpeechServiceRecognizer = class extends Exports_js_2.ServiceRecognizerBase {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, speechRecognizer) {
super(authentication, connectionFactory, audioSource, recognizerConfig, speechRecognizer);
this.privSpeechRecognizer = speechRecognizer;
}
async processTypeSpecificMessages(connectionMessage) {
let result;
const resultProps = new Exports_js_1.PropertyCollection();
let processed = false;
switch (connectionMessage.path.toLowerCase()) {
case "speech.hypothesis":
case "speech.fragment":
const hypothesis = Exports_js_2.SpeechHypothesis.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, hypothesis.asJson());
result = new Exports_js_1.SpeechRecognitionResult(
this.privRequestSession.requestId,
Exports_js_1.ResultReason.RecognizingSpeech,
hypothesis.Text,
hypothesis.Duration,
hypothesis.Offset,
hypothesis.Language,
hypothesis.LanguageDetectionConfidence,
void 0,
// Speaker Id
void 0,
hypothesis.asJson(),
resultProps
);
this.privRequestSession.onHypothesis(hypothesis.Offset);
const ev = new Exports_js_1.SpeechRecognitionEventArgs(result, hypothesis.Offset, this.privRequestSession.sessionId);
if (!!this.privSpeechRecognizer.recognizing) {
try {
this.privSpeechRecognizer.recognizing(this.privSpeechRecognizer, ev);
} catch (error) {
}
}
processed = true;
break;
case "speech.phrase":
const simple = Exports_js_2.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, simple.asJson());
const resultReason = Exports_js_2.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus, this.privExpectContentAssessmentResponse);
this.privRequestSession.onPhraseRecognized(simple.Offset + simple.Duration);
if (Exports_js_1.ResultReason.Canceled === resultReason) {
const cancelReason = Exports_js_2.EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus);
const cancellationErrorCode = Exports_js_2.EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus);
await this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_js_2.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode));
} else {
if (simple.RecognitionStatus === Exports_js_2.RecognitionStatus.EndOfDictation) {
break;
}
if (this.privRecognizerConfig.parameters.getProperty(Exports_js_2.OutputFormatPropertyName) === Exports_js_1.OutputFormat[Exports_js_1.OutputFormat.Simple]) {
result = new Exports_js_1.SpeechRecognitionResult(
this.privRequestSession.requestId,
resultReason,
simple.DisplayText,
simple.Duration,
simple.Offset,
simple.Language,
simple.LanguageDetectionConfidence,
void 0,
// Speaker Id
void 0,
simple.asJson(),
resultProps
);
} else {
const detailed = Exports_js_2.DetailedSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, detailed.asJson());
result = new Exports_js_1.SpeechRecognitionResult(
this.privRequestSession.requestId,
resultReason,
detailed.RecognitionStatus === Exports_js_2.RecognitionStatus.Success ? detailed.NBest[0].Display : "",
detailed.Duration,
detailed.Offset,
detailed.Language,
detailed.LanguageDetectionConfidence,
void 0,
// Speaker Id
void 0,
detailed.asJson(),
resultProps
);
}
const event = new Exports_js_1.SpeechRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);
if (!!this.privSpeechRecognizer.recognized) {
try {
this.privSpeechRecognizer.recognized(this.privSpeechRecognizer, event);
} catch (error) {
}
}
if (!!this.privSuccessCallback) {
try {
this.privSuccessCallback(result);
} catch (e) {
if (!!this.privErrorCallback) {
this.privErrorCallback(e);
}
}
this.privSuccessCallback = void 0;
this.privErrorCallback = void 0;
}
}
processed = true;
break;
default:
break;
}
return processed;
}
// Cancels recognition.
cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
const properties = new Exports_js_1.PropertyCollection();
properties.setProperty(Exports_js_2.CancellationErrorCodePropertyName, Exports_js_1.CancellationErrorCode[errorCode]);
if (!!this.privSpeechRecognizer.canceled) {
const cancelEvent = new Exports_js_1.SpeechRecognitionCanceledEventArgs(cancellationReason, error, errorCode, void 0, sessionId);
try {
this.privSpeechRecognizer.canceled(this.privSpeechRecognizer, cancelEvent);
} catch {
}
}
if (!!this.privSuccessCallback) {
const result = new Exports_js_1.SpeechRecognitionResult(
requestId,
Exports_js_1.ResultReason.Canceled,
void 0,
// Text
void 0,
// Duration
void 0,
// Offset
void 0,
// Language
void 0,
// Language Detection Confidence
void 0,
// Speaker Id
error,
void 0,
// Json
properties
);
try {
this.privSuccessCallback(result);
this.privSuccessCallback = void 0;
} catch {
}
}
}
};
exports.SpeechServiceRecognizer = SpeechServiceRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseDetection/SpeakerDiarization.js
var require_SpeakerDiarization = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseDetection/SpeakerDiarization.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IdentityProvider = exports.SpeakerDiarizationMode = void 0;
var SpeakerDiarizationMode;
(function(SpeakerDiarizationMode2) {
SpeakerDiarizationMode2["None"] = "None";
SpeakerDiarizationMode2["Identity"] = "Identity";
SpeakerDiarizationMode2["Anonymous"] = "Anonymous";
})(SpeakerDiarizationMode = exports.SpeakerDiarizationMode || (exports.SpeakerDiarizationMode = {}));
var IdentityProvider;
(function(IdentityProvider2) {
IdentityProvider2["CallCenter"] = "CallCenter";
})(IdentityProvider = exports.IdentityProvider || (exports.IdentityProvider = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ConversationTranscriptionServiceRecognizer.js
var require_ConversationTranscriptionServiceRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ConversationTranscriptionServiceRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranscriptionServiceRecognizer = void 0;
var Exports_js_1 = require_Exports3();
var Exports_js_2 = require_Exports7();
var SpeakerDiarization_js_1 = require_SpeakerDiarization();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var ConversationTranscriptionServiceRecognizer = class extends Exports_js_2.ServiceRecognizerBase {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, conversationTranscriber) {
super(authentication, connectionFactory, audioSource, recognizerConfig, conversationTranscriber);
this.privConversationTranscriber = conversationTranscriber;
this.setSpeakerDiarizationJson();
}
setSpeakerDiarizationJson() {
if (this.privEnableSpeakerId) {
const phraseDetection = this.privSpeechContext.getContext().phraseDetection || {};
phraseDetection.mode = PhraseDetectionContext_js_1.RecognitionMode.Conversation;
const speakerDiarization = {};
speakerDiarization.mode = SpeakerDiarization_js_1.SpeakerDiarizationMode.Anonymous;
speakerDiarization.audioSessionId = this.privDiarizationSessionId;
speakerDiarization.audioOffsetMs = 0;
speakerDiarization.diarizeIntermediates = this.privRecognizerConfig.parameters.getProperty(Exports_js_1.PropertyId.SpeechServiceResponse_DiarizeIntermediateResults, "false") === "true";
phraseDetection.speakerDiarization = speakerDiarization;
this.privSpeechContext.getContext().phraseDetection = phraseDetection;
}
}
async processTypeSpecificMessages(connectionMessage) {
let result;
const resultProps = new Exports_js_1.PropertyCollection();
resultProps.setProperty(Exports_js_1.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
let processed = false;
switch (connectionMessage.path.toLowerCase()) {
case "speech.hypothesis":
case "speech.fragment":
const hypothesis = Exports_js_2.SpeechHypothesis.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
result = new Exports_js_1.ConversationTranscriptionResult(this.privRequestSession.requestId, Exports_js_1.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, hypothesis.Offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, hypothesis.SpeakerId, void 0, hypothesis.asJson(), resultProps);
this.privRequestSession.onHypothesis(hypothesis.Offset);
const ev = new Exports_js_1.ConversationTranscriptionEventArgs(result, hypothesis.Duration, this.privRequestSession.sessionId);
if (!!this.privConversationTranscriber.transcribing) {
try {
this.privConversationTranscriber.transcribing(this.privConversationTranscriber, ev);
} catch (error) {
}
}
processed = true;
break;
case "speech.phrase":
const simple = Exports_js_2.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
const resultReason = Exports_js_2.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus);
this.privRequestSession.onPhraseRecognized(simple.Offset + simple.Duration);
if (Exports_js_1.ResultReason.Canceled === resultReason) {
const cancelReason = Exports_js_2.EnumTranslation.implTranslateCancelResult(simple.RecognitionStatus);
const cancellationErrorCode = Exports_js_2.EnumTranslation.implTranslateCancelErrorCode(simple.RecognitionStatus);
await this.cancelRecognitionLocal(cancelReason, cancellationErrorCode, Exports_js_2.EnumTranslation.implTranslateErrorDetails(cancellationErrorCode));
} else {
if (!(this.privRequestSession.isSpeechEnded && resultReason === Exports_js_1.ResultReason.NoMatch && simple.RecognitionStatus !== Exports_js_2.RecognitionStatus.InitialSilenceTimeout)) {
if (this.privRecognizerConfig.parameters.getProperty(Exports_js_2.OutputFormatPropertyName) === Exports_js_1.OutputFormat[Exports_js_1.OutputFormat.Simple]) {
result = new Exports_js_1.ConversationTranscriptionResult(this.privRequestSession.requestId, resultReason, simple.DisplayText, simple.Duration, simple.Offset, simple.Language, simple.LanguageDetectionConfidence, simple.SpeakerId, void 0, simple.asJson(), resultProps);
} else {
const detailed = Exports_js_2.DetailedSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
result = new Exports_js_1.ConversationTranscriptionResult(this.privRequestSession.requestId, resultReason, detailed.RecognitionStatus === Exports_js_2.RecognitionStatus.Success ? detailed.NBest[0].Display : void 0, detailed.Duration, detailed.Offset, detailed.Language, detailed.LanguageDetectionConfidence, simple.SpeakerId, void 0, detailed.asJson(), resultProps);
}
const event = new Exports_js_1.ConversationTranscriptionEventArgs(result, result.offset, this.privRequestSession.sessionId);
if (!!this.privConversationTranscriber.transcribed) {
try {
this.privConversationTranscriber.transcribed(this.privConversationTranscriber, event);
} catch (error) {
}
}
}
}
processed = true;
break;
default:
break;
}
return processed;
}
// Cancels recognition.
cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
const properties = new Exports_js_1.PropertyCollection();
properties.setProperty(Exports_js_2.CancellationErrorCodePropertyName, Exports_js_1.CancellationErrorCode[errorCode]);
if (!!this.privConversationTranscriber.canceled) {
const cancelEvent = new Exports_js_1.ConversationTranscriptionCanceledEventArgs(cancellationReason, error, errorCode, void 0, sessionId);
try {
this.privConversationTranscriber.canceled(this.privConversationTranscriber, cancelEvent);
} catch {
}
}
}
};
exports.ConversationTranscriptionServiceRecognizer = ConversationTranscriptionServiceRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/TranscriptionServiceRecognizer.js
var require_TranscriptionServiceRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/TranscriptionServiceRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranscriptionServiceRecognizer = void 0;
var Exports_js_1 = require_Exports();
var Exports_js_2 = require_Exports3();
var Exports_js_3 = require_Exports7();
var SpeechConnectionMessage_Internal_js_1 = require_SpeechConnectionMessage_Internal();
var TranscriptionServiceRecognizer = class extends Exports_js_3.ConversationServiceRecognizer {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, transcriber) {
super(authentication, connectionFactory, audioSource, recognizerConfig, transcriber);
this.privTranscriberRecognizer = transcriber;
this.sendPrePayloadJSONOverride = (connection) => this.sendTranscriptionStartJSON(connection);
if (this.privRecognizerConfig.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps) === "true") {
this.privSpeechContext.setWordLevelTimings();
}
}
async sendSpeechEventAsync(info, command) {
if (!!this.privRequestSession.isRecognizing) {
const connection = await this.fetchConnection();
await this.sendSpeechEvent(connection, this.createSpeechEventPayload(info, command));
}
}
async sendMeetingSpeechEventAsync(info, command) {
if (!!this.privRequestSession.isRecognizing) {
const connection = await this.fetchConnection();
await this.sendSpeechEvent(connection, this.createMeetingSpeechEventPayload(info, command));
}
}
processTypeSpecificMessages(connectionMessage) {
return this.processSpeechMessages(connectionMessage);
}
handleRecognizedCallback(result, offset, sessionId) {
try {
const event = new Exports_js_2.SpeechRecognitionEventArgs(result, offset, sessionId);
this.privTranscriberRecognizer.recognized(this.privTranscriberRecognizer, event);
if (!!this.privSuccessCallback) {
try {
this.privSuccessCallback(result);
} catch (e) {
if (!!this.privErrorCallback) {
this.privErrorCallback(e);
}
}
this.privSuccessCallback = void 0;
this.privErrorCallback = void 0;
}
} catch (error) {
}
}
handleRecognizingCallback(result, duration, sessionId) {
try {
const ev = new Exports_js_2.SpeechRecognitionEventArgs(result, duration, sessionId);
this.privTranscriberRecognizer.recognizing(this.privTranscriberRecognizer, ev);
} catch (error) {
}
}
// Cancels recognition.
cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
const properties = new Exports_js_2.PropertyCollection();
properties.setProperty(Exports_js_3.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[errorCode]);
if (this.privTranscriberRecognizer.IsMeetingRecognizer()) {
if (!!this.privTranscriberRecognizer.canceled) {
const cancelEvent = new Exports_js_2.MeetingTranscriptionCanceledEventArgs(cancellationReason, error, errorCode, void 0, sessionId);
try {
this.privTranscriberRecognizer.canceled(this.privTranscriberRecognizer, cancelEvent);
} catch {
}
}
} else {
if (!!this.privTranscriberRecognizer.canceled) {
const cancelEvent = new Exports_js_2.ConversationTranscriptionCanceledEventArgs(cancellationReason, error, errorCode, void 0, sessionId);
try {
this.privTranscriberRecognizer.canceled(this.privTranscriberRecognizer, cancelEvent);
} catch {
}
}
}
if (!!this.privSuccessCallback) {
const result = new Exports_js_2.SpeechRecognitionResult(
requestId,
Exports_js_2.ResultReason.Canceled,
void 0,
// Text
void 0,
// Duration
void 0,
// Offset
void 0,
// Language
void 0,
// Language Detection Confidence
void 0,
// Speaker Id
error,
void 0,
// Json
properties
);
try {
this.privSuccessCallback(result);
this.privSuccessCallback = void 0;
} catch {
}
}
}
// Encapsulated for derived service recognizers that need to send additional JSON
async sendTranscriptionStartJSON(connection) {
await this.sendSpeechContext(connection, true);
if (this.privTranscriberRecognizer.IsMeetingRecognizer()) {
const info = this.privTranscriberRecognizer.getMeetingInfo();
const payload = this.createMeetingSpeechEventPayload(info, "start");
await this.sendSpeechEvent(connection, payload);
} else {
const info = this.privTranscriberRecognizer.getConversationInfo();
const payload = this.createSpeechEventPayload(info, "start");
await this.sendSpeechEvent(connection, payload);
}
await this.sendWaveHeader(connection);
return;
}
sendSpeechEvent(connection, payload) {
const speechEventJson = JSON.stringify(payload);
if (speechEventJson) {
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "speech.event", this.privRequestSession.requestId, "application/json", speechEventJson));
}
return;
}
createSpeechEventPayload(info, command) {
const eventDict = { id: "meeting", name: command, meeting: info.conversationProperties };
eventDict.meeting.id = info.id;
eventDict.meeting.attendees = info.participants;
return eventDict;
}
createMeetingSpeechEventPayload(info, command) {
const eventDict = { id: "meeting", name: command, meeting: info.meetingProperties };
eventDict.meeting.id = info.id;
eventDict.meeting.attendees = info.participants;
return eventDict;
}
};
exports.TranscriptionServiceRecognizer = TranscriptionServiceRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/DetailedSpeechPhrase.js
var require_DetailedSpeechPhrase = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/DetailedSpeechPhrase.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DetailedSpeechPhrase = void 0;
var Exports_js_1 = require_Exports7();
var DetailedSpeechPhrase = class _DetailedSpeechPhrase {
constructor(json, baseOffset) {
this.privDetailedSpeechPhrase = JSON.parse(json);
this.privDetailedSpeechPhrase.RecognitionStatus = this.mapRecognitionStatus(this.privDetailedSpeechPhrase.RecognitionStatus);
this.updateOffsets(baseOffset);
}
static fromJSON(json, baseOffset) {
return new _DetailedSpeechPhrase(json, baseOffset);
}
updateOffsets(baseOffset) {
this.privDetailedSpeechPhrase.Offset += baseOffset;
if (!!this.privDetailedSpeechPhrase.NBest) {
for (const phrase of this.privDetailedSpeechPhrase.NBest) {
if (!!phrase.Words) {
for (const word of phrase.Words) {
word.Offset += baseOffset;
}
}
if (!!phrase.DisplayWords) {
for (const word of phrase.DisplayWords) {
word.Offset += baseOffset;
}
}
}
}
}
asJson() {
const jsonObj = { ...this.privDetailedSpeechPhrase };
return JSON.stringify({
...jsonObj,
RecognitionStatus: Exports_js_1.RecognitionStatus[jsonObj.RecognitionStatus]
});
}
get RecognitionStatus() {
return this.privDetailedSpeechPhrase.RecognitionStatus;
}
get NBest() {
return this.privDetailedSpeechPhrase.NBest;
}
get Duration() {
return this.privDetailedSpeechPhrase.Duration;
}
get Offset() {
return this.privDetailedSpeechPhrase.Offset;
}
get Language() {
return this.privDetailedSpeechPhrase.PrimaryLanguage === void 0 ? void 0 : this.privDetailedSpeechPhrase.PrimaryLanguage.Language;
}
get LanguageDetectionConfidence() {
return this.privDetailedSpeechPhrase.PrimaryLanguage === void 0 ? void 0 : this.privDetailedSpeechPhrase.PrimaryLanguage.Confidence;
}
get Text() {
if (!!this.privDetailedSpeechPhrase.NBest && this.privDetailedSpeechPhrase.NBest[0]) {
return this.privDetailedSpeechPhrase.NBest[0].Display || this.privDetailedSpeechPhrase.NBest[0].DisplayText;
}
return this.privDetailedSpeechPhrase.DisplayText;
}
get SpeakerId() {
return this.privDetailedSpeechPhrase.SpeakerId;
}
mapRecognitionStatus(status) {
if (typeof status === "string") {
return Exports_js_1.RecognitionStatus[status];
} else if (typeof status === "number") {
return status;
}
}
};
exports.DetailedSpeechPhrase = DetailedSpeechPhrase;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SimpleSpeechPhrase.js
var require_SimpleSpeechPhrase = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SimpleSpeechPhrase.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleSpeechPhrase = void 0;
var Exports_js_1 = require_Exports7();
var SimpleSpeechPhrase = class _SimpleSpeechPhrase {
constructor(json, baseOffset = 0) {
this.privSimpleSpeechPhrase = JSON.parse(json);
this.privSimpleSpeechPhrase.RecognitionStatus = this.mapRecognitionStatus(this.privSimpleSpeechPhrase.RecognitionStatus);
this.updateOffset(baseOffset);
}
static fromJSON(json, baseOffset) {
return new _SimpleSpeechPhrase(json, baseOffset);
}
updateOffset(baseOffset) {
this.privSimpleSpeechPhrase.Offset += baseOffset;
}
asJson() {
const jsonObj = { ...this.privSimpleSpeechPhrase };
return JSON.stringify({
...jsonObj,
RecognitionStatus: Exports_js_1.RecognitionStatus[jsonObj.RecognitionStatus]
});
}
get RecognitionStatus() {
return this.privSimpleSpeechPhrase.RecognitionStatus;
}
get DisplayText() {
return this.privSimpleSpeechPhrase.DisplayText;
}
get Offset() {
return this.privSimpleSpeechPhrase.Offset;
}
get Duration() {
return this.privSimpleSpeechPhrase.Duration;
}
get Language() {
return this.privSimpleSpeechPhrase.PrimaryLanguage === void 0 ? void 0 : this.privSimpleSpeechPhrase.PrimaryLanguage.Language;
}
get LanguageDetectionConfidence() {
return this.privSimpleSpeechPhrase.PrimaryLanguage === void 0 ? void 0 : this.privSimpleSpeechPhrase.PrimaryLanguage.Confidence;
}
get SpeakerId() {
return this.privSimpleSpeechPhrase.SpeakerId;
}
mapRecognitionStatus(status) {
if (typeof status === "string") {
return Exports_js_1.RecognitionStatus[status];
} else if (typeof status === "number") {
return status;
}
}
};
exports.SimpleSpeechPhrase = SimpleSpeechPhrase;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/AddedLmIntent.js
var require_AddedLmIntent = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/AddedLmIntent.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AddedLmIntent = void 0;
var AddedLmIntent = class {
/**
* Creates and initializes an instance of this class.
* @constructor
* @param modelImpl - The model.
* @param intentName - The intent name.
*/
constructor(modelImpl, intentName) {
this.modelImpl = modelImpl;
this.intentName = intentName;
}
};
exports.AddedLmIntent = AddedLmIntent;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/IntentServiceRecognizer.js
var require_IntentServiceRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/IntentServiceRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentServiceRecognizer = void 0;
var Exports_js_1 = require_Exports();
var Exports_js_2 = require_Exports3();
var Exports_js_3 = require_Exports7();
var IntentServiceRecognizer = class extends Exports_js_3.ServiceRecognizerBase {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) {
super(authentication, connectionFactory, audioSource, recognizerConfig, recognizer);
this.privIntentRecognizer = recognizer;
this.privIntentDataSent = false;
recognizerConfig.recognitionEndpointVersion = "1";
}
setIntents(addedIntents, umbrellaIntent) {
this.privAddedLmIntents = addedIntents;
this.privUmbrellaIntent = umbrellaIntent;
this.privIntentDataSent = true;
}
processTypeSpecificMessages(connectionMessage) {
let result;
let ev;
let processed = false;
const resultProps = new Exports_js_2.PropertyCollection();
if (connectionMessage.messageType === Exports_js_1.MessageType.Text) {
resultProps.setProperty(Exports_js_2.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
}
switch (connectionMessage.path.toLowerCase()) {
case "speech.hypothesis":
const speechHypothesis = Exports_js_3.SpeechHypothesis.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
result = new Exports_js_2.IntentRecognitionResult(void 0, this.privRequestSession.requestId, Exports_js_2.ResultReason.RecognizingIntent, speechHypothesis.Text, speechHypothesis.Duration, speechHypothesis.Offset, speechHypothesis.Language, speechHypothesis.LanguageDetectionConfidence, void 0, speechHypothesis.asJson(), resultProps);
this.privRequestSession.onHypothesis(result.offset);
ev = new Exports_js_2.IntentRecognitionEventArgs(result, speechHypothesis.Offset, this.privRequestSession.sessionId);
if (!!this.privIntentRecognizer.recognizing) {
try {
this.privIntentRecognizer.recognizing(this.privIntentRecognizer, ev);
} catch (error) {
}
}
processed = true;
break;
case "speech.phrase":
const simple = Exports_js_3.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
result = new Exports_js_2.IntentRecognitionResult(void 0, this.privRequestSession.requestId, Exports_js_3.EnumTranslation.implTranslateRecognitionResult(simple.RecognitionStatus), simple.DisplayText, simple.Duration, simple.Offset, simple.Language, simple.LanguageDetectionConfidence, void 0, simple.asJson(), resultProps);
ev = new Exports_js_2.IntentRecognitionEventArgs(result, result.offset, this.privRequestSession.sessionId);
const sendEvent = () => {
if (!!this.privIntentRecognizer.recognized) {
try {
this.privIntentRecognizer.recognized(this.privIntentRecognizer, ev);
} catch (error) {
}
}
if (!!this.privSuccessCallback) {
try {
this.privSuccessCallback(result);
} catch (e) {
if (!!this.privErrorCallback) {
this.privErrorCallback(e);
}
}
this.privSuccessCallback = void 0;
this.privErrorCallback = void 0;
}
};
if (false === this.privIntentDataSent || Exports_js_2.ResultReason.NoMatch === ev.result.reason) {
this.privRequestSession.onPhraseRecognized(ev.offset + ev.result.duration);
sendEvent();
} else {
this.privPendingIntentArgs = ev;
}
processed = true;
break;
case "response":
ev = this.privPendingIntentArgs;
this.privPendingIntentArgs = void 0;
if (void 0 === ev) {
if ("" === connectionMessage.textBody) {
return;
}
ev = new Exports_js_2.IntentRecognitionEventArgs(new Exports_js_2.IntentRecognitionResult(), 0, this.privRequestSession.sessionId);
}
const intentResponse = Exports_js_3.IntentResponse.fromJSON(connectionMessage.textBody);
if (null !== intentResponse && !!intentResponse.topScoringIntent && !!intentResponse.topScoringIntent.intent) {
let addedIntent = this.privAddedLmIntents[intentResponse.topScoringIntent.intent];
if (this.privUmbrellaIntent !== void 0) {
addedIntent = this.privUmbrellaIntent;
}
if (!!addedIntent) {
const intentId = addedIntent === void 0 || addedIntent.intentName === void 0 ? intentResponse.topScoringIntent.intent : addedIntent.intentName;
let reason = ev.result.reason;
if (void 0 !== intentId) {
reason = Exports_js_2.ResultReason.RecognizedIntent;
}
const properties = void 0 !== ev.result.properties ? ev.result.properties : new Exports_js_2.PropertyCollection();
properties.setProperty(Exports_js_2.PropertyId.LanguageUnderstandingServiceResponse_JsonResult, connectionMessage.textBody);
ev = new Exports_js_2.IntentRecognitionEventArgs(new Exports_js_2.IntentRecognitionResult(intentId, ev.result.resultId, reason, ev.result.text, ev.result.duration, ev.result.offset, void 0, void 0, 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);
} catch (error) {
}
}
if (!!this.privSuccessCallback) {
try {
this.privSuccessCallback(ev.result);
} catch (e) {
if (!!this.privErrorCallback) {
this.privErrorCallback(e);
}
}
this.privSuccessCallback = void 0;
this.privErrorCallback = void 0;
}
processed = true;
break;
default:
break;
}
const defferal = new Exports_js_1.Deferred();
defferal.resolve(processed);
return defferal.promise;
}
// Cancels recognition.
cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
const properties = new Exports_js_2.PropertyCollection();
properties.setProperty(Exports_js_3.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[errorCode]);
if (!!this.privIntentRecognizer.canceled) {
const cancelEvent = new Exports_js_2.IntentRecognitionCanceledEventArgs(cancellationReason, error, errorCode, void 0, void 0, sessionId);
try {
this.privIntentRecognizer.canceled(this.privIntentRecognizer, cancelEvent);
} catch {
}
}
if (!!this.privSuccessCallback) {
const result = new Exports_js_2.IntentRecognitionResult(
void 0,
// Intent Id
requestId,
Exports_js_2.ResultReason.Canceled,
void 0,
// Text
void 0,
// Duration
void 0,
// Offset
void 0,
// Language
void 0,
// LanguageDetectionConfidence
error,
void 0,
// Json
properties
);
try {
this.privSuccessCallback(result);
this.privSuccessCallback = void 0;
} catch {
}
}
}
};
exports.IntentServiceRecognizer = IntentServiceRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/IntentResponse.js
var require_IntentResponse = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/IntentResponse.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntentResponse = void 0;
var IntentResponse = class _IntentResponse {
constructor(json) {
if (json === "") {
this.privIntentResponse = {};
} else {
this.privIntentResponse = JSON.parse(json);
}
}
static fromJSON(json) {
return new _IntentResponse(json);
}
get query() {
return this.privIntentResponse.query;
}
get topScoringIntent() {
return this.privIntentResponse.topScoringIntent;
}
get entities() {
return this.privIntentResponse.entities;
}
};
exports.IntentResponse = IntentResponse;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SpeakerResponse.js
var require_SpeakerResponse = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SpeakerResponse.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceTelemetryListener.Internal.js
var require_ServiceTelemetryListener_Internal = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceTelemetryListener.Internal.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServiceTelemetryListener = void 0;
var Exports_js_1 = require_Exports();
var RecognitionEvents_js_1 = require_RecognitionEvents();
var ServiceTelemetryListener = class {
constructor(requestId, audioSourceId, audioNodeId) {
this.privIsDisposed = false;
this.privListeningTriggerMetric = null;
this.privMicMetric = null;
this.privConnectionEstablishMetric = null;
this.privRequestId = requestId;
this.privAudioSourceId = audioSourceId;
this.privAudioNodeId = audioNodeId;
this.privReceivedMessages = {};
this.privPhraseLatencies = [];
this.privHypothesisLatencies = [];
}
phraseReceived(audioReceivedTime) {
if (audioReceivedTime > 0) {
this.privPhraseLatencies.push(Date.now() - audioReceivedTime);
}
}
hypothesisReceived(audioReceivedTime) {
if (audioReceivedTime > 0) {
this.privHypothesisLatencies.push(Date.now() - audioReceivedTime);
}
}
onEvent(e) {
if (this.privIsDisposed) {
return;
}
if (e instanceof RecognitionEvents_js_1.RecognitionTriggeredEvent && e.requestId === this.privRequestId) {
this.privListeningTriggerMetric = {
End: e.eventTime,
Name: "ListeningTrigger",
Start: e.eventTime
};
}
if (e instanceof Exports_js_1.AudioStreamNodeAttachingEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {
this.privMicStartTime = e.eventTime;
}
if (e instanceof Exports_js_1.AudioStreamNodeAttachedEvent && e.audioSourceId === this.privAudioSourceId && e.audioNodeId === this.privAudioNodeId) {
this.privMicStartTime = e.eventTime;
}
if (e instanceof Exports_js_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_js_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_js_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_js_1.ConnectingToServiceEvent && e.requestId === this.privRequestId) {
this.privConnectionId = e.sessionId;
}
if (e instanceof Exports_js_1.ConnectionStartEvent && e.connectionId === this.privConnectionId) {
this.privConnectionStartTime = e.eventTime;
}
if (e instanceof Exports_js_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_js_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_js_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();
}
const maxMessagesToSend = 50;
if (this.privReceivedMessages[e.message.headers.path].length < maxMessagesToSend) {
this.privReceivedMessages[e.message.headers.path].push(e.networkReceivedTime);
}
}
}
}
getTelemetry() {
const 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
});
}
const telemetry = {
Metrics: metrics,
ReceivedMessages: this.privReceivedMessages
};
const json = JSON.stringify(telemetry);
this.privReceivedMessages = {};
this.privListeningTriggerMetric = null;
this.privMicMetric = null;
this.privConnectionEstablishMetric = null;
this.privPhraseLatencies = [];
this.privHypothesisLatencies = [];
return json;
}
// Determines if there are any telemetry events to send to the service.
get hasTelemetry() {
return Object.keys(this.privReceivedMessages).length !== 0 || this.privListeningTriggerMetric !== null || this.privMicMetric !== null || this.privConnectionEstablishMetric !== null || this.privPhraseLatencies.length !== 0 || this.privHypothesisLatencies.length !== 0;
}
dispose() {
this.privIsDisposed = true;
}
getConnectionError(statusCode) {
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();
}
}
};
exports.ServiceTelemetryListener = ServiceTelemetryListener;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/RequestSession.js
var require_RequestSession = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/RequestSession.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestSession = void 0;
var Exports_js_1 = require_Exports();
var RecognitionEvents_js_1 = require_RecognitionEvents();
var ServiceTelemetryListener_Internal_js_1 = require_ServiceTelemetryListener_Internal();
var RequestSession = class {
constructor(audioSourceId) {
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.privRecognitionBytesSent = 0;
this.privRecogNumber = 0;
this.privInTurn = false;
this.privConnectionAttempts = 0;
this.privAudioSourceId = audioSourceId;
this.privRequestId = (0, Exports_js_1.createNoDashGuid)();
this.privAudioNodeId = (0, Exports_js_1.createNoDashGuid)();
this.privTurnDeferral = new Exports_js_1.Deferred();
this.privTurnDeferral.resolve();
}
get sessionId() {
return this.privSessionId;
}
get requestId() {
return this.privRequestId;
}
get audioNodeId() {
return this.privAudioNodeId;
}
get turnCompletionPromise() {
return this.privTurnDeferral.promise;
}
get isSpeechEnded() {
return this.privIsSpeechEnded;
}
get isRecognizing() {
return this.privIsRecognizing;
}
get currentTurnAudioOffset() {
return this.privTurnStartAudioOffset;
}
get recogNumber() {
return this.privRecogNumber;
}
get numConnectionAttempts() {
return this.privConnectionAttempts;
}
// The number of bytes sent for the current connection.
// Counter is reset to 0 each time a connection is established.
get bytesSent() {
return this.privBytesSent;
}
// The number of bytes sent for the current recognition.
// Counter is reset to 0 each time recognition is started.
get recognitionBytesSent() {
return this.privRecognitionBytesSent;
}
listenForServiceTelemetry(eventSource) {
if (!!this.privServiceTelemetryListener) {
this.privDetachables.push(eventSource.attachListener(this.privServiceTelemetryListener));
}
}
startNewRecognition() {
this.privRecognitionBytesSent = 0;
this.privIsSpeechEnded = false;
this.privIsRecognizing = true;
this.privTurnStartAudioOffset = 0;
this.privLastRecoOffset = 0;
this.privRecogNumber++;
this.privServiceTelemetryListener = new ServiceTelemetryListener_Internal_js_1.ServiceTelemetryListener(this.privRequestId, this.privAudioSourceId, this.privAudioNodeId);
this.onEvent(new RecognitionEvents_js_1.RecognitionTriggeredEvent(this.requestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId));
}
async onAudioSourceAttachCompleted(audioNode, isError) {
this.privAudioNode = audioNode;
this.privIsAudioNodeDetached = false;
if (isError) {
await this.onComplete();
} else {
this.onEvent(new RecognitionEvents_js_1.ListeningStartedEvent(this.privRequestId, this.privSessionId, this.privAudioSourceId, this.privAudioNodeId));
}
}
onPreConnectionStart(authFetchEventId, connectionId) {
this.privAuthFetchEventId = authFetchEventId;
this.privSessionId = connectionId;
this.onEvent(new RecognitionEvents_js_1.ConnectingToServiceEvent(this.privRequestId, this.privAuthFetchEventId, this.privSessionId));
}
async onAuthCompleted(isError) {
if (isError) {
await this.onComplete();
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async onConnectionEstablishCompleted(statusCode, reason) {
if (statusCode === 200) {
this.onEvent(new RecognitionEvents_js_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;
} else if (statusCode === 403) {
await this.onComplete();
}
}
async onServiceTurnEndResponse(continuousRecognition) {
this.privTurnDeferral.resolve();
if (!continuousRecognition || this.isSpeechEnded) {
await this.onComplete();
this.privInTurn = false;
} else {
this.privTurnStartAudioOffset = this.privLastRecoOffset;
this.privAudioNode.replay();
}
}
onSpeechContext() {
this.privRequestId = (0, Exports_js_1.createNoDashGuid)();
}
onServiceTurnStartResponse() {
if (!!this.privTurnDeferral && !!this.privInTurn) {
this.privTurnDeferral.reject("Another turn started before current completed.");
this.privTurnDeferral.promise.then().catch(() => {
});
}
this.privInTurn = true;
this.privTurnDeferral = new Exports_js_1.Deferred();
}
onHypothesis(offset) {
if (!this.privHypothesisReceived) {
this.privHypothesisReceived = true;
this.privServiceTelemetryListener.hypothesisReceived(this.privAudioNode.findTimeAtOffset(offset));
}
}
onPhraseRecognized(offset) {
this.privServiceTelemetryListener.phraseReceived(this.privAudioNode.findTimeAtOffset(offset));
this.onServiceRecognized(offset);
}
onServiceRecognized(offset) {
this.privLastRecoOffset = offset;
this.privHypothesisReceived = false;
this.privAudioNode.shrinkBuffers(offset);
this.privConnectionAttempts = 0;
}
onAudioSent(bytesSent) {
this.privBytesSent += bytesSent;
this.privRecognitionBytesSent += bytesSent;
}
onRetryConnection() {
this.privConnectionAttempts++;
}
async dispose() {
if (!this.privIsDisposed) {
this.privIsDisposed = true;
for (const detachable of this.privDetachables) {
await detachable.detach();
}
if (!!this.privServiceTelemetryListener) {
this.privServiceTelemetryListener.dispose();
}
this.privIsRecognizing = false;
}
}
getTelemetry() {
if (this.privServiceTelemetryListener.hasTelemetry) {
return this.privServiceTelemetryListener.getTelemetry();
} else {
return null;
}
}
async onStopRecognizing() {
await this.onComplete();
}
// Should be called with the audioNode for this session has indicated that it is out of speech.
onSpeechEnded() {
this.privIsSpeechEnded = true;
}
onEvent(event) {
if (!!this.privServiceTelemetryListener) {
this.privServiceTelemetryListener.onEvent(event);
}
Exports_js_1.Events.instance.onEvent(event);
}
async onComplete() {
if (!!this.privIsRecognizing) {
this.privIsRecognizing = false;
await this.detachAudioNode();
}
}
async detachAudioNode() {
if (!this.privIsAudioNodeDetached) {
this.privIsAudioNodeDetached = true;
if (this.privAudioNode) {
await this.privAudioNode.detach();
}
}
}
};
exports.RequestSession = RequestSession;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseOutput/PhraseOutput.js
var require_PhraseOutput = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/PhraseOutput/PhraseOutput.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TentativePhraseResultsOption = exports.OutputFormat = exports.PhraseExtension = exports.PhraseOption = void 0;
var PhraseOption;
(function(PhraseOption2) {
PhraseOption2["WordTimings"] = "WordTimings";
PhraseOption2["SNR"] = "SNR";
PhraseOption2["Pronunciation"] = "Pronunciation";
PhraseOption2["WordPronunciation"] = "WordPronunciation";
PhraseOption2["WordConfidence"] = "WordConfidence";
PhraseOption2["Words"] = "Words";
PhraseOption2["Sentiment"] = "Sentiment";
PhraseOption2["PronunciationAssessment"] = "PronunciationAssessment";
PhraseOption2["ContentAssessment"] = "ContentAssessment";
PhraseOption2["PhraseAMScore"] = "PhraseAMScore";
PhraseOption2["PhraseLMScore"] = "PhraseLMScore";
PhraseOption2["WordAMScore"] = "WordAMScore";
PhraseOption2["WordLMScore"] = "WordLMScore";
PhraseOption2["RuleTree"] = "RuleTree";
PhraseOption2["NBestTimings"] = "NBestTimings";
PhraseOption2["DecoderDiagnostics"] = "DecoderDiagnostics";
PhraseOption2["DisplayWordTimings"] = "DisplayWordTimings";
PhraseOption2["DisplayWords"] = "DisplayWords";
})(PhraseOption = exports.PhraseOption || (exports.PhraseOption = {}));
var PhraseExtension;
(function(PhraseExtension2) {
PhraseExtension2["Graph"] = "Graph";
PhraseExtension2["Corrections"] = "Corrections";
PhraseExtension2["Sentiment"] = "Sentiment";
})(PhraseExtension = exports.PhraseExtension || (exports.PhraseExtension = {}));
var OutputFormat3;
(function(OutputFormat4) {
OutputFormat4["Simple"] = "Simple";
OutputFormat4["Detailed"] = "Detailed";
})(OutputFormat3 = exports.OutputFormat || (exports.OutputFormat = {}));
var TentativePhraseResultsOption;
(function(TentativePhraseResultsOption2) {
TentativePhraseResultsOption2["None"] = "None";
TentativePhraseResultsOption2["Always"] = "Always";
})(TentativePhraseResultsOption = exports.TentativePhraseResultsOption || (exports.TentativePhraseResultsOption = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechContext.js
var require_SpeechContext = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechContext.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechContext = void 0;
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var PhraseOutput_js_1 = require_PhraseOutput();
var SpeechContext = class {
constructor(dynamicGrammar) {
this.privContext = {};
this.privDynamicGrammar = dynamicGrammar;
}
getContext() {
return this.privContext;
}
/**
* @Internal
* This is only used by pronunciation assessment config.
* Do not use externally, object returned will change without warning or notice.
*/
setPronunciationAssessmentParams(params, contentAssessmentTopic, isSpeakerDiarizationEnabled = false) {
if (this.privContext.phraseDetection === void 0) {
this.privContext.phraseDetection = {
enrichment: {
pronunciationAssessment: {}
}
};
}
if (this.privContext.phraseDetection.enrichment === void 0) {
this.privContext.phraseDetection.enrichment = {
pronunciationAssessment: {}
};
}
this.privContext.phraseDetection.enrichment.pronunciationAssessment = JSON.parse(params) || {};
if (isSpeakerDiarizationEnabled) {
this.privContext.phraseDetection.mode = PhraseDetectionContext_js_1.RecognitionMode.Conversation;
}
this.setWordLevelTimings();
this.privContext.phraseOutput.detailed.options.push(PhraseOutput_js_1.PhraseOption.PronunciationAssessment);
if (this.privContext.phraseOutput.detailed.options.indexOf(PhraseOutput_js_1.PhraseOption.SNR) === -1) {
this.privContext.phraseOutput.detailed.options.push(PhraseOutput_js_1.PhraseOption.SNR);
}
if (!!contentAssessmentTopic) {
this.privContext.phraseDetection.enrichment.contentAssessment = {
topic: contentAssessmentTopic
};
this.privContext.phraseOutput.detailed.options.push(PhraseOutput_js_1.PhraseOption.ContentAssessment);
}
}
setDetailedOutputFormat() {
if (this.privContext.phraseOutput === void 0) {
this.privContext.phraseOutput = {
detailed: {
options: []
}
};
}
if (this.privContext.phraseOutput.detailed === void 0) {
this.privContext.phraseOutput.detailed = {
options: []
};
}
this.privContext.phraseOutput.format = PhraseOutput_js_1.OutputFormat.Detailed;
}
setWordLevelTimings() {
if (this.privContext.phraseOutput === void 0) {
this.privContext.phraseOutput = {
detailed: {
options: []
}
};
}
if (this.privContext.phraseOutput.detailed === void 0) {
this.privContext.phraseOutput.detailed = {
options: []
};
}
this.privContext.phraseOutput.format = PhraseOutput_js_1.OutputFormat.Detailed;
if (this.privContext.phraseOutput.detailed.options.indexOf(PhraseOutput_js_1.PhraseOption.WordTimings) === -1) {
this.privContext.phraseOutput.detailed.options.push(PhraseOutput_js_1.PhraseOption.WordTimings);
}
}
setSpeakerDiarizationAudioOffsetMs(audioOffsetMs) {
this.privContext.phraseDetection.speakerDiarization.audioOffsetMs = audioOffsetMs;
}
toJSON() {
const dgi = this.privDynamicGrammar.generateGrammarObject();
this.privContext.dgi = dgi;
const ret = JSON.stringify(this.privContext);
return ret;
}
};
exports.SpeechContext = SpeechContext;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/Dgi/Group.js
var require_Group = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/Dgi/Group.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubstringMatchType = exports.GroupType = void 0;
var GroupType;
(function(GroupType2) {
GroupType2["IntentText"] = "IntentText";
GroupType2["IntentEntity"] = "IntentEntity";
GroupType2["Generic"] = "Generic";
GroupType2["People"] = "People";
GroupType2["Place"] = "Place";
GroupType2["DynamicEntity"] = "DynamicEntity";
})(GroupType = exports.GroupType || (exports.GroupType = {}));
var SubstringMatchType;
(function(SubstringMatchType2) {
SubstringMatchType2["None"] = "None";
SubstringMatchType2["LeftRooted"] = "LeftRooted";
SubstringMatchType2["PartialName"] = "PartialName";
SubstringMatchType2["MiddleOfSentence"] = "MiddleOfSentence";
})(SubstringMatchType = exports.SubstringMatchType || (exports.SubstringMatchType = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/DynamicGrammarBuilder.js
var require_DynamicGrammarBuilder = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/DynamicGrammarBuilder.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DynamicGrammarBuilder = void 0;
var Group_js_1 = require_Group();
var DynamicGrammarBuilder = class {
constructor() {
this.privWeight = 1;
}
// Adds one more reference phrases to the dynamic grammar to send.
// All added phrases are generic phrases.
addPhrase(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.
clearPhrases() {
this.privPhrases = void 0;
}
// Adds one or more reference grammars to the current grammar.
addReferenceGrammar(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.
clearGrammars() {
this.privGrammars = void 0;
}
// Sets the weight for the dynamic grammar.
setWeight(weight) {
this.privWeight = weight;
}
// 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
generateGrammarObject() {
if (this.privGrammars === void 0 && this.privPhrases === void 0) {
return void 0;
}
const retObj = {};
retObj.referenceGrammars = this.privGrammars;
if (void 0 !== this.privPhrases && 0 !== this.privPhrases.length) {
const retPhrases = [];
this.privPhrases.forEach((value) => {
retPhrases.push({
text: value
});
});
retObj.groups = [{ type: Group_js_1.GroupType.Generic, items: retPhrases }];
retObj.bias = this.privWeight;
}
return retObj;
}
};
exports.DynamicGrammarBuilder = DynamicGrammarBuilder;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/ActivityResponsePayload.js
var require_ActivityResponsePayload = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/ActivityResponsePayload.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageDataStreamType = exports.ActivityPayloadResponse = void 0;
var ActivityPayloadResponse = class _ActivityPayloadResponse {
constructor(json) {
this.privActivityResponse = JSON.parse(json);
}
static fromJSON(json) {
return new _ActivityPayloadResponse(json);
}
get conversationId() {
return this.privActivityResponse.conversationId;
}
get messageDataStreamType() {
return this.privActivityResponse.messageDataStreamType;
}
get messagePayload() {
return this.privActivityResponse.messagePayload;
}
get version() {
return this.privActivityResponse.version;
}
};
exports.ActivityPayloadResponse = ActivityPayloadResponse;
var MessageDataStreamType;
(function(MessageDataStreamType2) {
MessageDataStreamType2[MessageDataStreamType2["None"] = 0] = "None";
MessageDataStreamType2[MessageDataStreamType2["TextToSpeechAudio"] = 1] = "TextToSpeechAudio";
})(MessageDataStreamType = exports.MessageDataStreamType || (exports.MessageDataStreamType = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/DialogServiceTurnState.js
var require_DialogServiceTurnState = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/DialogServiceTurnState.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogServiceTurnState = void 0;
var AudioOutputFormat_js_1 = require_AudioOutputFormat();
var AudioOutputStream_js_1 = require_AudioOutputStream();
var ActivityResponsePayload_js_1 = require_ActivityResponsePayload();
var DialogServiceTurnState = class {
constructor(manager, requestId) {
this.privRequestId = requestId;
this.privIsCompleted = false;
this.privAudioStream = null;
this.privTurnManager = manager;
this.resetTurnEndTimeout();
}
get audioStream() {
this.resetTurnEndTimeout();
return this.privAudioStream;
}
processActivityPayload(payload, audioFormat) {
if (payload.messageDataStreamType === ActivityResponsePayload_js_1.MessageDataStreamType.TextToSpeechAudio) {
this.privAudioStream = AudioOutputStream_js_1.AudioOutputStream.createPullStream();
this.privAudioStream.format = audioFormat !== void 0 ? audioFormat : AudioOutputFormat_js_1.AudioOutputFormatImpl.getDefaultOutputFormat();
}
return this.privAudioStream;
}
endAudioStream() {
if (this.privAudioStream !== null && !this.privAudioStream.isClosed) {
this.privAudioStream.close();
}
}
complete() {
if (this.privTimeoutToken !== void 0) {
clearTimeout(this.privTimeoutToken);
}
this.endAudioStream();
}
resetTurnEndTimeout() {
if (this.privTimeoutToken !== void 0) {
clearTimeout(this.privTimeoutToken);
}
this.privTimeoutToken = setTimeout(() => {
this.privTurnManager.CompleteTurn(this.privRequestId);
return;
}, 2e3);
}
};
exports.DialogServiceTurnState = DialogServiceTurnState;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/DialogServiceTurnStateManager.js
var require_DialogServiceTurnStateManager = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/DialogServiceTurnStateManager.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogServiceTurnStateManager = void 0;
var Error_js_1 = require_Error();
var DialogServiceTurnState_js_1 = require_DialogServiceTurnState();
var DialogServiceTurnStateManager = class {
constructor() {
this.privTurnMap = /* @__PURE__ */ new Map();
return;
}
StartTurn(id) {
if (this.privTurnMap.has(id)) {
throw new Error_js_1.InvalidOperationError("Service error: There is already a turn with id:" + id);
}
const turnState = new DialogServiceTurnState_js_1.DialogServiceTurnState(this, id);
this.privTurnMap.set(id, turnState);
return this.privTurnMap.get(id);
}
GetTurn(id) {
return this.privTurnMap.get(id);
}
CompleteTurn(id) {
if (!this.privTurnMap.has(id)) {
throw new Error_js_1.InvalidOperationError("Service error: Received turn end for an unknown turn id:" + id);
}
const turnState = this.privTurnMap.get(id);
turnState.complete();
this.privTurnMap.delete(id);
return turnState;
}
};
exports.DialogServiceTurnStateManager = DialogServiceTurnStateManager;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/InvocationSource.js
var require_InvocationSource = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/InvocationSource.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvocationSource = void 0;
var InvocationSource;
(function(InvocationSource2) {
InvocationSource2["None"] = "None";
InvocationSource2["VoiceActivationWithKeyword"] = "VoiceActivationWithKeyword";
})(InvocationSource = exports.InvocationSource || (exports.InvocationSource = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/KeywordDetection/KeywordDetection.js
var require_KeywordDetection = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/KeywordDetection/KeywordDetection.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OnRejectAction = exports.KeywordDetectionType = void 0;
var KeywordDetectionType;
(function(KeywordDetectionType2) {
KeywordDetectionType2["StartTrigger"] = "StartTrigger";
})(KeywordDetectionType = exports.KeywordDetectionType || (exports.KeywordDetectionType = {}));
var OnRejectAction;
(function(OnRejectAction2) {
OnRejectAction2["EndOfTurn"] = "EndOfTurn";
OnRejectAction2["Continue"] = "Continue";
})(OnRejectAction = exports.OnRejectAction || (exports.OnRejectAction = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/DialogServiceAdapter.js
var require_DialogServiceAdapter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/DialogServiceAdapter.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DialogServiceAdapter = void 0;
var Exports_js_1 = require_Exports4();
var DialogEvents_js_1 = require_DialogEvents();
var Exports_js_2 = require_Exports();
var AudioOutputFormat_js_1 = require_AudioOutputFormat();
var Exports_js_3 = require_Exports3();
var DialogServiceTurnStateManager_js_1 = require_DialogServiceTurnStateManager();
var Exports_js_4 = require_Exports7();
var ActivityResponsePayload_js_1 = require_ActivityResponsePayload();
var InvocationSource_js_1 = require_InvocationSource();
var KeywordDetection_js_1 = require_KeywordDetection();
var SpeechConnectionMessage_Internal_js_1 = require_SpeechConnectionMessage_Internal();
var DialogServiceAdapter = class extends Exports_js_4.ServiceRecognizerBase {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, dialogServiceConnector) {
super(authentication, connectionFactory, audioSource, recognizerConfig, dialogServiceConnector);
this.privEvents = new Exports_js_2.EventSource();
this.privDialogServiceConnector = dialogServiceConnector;
this.receiveMessageOverride = () => this.receiveDialogMessageOverride();
this.privTurnStateManager = new DialogServiceTurnStateManager_js_1.DialogServiceTurnStateManager();
this.recognizeOverride = (recoMode, successCallback, errorCallback) => this.listenOnce(recoMode, successCallback, errorCallback);
this.postConnectImplOverride = (connection) => this.dialogConnectImpl(connection);
this.configConnectionOverride = (connection) => this.configConnection(connection);
this.disconnectOverride = () => this.privDisconnect();
this.privDialogAudioSource = audioSource;
this.agentConfigSent = false;
this.privLastResult = null;
this.connectionEvents.attach((connectionEvent) => {
if (connectionEvent.name === "ConnectionClosedEvent") {
this.terminateMessageLoop = true;
}
});
}
async sendMessage(message) {
const interactionGuid = (0, Exports_js_2.createGuid)();
const requestId = (0, Exports_js_2.createNoDashGuid)();
const agentMessage = {
context: {
interactionId: interactionGuid
},
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
messagePayload: JSON.parse(message),
version: 0.5
};
const agentMessageJson = JSON.stringify(agentMessage);
const connection = await this.fetchConnection();
await connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "agent", requestId, "application/json", agentMessageJson));
}
async privDisconnect() {
await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.NoError, "Disconnecting");
this.terminateMessageLoop = true;
this.agentConfigSent = false;
return;
}
processTypeSpecificMessages(connectionMessage) {
const resultProps = new Exports_js_3.PropertyCollection();
if (connectionMessage.messageType === Exports_js_2.MessageType.Text) {
resultProps.setProperty(Exports_js_3.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
}
let result;
let processed;
switch (connectionMessage.path.toLowerCase()) {
case "speech.phrase":
const speechPhrase = Exports_js_4.SimpleSpeechPhrase.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
this.privRequestSession.onPhraseRecognized(speechPhrase.Offset + speechPhrase.Duration);
if (speechPhrase.RecognitionStatus !== Exports_js_4.RecognitionStatus.TooManyRequests && speechPhrase.RecognitionStatus !== Exports_js_4.RecognitionStatus.Error) {
const args = this.fireEventForResult(speechPhrase, resultProps);
this.privLastResult = args.result;
if (!!this.privDialogServiceConnector.recognized) {
try {
this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, args);
} catch (error) {
}
}
}
processed = true;
break;
case "speech.hypothesis":
const hypothesis = Exports_js_4.SpeechHypothesis.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
result = new Exports_js_3.SpeechRecognitionResult(this.privRequestSession.requestId, Exports_js_3.ResultReason.RecognizingSpeech, hypothesis.Text, hypothesis.Duration, hypothesis.Offset, hypothesis.Language, hypothesis.LanguageDetectionConfidence, void 0, void 0, hypothesis.asJson(), resultProps);
this.privRequestSession.onHypothesis(hypothesis.Offset);
const ev = new Exports_js_3.SpeechRecognitionEventArgs(result, hypothesis.Offset, this.privRequestSession.sessionId);
if (!!this.privDialogServiceConnector.recognizing) {
try {
this.privDialogServiceConnector.recognizing(this.privDialogServiceConnector, ev);
} catch (error) {
}
}
processed = true;
break;
case "speech.keyword":
const keyword = Exports_js_4.SpeechKeyword.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
result = new Exports_js_3.SpeechRecognitionResult(this.privRequestSession.requestId, keyword.Status === "Accepted" ? Exports_js_3.ResultReason.RecognizedKeyword : Exports_js_3.ResultReason.NoMatch, keyword.Text, keyword.Duration, keyword.Offset, void 0, void 0, void 0, void 0, keyword.asJson(), resultProps);
if (keyword.Status !== "Accepted") {
this.privLastResult = result;
}
const event = new Exports_js_3.SpeechRecognitionEventArgs(result, result.duration, result.resultId);
if (!!this.privDialogServiceConnector.recognized) {
try {
this.privDialogServiceConnector.recognized(this.privDialogServiceConnector, event);
} catch (error) {
}
}
processed = true;
break;
case "audio":
{
const audioRequestId = connectionMessage.requestId.toUpperCase();
const turn = this.privTurnStateManager.GetTurn(audioRequestId);
try {
if (!connectionMessage.binaryBody) {
turn.endAudioStream();
} else {
turn.audioStream.write(connectionMessage.binaryBody);
}
} catch (error) {
}
}
processed = true;
break;
case "response":
{
this.handleResponseMessage(connectionMessage);
}
processed = true;
break;
default:
break;
}
const defferal = new Exports_js_2.Deferred();
defferal.resolve(processed);
return defferal.promise;
}
// Cancels recognition.
async cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
this.terminateMessageLoop = true;
if (!!this.privRequestSession.isRecognizing) {
await this.privRequestSession.onStopRecognizing();
}
if (!!this.privDialogServiceConnector.canceled) {
const properties = new Exports_js_3.PropertyCollection();
properties.setProperty(Exports_js_4.CancellationErrorCodePropertyName, Exports_js_3.CancellationErrorCode[errorCode]);
const cancelEvent = new Exports_js_3.SpeechRecognitionCanceledEventArgs(cancellationReason, error, errorCode, void 0, sessionId);
try {
this.privDialogServiceConnector.canceled(this.privDialogServiceConnector, cancelEvent);
} catch {
}
if (!!this.privSuccessCallback) {
const result = new Exports_js_3.SpeechRecognitionResult(
void 0,
// ResultId
Exports_js_3.ResultReason.Canceled,
void 0,
// Text
void 0,
// Duration
void 0,
// Offset
void 0,
// Language
void 0,
// Language Detection Confidence
void 0,
// Speaker Id
error,
void 0,
// Json
properties
);
try {
this.privSuccessCallback(result);
this.privSuccessCallback = void 0;
} catch {
}
}
}
}
async listenOnce(recoMode, successCallback, errorCallback) {
this.privRecognizerConfig.recognitionMode = recoMode;
this.privSuccessCallback = successCallback;
this.privErrorCallback = errorCallback;
this.privRequestSession.startNewRecognition();
this.privRequestSession.listenForServiceTelemetry(this.privDialogAudioSource.events);
this.privRecognizerConfig.parameters.setProperty(Exports_js_3.PropertyId.Speech_SessionId, this.privRequestSession.sessionId);
const conPromise = this.connectImpl();
const preAudioPromise = this.sendPreAudioMessages();
const node = await this.privDialogAudioSource.attach(this.privRequestSession.audioNodeId);
const format2 = await this.privDialogAudioSource.format;
const deviceInfo = await this.privDialogAudioSource.deviceInfo;
const audioNode = new Exports_js_1.ReplayableAudioNode(node, format2.avgBytesPerSec);
await this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false);
this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo };
try {
await conPromise;
await preAudioPromise;
} catch (error) {
await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.ConnectionFailure, error);
return Promise.resolve();
}
const sessionStartEventArgs = new Exports_js_3.SessionEventArgs(this.privRequestSession.sessionId);
if (!!this.privRecognizer.sessionStarted) {
this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs);
}
const audioSendPromise = this.sendAudio(audioNode);
audioSendPromise.then(() => {
}, async (error) => {
await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.RuntimeError, error);
});
}
// Establishes a websocket connection to the end point.
dialogConnectImpl(connection) {
this.privConnectionLoop = this.startMessageLoop();
return connection;
}
receiveDialogMessageOverride() {
const communicationCustodian = new Exports_js_2.Deferred();
const loop = async () => {
try {
const isDisposed = this.isDisposed();
const terminateMessageLoop = !this.isDisposed() && this.terminateMessageLoop;
if (isDisposed || terminateMessageLoop) {
communicationCustodian.resolve(void 0);
return;
}
const connection = await this.fetchConnection();
const message = await connection.read();
if (!message) {
return loop();
}
const connectionMessage = SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage.fromConnectionMessage(message);
switch (connectionMessage.path.toLowerCase()) {
case "turn.start":
{
const turnRequestId = connectionMessage.requestId.toUpperCase();
const audioSessionReqId = this.privRequestSession.requestId.toUpperCase();
if (turnRequestId !== audioSessionReqId) {
this.privTurnStateManager.StartTurn(turnRequestId);
} else {
this.privRequestSession.onServiceTurnStartResponse();
}
}
break;
case "speech.startdetected":
const speechStartDetected = Exports_js_4.SpeechDetected.fromJSON(connectionMessage.textBody, this.privRequestSession.currentTurnAudioOffset);
const speechStartEventArgs = new Exports_js_3.RecognitionEventArgs(speechStartDetected.Offset, this.privRequestSession.sessionId);
if (!!this.privRecognizer.speechStartDetected) {
this.privRecognizer.speechStartDetected(this.privRecognizer, speechStartEventArgs);
}
break;
case "speech.enddetected":
let json;
if (connectionMessage.textBody.length > 0) {
json = connectionMessage.textBody;
} else {
json = "{ Offset: 0 }";
}
const speechStopDetected = Exports_js_4.SpeechDetected.fromJSON(json, this.privRequestSession.currentTurnAudioOffset);
this.privRequestSession.onServiceRecognized(speechStopDetected.Offset);
const speechStopEventArgs = new Exports_js_3.RecognitionEventArgs(speechStopDetected.Offset, this.privRequestSession.sessionId);
if (!!this.privRecognizer.speechEndDetected) {
this.privRecognizer.speechEndDetected(this.privRecognizer, speechStopEventArgs);
}
break;
case "turn.end":
{
const turnEndRequestId = connectionMessage.requestId.toUpperCase();
const audioSessionReqId = this.privRequestSession.requestId.toUpperCase();
if (turnEndRequestId !== audioSessionReqId) {
this.privTurnStateManager.CompleteTurn(turnEndRequestId);
} else {
const sessionStopEventArgs = new Exports_js_3.SessionEventArgs(this.privRequestSession.sessionId);
await this.privRequestSession.onServiceTurnEndResponse(false);
if (!this.privRecognizerConfig.isContinuousRecognition || this.privRequestSession.isSpeechEnded || !this.privRequestSession.isRecognizing) {
if (!!this.privRecognizer.sessionStopped) {
this.privRecognizer.sessionStopped(this.privRecognizer, sessionStopEventArgs);
}
}
if (!!this.privSuccessCallback && this.privLastResult) {
try {
this.privSuccessCallback(this.privLastResult);
this.privLastResult = null;
} catch (e) {
if (!!this.privErrorCallback) {
this.privErrorCallback(e);
}
}
this.privSuccessCallback = void 0;
this.privErrorCallback = void 0;
}
}
}
break;
default:
try {
const processed = await this.processTypeSpecificMessages(connectionMessage);
if (!processed) {
if (!!this.serviceEvents) {
this.serviceEvents.onEvent(new Exports_js_2.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));
}
}
} catch (e) {
}
}
const ret = loop();
return ret;
} catch (error) {
this.terminateMessageLoop = true;
communicationCustodian.resolve();
}
};
loop().catch((reason) => {
Exports_js_2.Events.instance.onEvent(new Exports_js_2.BackgroundEvent(reason));
});
return communicationCustodian.promise;
}
async startMessageLoop() {
this.terminateMessageLoop = false;
try {
await this.receiveDialogMessageOverride();
} catch (error) {
await this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.RuntimeError, error);
}
return Promise.resolve();
}
// Takes an established websocket connection to the endpoint and sends speech configuration information.
async configConnection(connection) {
if (this.terminateMessageLoop) {
this.terminateMessageLoop = false;
return Promise.reject("Connection to service terminated.");
}
await this.sendSpeechServiceConfig(connection, this.privRequestSession, this.privRecognizerConfig.SpeechServiceConfig.serialize());
await this.sendAgentConfig(connection);
return connection;
}
async sendPreAudioMessages() {
const connection = await this.fetchConnection();
this.addKeywordContextData();
await this.sendSpeechContext(connection, true);
await this.sendAgentContext(connection);
await this.sendWaveHeader(connection);
}
sendAgentConfig(connection) {
if (this.agentConfig && !this.agentConfigSent) {
if (this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.Conversation_DialogType) === Exports_js_3.DialogServiceConfig.DialogTypes.CustomCommands) {
const config = this.agentConfig.get();
config.botInfo.commandsCulture = this.privRecognizerConfig.parameters.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_RecoLanguage, "en-us");
this.agentConfig.set(config);
}
this.onEvent(new DialogEvents_js_1.SendingAgentContextMessageEvent(this.agentConfig));
const agentConfigJson = this.agentConfig.toJsonString();
this.agentConfigSent = true;
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "agent.config", this.privRequestSession.requestId, "application/json", agentConfigJson));
}
return;
}
sendAgentContext(connection) {
const guid = (0, Exports_js_2.createGuid)();
const speechActivityTemplate = this.privDialogServiceConnector.properties.getProperty(Exports_js_3.PropertyId.Conversation_Speech_Activity_Template);
const agentContext = {
channelData: "",
context: {
interactionId: guid
},
messagePayload: typeof speechActivityTemplate === void 0 ? void 0 : speechActivityTemplate,
version: 0.5
};
const agentContextJson = JSON.stringify(agentContext);
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "speech.agent.context", this.privRequestSession.requestId, "application/json", agentContextJson));
}
fireEventForResult(serviceResult, properties) {
const resultReason = Exports_js_4.EnumTranslation.implTranslateRecognitionResult(serviceResult.RecognitionStatus);
const result = new Exports_js_3.SpeechRecognitionResult(this.privRequestSession.requestId, resultReason, serviceResult.DisplayText, serviceResult.Duration, serviceResult.Offset, serviceResult.Language, serviceResult.LanguageDetectionConfidence, void 0, void 0, serviceResult.asJson(), properties);
const ev = new Exports_js_3.SpeechRecognitionEventArgs(result, serviceResult.Offset, this.privRequestSession.sessionId);
return ev;
}
handleResponseMessage(responseMessage) {
const responsePayload = JSON.parse(responseMessage.textBody);
switch (responsePayload.messageType.toLowerCase()) {
case "message":
const responseRequestId = responseMessage.requestId.toUpperCase();
const activityPayload = ActivityResponsePayload_js_1.ActivityPayloadResponse.fromJSON(responseMessage.textBody);
const turn = this.privTurnStateManager.GetTurn(responseRequestId);
if (activityPayload.conversationId) {
const updateAgentConfig = this.agentConfig.get();
updateAgentConfig.botInfo.conversationId = activityPayload.conversationId;
this.agentConfig.set(updateAgentConfig);
}
const pullAudioOutputStream = turn.processActivityPayload(activityPayload, AudioOutputFormat_js_1.AudioOutputFormatImpl.fromSpeechSynthesisOutputFormatString(this.privDialogServiceConnector.properties.getProperty(Exports_js_3.PropertyId.SpeechServiceConnection_SynthOutputFormat, void 0)));
const activity = new Exports_js_3.ActivityReceivedEventArgs(activityPayload.messagePayload, pullAudioOutputStream);
if (!!this.privDialogServiceConnector.activityReceived) {
try {
this.privDialogServiceConnector.activityReceived(this.privDialogServiceConnector, activity);
} catch (error) {
}
}
break;
case "messagestatus":
if (!!this.privDialogServiceConnector.turnStatusReceived) {
try {
this.privDialogServiceConnector.turnStatusReceived(this.privDialogServiceConnector, new Exports_js_3.TurnStatusReceivedEventArgs(responseMessage.textBody));
} catch (error) {
}
}
break;
default:
Exports_js_2.Events.instance.onEvent(new Exports_js_2.BackgroundEvent(`Unexpected response of type ${responsePayload.messageType}. Ignoring.`));
break;
}
}
onEvent(event) {
this.privEvents.onEvent(event);
Exports_js_2.Events.instance.onEvent(event);
}
addKeywordContextData() {
const keywordPropertyValue = this.privRecognizerConfig.parameters.getProperty("SPEECH-KeywordsToDetect");
if (keywordPropertyValue === void 0) {
return;
}
const keywordOffsetPropertyValue = this.privRecognizerConfig.parameters.getProperty("SPEECH-KeywordsToDetect-Offsets");
const keywordDurationPropertyValue = this.privRecognizerConfig.parameters.getProperty("SPEECH-KeywordsToDetect-Durations");
const keywords = keywordPropertyValue.split(";");
const keywordOffsets = keywordOffsetPropertyValue === void 0 ? [] : keywordOffsetPropertyValue.split(";");
const keywordDurations = keywordDurationPropertyValue === void 0 ? [] : keywordDurationPropertyValue.split(";");
const keywordDefinitionArray = [];
for (let i = 0; i < keywords.length; i++) {
const definition = {
text: keywords[i]
};
if (i < keywordOffsets.length) {
definition.startOffset = Number(keywordOffsets[i]);
}
if (i < keywordDurations.length) {
definition.duration = Number(keywordDurations[i]);
}
keywordDefinitionArray.push(definition);
}
this.speechContext.getContext().invocationSource = InvocationSource_js_1.InvocationSource.VoiceActivationWithKeyword;
this.speechContext.getContext().keywordDetection = [{
clientDetectedKeywords: keywordDefinitionArray,
onReject: { action: KeywordDetection_js_1.OnRejectAction.EndOfTurn },
type: KeywordDetection_js_1.KeywordDetectionType.StartTrigger
}];
}
};
exports.DialogServiceAdapter = DialogServiceAdapter;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/AgentConfig.js
var require_AgentConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/AgentConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentConfig = void 0;
var AgentConfig = class {
toJsonString() {
return JSON.stringify(this.iPrivConfig);
}
get() {
return this.iPrivConfig;
}
/**
* Setter for the agent.config object.
* @param value a JSON serializable object.
*/
set(value) {
this.iPrivConfig = value;
}
};
exports.AgentConfig = AgentConfig;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationConnectionConfig.js
var require_ConversationConnectionConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationConnectionConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationConnectionConfig = void 0;
var RestConfigBase_js_1 = require_RestConfigBase();
var ConversationConnectionConfig = class _ConversationConnectionConfig extends RestConfigBase_js_1.RestConfigBase {
static get host() {
return _ConversationConnectionConfig.privHost;
}
static get apiVersion() {
return _ConversationConnectionConfig.privApiVersion;
}
static get clientAppId() {
return _ConversationConnectionConfig.privClientAppId;
}
static get defaultLanguageCode() {
return _ConversationConnectionConfig.privDefaultLanguageCode;
}
static get restPath() {
return _ConversationConnectionConfig.privRestPath;
}
static get webSocketPath() {
return _ConversationConnectionConfig.privWebSocketPath;
}
static get transcriptionEventKeys() {
return _ConversationConnectionConfig.privTranscriptionEventKeys;
}
};
exports.ConversationConnectionConfig = ConversationConnectionConfig;
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.privTranscriptionEventKeys = ["iCalUid", "callId", "organizer", "FLAC", "MTUri", "DifferentiateGuestSpeakers", "audiorecording", "Threadid", "OrganizerMri", "OrganizerTenantId", "UserToken"];
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationManager.js
var require_ConversationManager = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationManager.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationManager = void 0;
var Exports_js_1 = require_Exports4();
var Contracts_js_1 = require_Contracts();
var Exports_js_2 = require_Exports3();
var ConversationConnectionConfig_js_1 = require_ConversationConnectionConfig();
var ConversationManager = class {
constructor() {
this.privRequestParams = ConversationConnectionConfig_js_1.ConversationConnectionConfig.configParams;
this.privErrors = ConversationConnectionConfig_js_1.ConversationConnectionConfig.restErrors;
this.privHost = ConversationConnectionConfig_js_1.ConversationConnectionConfig.host;
this.privApiVersion = ConversationConnectionConfig_js_1.ConversationConnectionConfig.apiVersion;
this.privRestPath = ConversationConnectionConfig_js_1.ConversationConnectionConfig.restPath;
this.privRestAdapter = new Exports_js_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
*/
createOrJoin(args, conversationCode, cb, err) {
try {
Contracts_js_1.Contracts.throwIfNullOrUndefined(args, "args");
const languageCode = args.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage, ConversationConnectionConfig_js_1.ConversationConnectionConfig.defaultLanguageCode);
const nickname = args.getProperty(Exports_js_2.PropertyId.ConversationTranslator_Name, "conversation_host");
const endpointHost = args.getProperty(Exports_js_2.PropertyId.ConversationTranslator_Host, this.privHost);
const correlationId = args.getProperty(Exports_js_2.PropertyId.ConversationTranslator_CorrelationId);
const subscriptionKey = args.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Key);
const subscriptionRegion = args.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region);
const authToken = args.getProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token);
Contracts_js_1.Contracts.throwIfNullOrWhitespace(languageCode, "languageCode");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(nickname, "nickname");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(endpointHost, "endpointHost");
const queryParams = {};
queryParams[this.privRequestParams.apiVersion] = this.privApiVersion;
queryParams[this.privRequestParams.languageCode] = languageCode;
queryParams[this.privRequestParams.nickname] = nickname;
const headers = {};
if (correlationId) {
headers[this.privRequestParams.correlationId] = correlationId;
}
headers[this.privRequestParams.clientAppId] = ConversationConnectionConfig_js_1.ConversationConnectionConfig.clientAppId;
if (conversationCode !== void 0) {
queryParams[this.privRequestParams.roomId] = conversationCode;
} else {
Contracts_js_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_js_1.Contracts.throwIfNullOrUndefined(subscriptionKey, this.privErrors.authInvalidSubscriptionKey);
}
}
const config = {};
config.headers = headers;
this.privRestAdapter.options = config;
const endpoint = `https://${endpointHost}${this.privRestPath}`;
this.privRestAdapter.request(Exports_js_1.RestRequestType.Post, endpoint, queryParams, null).then((response) => {
const requestId = Exports_js_1.RestMessageAdapter.extractHeaderValue(this.privRequestParams.requestId, response.headers);
if (!response.ok) {
if (!!err) {
let errorMessage = this.privErrors.invalidCreateJoinConversationResponse.replace("{status}", response.status.toString());
let errMessageRaw;
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;
}
const conversation = JSON.parse(response.data);
if (conversation) {
conversation.requestId = requestId;
}
if (!!cb) {
try {
cb(conversation);
} catch (e) {
if (!!err) {
err(e);
}
}
cb = void 0;
}
}).catch(() => {
});
} catch (error) {
if (!!err) {
if (error instanceof Error) {
const 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
*/
leave(args, sessionToken) {
return new Promise((resolve, reject) => {
try {
Contracts_js_1.Contracts.throwIfNullOrUndefined(args, this.privErrors.invalidArgs.replace("{arg}", "config"));
Contracts_js_1.Contracts.throwIfNullOrWhitespace(sessionToken, this.privErrors.invalidArgs.replace("{arg}", "token"));
const endpointHost = args.getProperty(Exports_js_2.PropertyId.ConversationTranslator_Host, this.privHost);
const correlationId = args.getProperty(Exports_js_2.PropertyId.ConversationTranslator_CorrelationId);
const queryParams = {};
queryParams[this.privRequestParams.apiVersion] = this.privApiVersion;
queryParams[this.privRequestParams.sessionToken] = sessionToken;
const headers = {};
if (correlationId) {
headers[this.privRequestParams.correlationId] = correlationId;
}
const config = {};
config.headers = headers;
this.privRestAdapter.options = config;
const endpoint = `https://${endpointHost}${this.privRestPath}`;
this.privRestAdapter.request(Exports_js_1.RestRequestType.Delete, endpoint, queryParams, null).then((response) => {
if (!response.ok) {
}
resolve();
}).catch(() => {
});
} catch (error) {
if (error instanceof Error) {
const typedError = error;
reject(typedError.name + ": " + typedError.message);
} else {
reject(error);
}
}
});
}
};
exports.ConversationManager = ConversationManager;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationConnectionMessage.js
var require_ConversationConnectionMessage = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationConnectionMessage.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationConnectionMessage = void 0;
var Exports_js_1 = require_Exports();
var ConversationConnectionMessage = class extends Exports_js_1.ConnectionMessage {
constructor(messageType, body, headers, id) {
super(messageType, body, headers, id);
const json = JSON.parse(this.textBody);
if (json.type !== void 0) {
this.privConversationMessageType = json.type;
}
}
get conversationMessageType() {
return this.privConversationMessageType;
}
};
exports.ConversationConnectionMessage = ConversationConnectionMessage;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationWebsocketMessageFormatter.js
var require_ConversationWebsocketMessageFormatter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationWebsocketMessageFormatter.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationWebsocketMessageFormatter = void 0;
var Exports_js_1 = require_Exports();
var ConversationConnectionMessage_js_1 = require_ConversationConnectionMessage();
var ConversationWebsocketMessageFormatter = class {
/**
* Format incoming messages: text (speech partial/final, IM) or binary (tts)
*/
toConnectionMessage(message) {
const deferral = new Exports_js_1.Deferred();
try {
if (message.messageType === Exports_js_1.MessageType.Text) {
const incomingMessage = new ConversationConnectionMessage_js_1.ConversationConnectionMessage(message.messageType, message.textContent, {}, message.id);
deferral.resolve(incomingMessage);
} else if (message.messageType === Exports_js_1.MessageType.Binary) {
deferral.resolve(new ConversationConnectionMessage_js_1.ConversationConnectionMessage(message.messageType, message.binaryContent, void 0, message.id));
}
} catch (e) {
deferral.reject(`Error formatting the message. Error: ${e}`);
}
return deferral.promise;
}
/**
* Format outgoing messages: text (commands or IM)
*/
fromConnectionMessage(message) {
const deferral = new Exports_js_1.Deferred();
try {
if (message.messageType === Exports_js_1.MessageType.Text) {
const payload = `${message.textBody ? message.textBody : ""}`;
deferral.resolve(new Exports_js_1.RawWebsocketMessage(Exports_js_1.MessageType.Text, payload, message.id));
}
} catch (e) {
deferral.reject(`Error formatting the message. ${e}`);
}
return deferral.promise;
}
};
exports.ConversationWebsocketMessageFormatter = ConversationWebsocketMessageFormatter;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationConnectionFactory.js
var require_ConversationConnectionFactory = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationConnectionFactory.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationConnectionFactory = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var ConversationConnectionConfig_js_1 = require_ConversationConnectionConfig();
var ConversationWebsocketMessageFormatter_js_1 = require_ConversationWebsocketMessageFormatter();
var ConversationConnectionFactory = class extends ConnectionFactoryBase_js_1.ConnectionFactoryBase {
create(config, authInfo, connectionId) {
const endpointHost = config.parameters.getProperty(Exports_js_3.PropertyId.ConversationTranslator_Host, ConversationConnectionConfig_js_1.ConversationConnectionConfig.host);
const correlationId = config.parameters.getProperty(Exports_js_3.PropertyId.ConversationTranslator_CorrelationId, (0, Exports_js_2.createGuid)());
const endpoint = `wss://${endpointHost}${ConversationConnectionConfig_js_1.ConversationConnectionConfig.webSocketPath}`;
const token = config.parameters.getProperty(Exports_js_3.PropertyId.ConversationTranslator_Token, void 0);
Contracts_js_1.Contracts.throwIfNullOrUndefined(token, "token");
const queryParams = {};
queryParams[ConversationConnectionConfig_js_1.ConversationConnectionConfig.configParams.apiVersion] = ConversationConnectionConfig_js_1.ConversationConnectionConfig.apiVersion;
queryParams[ConversationConnectionConfig_js_1.ConversationConnectionConfig.configParams.token] = token;
queryParams[ConversationConnectionConfig_js_1.ConversationConnectionConfig.configParams.correlationId] = correlationId;
const enableCompression = config.parameters.getProperty("SPEECH-EnableWebsocketCompression", "false") === "true";
return Promise.resolve(new Exports_js_1.WebsocketConnection(endpoint, queryParams, {}, new ConversationWebsocketMessageFormatter_js_1.ConversationWebsocketMessageFormatter(), Exports_js_1.ProxyInfo.fromRecognizerConfig(config), enableCompression, connectionId));
}
};
exports.ConversationConnectionFactory = ConversationConnectionFactory;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationRequestSession.js
var require_ConversationRequestSession = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationRequestSession.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationRequestSession = void 0;
var Exports_js_1 = require_Exports();
var ConversationRequestSession = class {
constructor(sessionId) {
this.privIsDisposed = false;
this.privDetachables = new Array();
this.privSessionId = sessionId;
this.privRequestId = (0, Exports_js_1.createNoDashGuid)();
this.privRequestCompletionDeferral = new Exports_js_1.Deferred();
}
get sessionId() {
return this.privSessionId;
}
get requestId() {
return this.privRequestId;
}
get completionPromise() {
return this.privRequestCompletionDeferral.promise;
}
onPreConnectionStart(authFetchEventId, connectionId) {
this.privSessionId = connectionId;
}
onAuthCompleted(isError) {
if (isError) {
this.onComplete();
}
}
onConnectionEstablishCompleted(statusCode) {
if (statusCode === 200) {
return;
} else if (statusCode === 403) {
this.onComplete();
}
}
onServiceTurnEndResponse(continuousRecognition) {
if (!continuousRecognition) {
this.onComplete();
} else {
this.privRequestId = (0, Exports_js_1.createNoDashGuid)();
}
}
async dispose() {
if (!this.privIsDisposed) {
this.privIsDisposed = true;
for (const detachable of this.privDetachables) {
await detachable.detach();
}
}
}
onComplete() {
}
};
exports.ConversationRequestSession = ConversationRequestSession;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationTranslatorEventArgs.js
var require_ConversationTranslatorEventArgs = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationTranslatorEventArgs.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationReceivedTranslationEventArgs = exports.ParticipantsListEventArgs = exports.ParticipantAttributeEventArgs = exports.ParticipantEventArgs = exports.LockRoomEventArgs = exports.MuteAllEventArgs = void 0;
var Exports_js_1 = require_Exports3();
var MuteAllEventArgs = class extends Exports_js_1.SessionEventArgs {
constructor(isMuted, sessionId) {
super(sessionId);
this.privIsMuted = isMuted;
}
get isMuted() {
return this.privIsMuted;
}
};
exports.MuteAllEventArgs = MuteAllEventArgs;
var LockRoomEventArgs = class extends Exports_js_1.SessionEventArgs {
constructor(isLocked, sessionId) {
super(sessionId);
this.privIsLocked = isLocked;
}
get isMuted() {
return this.privIsLocked;
}
};
exports.LockRoomEventArgs = LockRoomEventArgs;
var ParticipantEventArgs = class extends Exports_js_1.SessionEventArgs {
constructor(participant, sessionId) {
super(sessionId);
this.privParticipant = participant;
}
get participant() {
return this.privParticipant;
}
};
exports.ParticipantEventArgs = ParticipantEventArgs;
var ParticipantAttributeEventArgs = class extends Exports_js_1.SessionEventArgs {
constructor(participantId, key, value, sessionId) {
super(sessionId);
this.privKey = key;
this.privValue = value;
this.privParticipantId = participantId;
}
get value() {
return this.privValue;
}
get key() {
return this.privKey;
}
get id() {
return this.privParticipantId;
}
};
exports.ParticipantAttributeEventArgs = ParticipantAttributeEventArgs;
var ParticipantsListEventArgs = class extends Exports_js_1.SessionEventArgs {
constructor(conversationId, token, translateTo, profanityFilter, roomProfanityFilter, isRoomLocked, isMuteAll, participants, sessionId) {
super(sessionId);
this.privRoomId = conversationId;
this.privSessionToken = token;
this.privTranslateTo = translateTo;
this.privProfanityFilter = profanityFilter;
this.privRoomProfanityFilter = roomProfanityFilter;
this.privIsRoomLocked = isRoomLocked;
this.privIsRoomLocked = isMuteAll;
this.privParticipants = participants;
}
get sessionToken() {
return this.privSessionToken;
}
get conversationId() {
return this.privRoomId;
}
get translateTo() {
return this.privTranslateTo;
}
get profanityFilter() {
return this.privProfanityFilter;
}
get roomProfanityFilter() {
return this.privRoomProfanityFilter;
}
get isRoomLocked() {
return this.privIsRoomLocked;
}
get isMuteAll() {
return this.privIsMuteAll;
}
get participants() {
return this.privParticipants;
}
};
exports.ParticipantsListEventArgs = ParticipantsListEventArgs;
var ConversationReceivedTranslationEventArgs = class {
constructor(command, payload, sessionId) {
this.privPayload = payload;
this.privCommand = command;
this.privSessionId = sessionId;
}
get payload() {
return this.privPayload;
}
get command() {
return this.privCommand;
}
get sessionId() {
return this.privSessionId;
}
};
exports.ConversationReceivedTranslationEventArgs = ConversationReceivedTranslationEventArgs;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationTranslatorInterfaces.js
var require_ConversationTranslatorInterfaces = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationTranslatorInterfaces.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslatorCommandTypes = exports.ConversationTranslatorMessageTypes = exports.InternalParticipants = void 0;
var InternalParticipants = class {
constructor(participants = [], meId) {
this.participants = participants;
this.meId = meId;
}
/**
* Add or update a participant
* @param value
*/
addOrUpdateParticipant(value) {
if (value === void 0) {
return;
}
const exists = this.getParticipantIndex(value.id);
if (exists > -1) {
this.participants.splice(exists, 1, value);
} else {
this.participants.push(value);
}
return this.getParticipant(value.id);
}
/**
* Find the participant's position in the participants list.
* @param id
*/
getParticipantIndex(id) {
return this.participants.findIndex((p) => p.id === id);
}
/**
* Find the participant by id.
* @param id
*/
getParticipant(id) {
return this.participants.find((p) => p.id === id);
}
/**
* Remove a participant from the participants list.
*/
deleteParticipant(id) {
this.participants = this.participants.filter((p) => p.id !== id);
}
/**
* Helper to return the conversation host.
*/
get host() {
return this.participants.find((p) => p.isHost === true);
}
/**
* Helper to return the current user.
*/
get me() {
return this.getParticipant(this.meId);
}
};
exports.InternalParticipants = InternalParticipants;
exports.ConversationTranslatorMessageTypes = {
command: "command",
final: "final",
info: "info",
instantMessage: "instant_message",
keepAlive: "keep_alive",
partial: "partial",
participantCommand: "participant_command",
translatedMessage: "translated_message"
};
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"
};
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/CommandResponsePayload.js
var require_CommandResponsePayload = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/CommandResponsePayload.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandResponsePayload = void 0;
var parseCommandResponse = (json) => JSON.parse(json);
var CommandResponsePayload = class _CommandResponsePayload {
constructor(json) {
this.privCommandResponse = parseCommandResponse(json);
}
get type() {
return this.privCommandResponse.type;
}
get command() {
return this.privCommandResponse.command;
}
get id() {
return this.privCommandResponse.id;
}
get nickname() {
return this.privCommandResponse.nickname;
}
get participantId() {
return this.privCommandResponse.participantId;
}
get roomid() {
return this.privCommandResponse.roomid;
}
get value() {
return this.privCommandResponse.value;
}
get token() {
return this.privCommandResponse.token;
}
static fromJSON(json) {
return new _CommandResponsePayload(json);
}
};
exports.CommandResponsePayload = CommandResponsePayload;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/ParticipantResponsePayload.js
var require_ParticipantResponsePayload = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/ParticipantResponsePayload.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParticipantPayloadResponse = exports.ParticipantsListPayloadResponse = void 0;
var parseListResponse = (json) => JSON.parse(json);
var parseParticipantResponse = (json) => JSON.parse(json);
var ParticipantsListPayloadResponse = class _ParticipantsListPayloadResponse {
constructor(json) {
this.privParticipantsPayloadResponse = parseListResponse(json);
}
get roomid() {
return this.privParticipantsPayloadResponse.roomid;
}
get id() {
return this.privParticipantsPayloadResponse.id;
}
get command() {
return this.privParticipantsPayloadResponse.command;
}
get participants() {
return this.privParticipantsPayloadResponse.participants;
}
get token() {
return this.privParticipantsPayloadResponse.token;
}
get translateTo() {
return this.privParticipantsPayloadResponse.translateTo;
}
get profanityFilter() {
return this.privParticipantsPayloadResponse.profanityFilter;
}
get roomProfanityFilter() {
return this.privParticipantsPayloadResponse.roomProfanityFilter;
}
get roomLocked() {
return this.privParticipantsPayloadResponse.roomLocked;
}
get muteAll() {
return this.privParticipantsPayloadResponse.muteAll;
}
get type() {
return this.privParticipantsPayloadResponse.type;
}
static fromJSON(json) {
return new _ParticipantsListPayloadResponse(json);
}
};
exports.ParticipantsListPayloadResponse = ParticipantsListPayloadResponse;
var ParticipantPayloadResponse = class _ParticipantPayloadResponse {
constructor(json) {
this.privParticipantPayloadResponse = parseParticipantResponse(json);
}
get nickname() {
return this.privParticipantPayloadResponse.nickname;
}
get locale() {
return this.privParticipantPayloadResponse.locale;
}
get usetts() {
return this.privParticipantPayloadResponse.usetts;
}
get ismuted() {
return this.privParticipantPayloadResponse.ismuted;
}
get ishost() {
return this.privParticipantPayloadResponse.ishost;
}
get participantId() {
return this.privParticipantPayloadResponse.participantId;
}
get avatar() {
return this.privParticipantPayloadResponse.avatar;
}
static fromJSON(json) {
return new _ParticipantPayloadResponse(json);
}
};
exports.ParticipantPayloadResponse = ParticipantPayloadResponse;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/TranslationResponsePayload.js
var require_TranslationResponsePayload = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/TranslationResponsePayload.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextResponsePayload = exports.SpeechResponsePayload = void 0;
var parseSpeechResponse = (json) => JSON.parse(json);
var parseTextResponse = (json) => JSON.parse(json);
var SpeechResponsePayload = class _SpeechResponsePayload {
constructor(json) {
this.privSpeechResponse = parseSpeechResponse(json);
}
get recognition() {
return this.privSpeechResponse.recognition;
}
get translations() {
return this.privSpeechResponse.translations;
}
get id() {
return this.privSpeechResponse.id;
}
get language() {
return this.privSpeechResponse.language;
}
get nickname() {
return this.privSpeechResponse.nickname;
}
get participantId() {
return this.privSpeechResponse.participantId;
}
get roomid() {
return this.privSpeechResponse.roomid;
}
get timestamp() {
return this.privSpeechResponse.timestamp;
}
get type() {
return this.privSpeechResponse.type;
}
get isFinal() {
return this.privSpeechResponse.type === "final";
}
static fromJSON(json) {
return new _SpeechResponsePayload(json);
}
};
exports.SpeechResponsePayload = SpeechResponsePayload;
var TextResponsePayload = class _TextResponsePayload {
constructor(json) {
this.privTextResponse = parseTextResponse(json);
}
get originalText() {
return this.privTextResponse.originalText;
}
get translations() {
return this.privTextResponse.translations;
}
get id() {
return this.privTextResponse.id;
}
get language() {
return this.privTextResponse.language;
}
get nickname() {
return this.privTextResponse.nickname;
}
get participantId() {
return this.privTextResponse.participantId;
}
get roomid() {
return this.privTextResponse.roomid;
}
get timestamp() {
return this.privTextResponse.timestamp;
}
get type() {
return this.privTextResponse.type;
}
static fromJSON(json) {
return new _TextResponsePayload(json);
}
};
exports.TextResponsePayload = TextResponsePayload;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/Exports.js
var require_Exports5 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ServiceMessages/Exports.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TextResponsePayload = exports.SpeechResponsePayload = exports.ParticipantPayloadResponse = exports.ParticipantsListPayloadResponse = exports.CommandResponsePayload = void 0;
var CommandResponsePayload_js_1 = require_CommandResponsePayload();
Object.defineProperty(exports, "CommandResponsePayload", { enumerable: true, get: function() {
return CommandResponsePayload_js_1.CommandResponsePayload;
} });
var ParticipantResponsePayload_js_1 = require_ParticipantResponsePayload();
Object.defineProperty(exports, "ParticipantsListPayloadResponse", { enumerable: true, get: function() {
return ParticipantResponsePayload_js_1.ParticipantsListPayloadResponse;
} });
Object.defineProperty(exports, "ParticipantPayloadResponse", { enumerable: true, get: function() {
return ParticipantResponsePayload_js_1.ParticipantPayloadResponse;
} });
var TranslationResponsePayload_js_1 = require_TranslationResponsePayload();
Object.defineProperty(exports, "SpeechResponsePayload", { enumerable: true, get: function() {
return TranslationResponsePayload_js_1.SpeechResponsePayload;
} });
Object.defineProperty(exports, "TextResponsePayload", { enumerable: true, get: function() {
return TranslationResponsePayload_js_1.TextResponsePayload;
} });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationServiceAdapter.js
var require_ConversationServiceAdapter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationServiceAdapter.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationServiceAdapter = void 0;
var Exports_js_1 = require_Exports();
var Exports_js_2 = require_Exports3();
var Exports_js_3 = require_Exports7();
var ConversationConnectionMessage_js_1 = require_ConversationConnectionMessage();
var ConversationRequestSession_js_1 = require_ConversationRequestSession();
var ConversationTranslatorEventArgs_js_1 = require_ConversationTranslatorEventArgs();
var ConversationTranslatorInterfaces_js_1 = require_ConversationTranslatorInterfaces();
var Exports_js_4 = require_Exports5();
var ConversationServiceAdapter = class extends Exports_js_3.ServiceRecognizerBase {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, conversationServiceConnector) {
super(authentication, connectionFactory, audioSource, recognizerConfig, conversationServiceConnector);
this.privConnectionConfigPromise = void 0;
this.privLastPartialUtteranceId = "";
this.privConversationServiceConnector = conversationServiceConnector;
this.privConversationAuthentication = authentication;
this.receiveMessageOverride = () => this.receiveConversationMessageOverride();
this.recognizeOverride = () => this.noOp();
this.postConnectImplOverride = (connection) => this.conversationConnectImpl(connection);
this.configConnectionOverride = () => this.configConnection();
this.disconnectOverride = () => this.privDisconnect();
this.privConversationRequestSession = new ConversationRequestSession_js_1.ConversationRequestSession((0, Exports_js_1.createNoDashGuid)());
this.privConversationConnectionFactory = connectionFactory;
this.privConversationIsDisposed = false;
}
isDisposed() {
return super.isDisposed() || this.privConversationIsDisposed;
}
async dispose(reason) {
this.privConversationIsDisposed = true;
if (this.privConnectionConfigPromise !== void 0) {
const connection = await this.privConnectionConfigPromise;
await connection.dispose(reason);
}
await super.dispose(reason);
}
async sendMessage(message) {
const connection = await this.fetchConnection();
return connection.send(new ConversationConnectionMessage_js_1.ConversationConnectionMessage(Exports_js_1.MessageType.Text, message));
}
async sendMessageAsync(message) {
const connection = await this.fetchConnection();
await connection.send(new ConversationConnectionMessage_js_1.ConversationConnectionMessage(Exports_js_1.MessageType.Text, message));
}
privDisconnect() {
if (this.terminateMessageLoop) {
return;
}
this.cancelRecognition(this.privConversationRequestSession.sessionId, this.privConversationRequestSession.requestId, Exports_js_2.CancellationReason.Error, Exports_js_2.CancellationErrorCode.NoError, "Disconnecting");
this.terminateMessageLoop = true;
return Promise.resolve();
}
// eslint-disable-next-line @typescript-eslint/require-await
async processTypeSpecificMessages() {
return true;
}
// Cancels recognition.
cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
this.terminateMessageLoop = true;
const cancelEvent = new Exports_js_2.ConversationTranslationCanceledEventArgs(cancellationReason, error, errorCode, void 0, sessionId);
try {
if (!!this.privConversationServiceConnector.canceled) {
this.privConversationServiceConnector.canceled(this.privConversationServiceConnector, cancelEvent);
}
} catch {
}
}
/**
* Establishes a websocket connection to the end point.
*/
async conversationConnectImpl(connection) {
this.privConnectionLoop = this.startMessageLoop();
return connection;
}
/**
* Process incoming websocket messages
*/
async receiveConversationMessageOverride() {
if (this.isDisposed() || this.terminateMessageLoop) {
return Promise.resolve();
}
const communicationCustodian = new Exports_js_1.Deferred();
try {
const connection = await this.fetchConnection();
const message = await connection.read();
if (this.isDisposed() || this.terminateMessageLoop) {
communicationCustodian.resolve();
return Promise.resolve();
}
if (!message) {
return this.receiveConversationMessageOverride();
}
const sessionId = this.privConversationRequestSession.sessionId;
const conversationMessageType = message.conversationMessageType.toLowerCase();
let sendFinal = false;
try {
switch (conversationMessageType) {
case "info":
case "participant_command":
case "command":
const commandPayload = Exports_js_4.CommandResponsePayload.fromJSON(message.textBody);
switch (commandPayload.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":
const participantsPayload = Exports_js_4.ParticipantsListPayloadResponse.fromJSON(message.textBody);
const participantsResult = participantsPayload.participants.map((p) => {
const 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_js_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_js_1.ParticipantAttributeEventArgs(commandPayload.participantId, ConversationTranslatorInterfaces_js_1.ConversationTranslatorCommandTypes.setTranslateToLanguages, commandPayload.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_js_1.ParticipantAttributeEventArgs(commandPayload.participantId, ConversationTranslatorInterfaces_js_1.ConversationTranslatorCommandTypes.setProfanityFiltering, commandPayload.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_js_1.ParticipantAttributeEventArgs(commandPayload.participantId, ConversationTranslatorInterfaces_js_1.ConversationTranslatorCommandTypes.setMute, commandPayload.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_js_1.MuteAllEventArgs(commandPayload.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_js_2.ConversationExpirationEventArgs(commandPayload.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_js_1.ParticipantAttributeEventArgs(commandPayload.participantId, ConversationTranslatorInterfaces_js_1.ConversationTranslatorCommandTypes.setUseTTS, commandPayload.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_js_1.LockRoomEventArgs(commandPayload.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_js_1.ParticipantAttributeEventArgs(commandPayload.participantId, ConversationTranslatorInterfaces_js_1.ConversationTranslatorCommandTypes.changeNickname, commandPayload.value, sessionId));
}
break;
/**
* 'JoinSession' is sent when a user joins the Conversation.
*/
case "joinsession":
const joinParticipantPayload = Exports_js_4.ParticipantPayloadResponse.fromJSON(message.textBody);
const 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_js_1.ParticipantEventArgs(joiningParticipant, sessionId));
}
break;
/**
* 'LeaveSession' is sent when a user leaves the Conversation'.
*/
case "leavesession":
const leavingParticipant = {
id: commandPayload.participantId
};
if (!!this.privConversationServiceConnector.participantLeaveCommandReceived) {
this.privConversationServiceConnector.participantLeaveCommandReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_js_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":
const disconnectParticipant = {
id: commandPayload.participantId
};
break;
case "token":
const token = new Exports_js_3.CognitiveTokenAuthentication(() => {
const authorizationToken = commandPayload.token;
return Promise.resolve(authorizationToken);
}, () => {
const authorizationToken = commandPayload.token;
return Promise.resolve(authorizationToken);
});
this.authentication = token;
this.privConversationServiceConnector.onToken(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":
const speechPayload = Exports_js_4.SpeechResponsePayload.fromJSON(message.textBody);
const conversationResultReason = conversationMessageType === "final" ? Exports_js_2.ResultReason.TranslatedParticipantSpeech : Exports_js_2.ResultReason.TranslatingParticipantSpeech;
const speechResult = new Exports_js_2.ConversationTranslationResult(speechPayload.participantId, this.getTranslations(speechPayload.translations), speechPayload.language, speechPayload.id, conversationResultReason, speechPayload.recognition, void 0, void 0, message.textBody, void 0);
if (speechPayload.isFinal) {
if (speechResult.text !== void 0 && speechResult.text.length > 0) {
sendFinal = true;
} else if (speechPayload.id === this.privLastPartialUtteranceId) {
sendFinal = true;
} else {
}
if (sendFinal) {
if (!!this.privConversationServiceConnector.translationReceived) {
this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_js_1.ConversationReceivedTranslationEventArgs(ConversationTranslatorInterfaces_js_1.ConversationTranslatorMessageTypes.final, speechResult, sessionId));
}
}
} else if (speechResult.text !== void 0) {
this.privLastPartialUtteranceId = speechPayload.id;
if (!!this.privConversationServiceConnector.translationReceived) {
this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_js_1.ConversationReceivedTranslationEventArgs(ConversationTranslatorInterfaces_js_1.ConversationTranslatorMessageTypes.partial, speechResult, sessionId));
}
}
break;
/**
* "translated_message" is a text message or instant message (IM).
*/
case "translated_message":
const textPayload = Exports_js_4.TextResponsePayload.fromJSON(message.textBody);
const textResult = new Exports_js_2.ConversationTranslationResult(textPayload.participantId, this.getTranslations(textPayload.translations), textPayload.language, void 0, void 0, textPayload.originalText, void 0, void 0, void 0, message.textBody, void 0);
if (!!this.privConversationServiceConnector.translationReceived) {
this.privConversationServiceConnector.translationReceived(this.privConversationServiceConnector, new ConversationTranslatorEventArgs_js_1.ConversationReceivedTranslationEventArgs(ConversationTranslatorInterfaces_js_1.ConversationTranslatorMessageTypes.instantMessage, textResult, sessionId));
}
break;
default:
break;
}
} catch (e) {
}
return this.receiveConversationMessageOverride();
} catch (e) {
this.terminateMessageLoop = true;
}
return communicationCustodian.promise;
}
async startMessageLoop() {
if (this.isDisposed()) {
return Promise.resolve();
}
this.terminateMessageLoop = false;
const messageRetrievalPromise = this.receiveConversationMessageOverride();
try {
const r = await messageRetrievalPromise;
return r;
} catch (error) {
this.cancelRecognition(this.privRequestSession ? this.privRequestSession.sessionId : "", this.privRequestSession ? this.privRequestSession.requestId : "", Exports_js_2.CancellationReason.Error, Exports_js_2.CancellationErrorCode.RuntimeError, error);
return null;
}
}
// Takes an established websocket connection to the endpoint
configConnection() {
if (this.isDisposed()) {
return Promise.resolve(void 0);
}
if (this.privConnectionConfigPromise !== void 0) {
return this.privConnectionConfigPromise.then((connection) => {
if (connection.state() === Exports_js_1.ConnectionState.Disconnected) {
this.privConnectionId = null;
this.privConnectionConfigPromise = void 0;
return this.configConnection();
}
return this.privConnectionConfigPromise;
}, () => {
this.privConnectionId = null;
this.privConnectionConfigPromise = void 0;
return this.configConnection();
});
}
if (this.terminateMessageLoop) {
return Promise.resolve(void 0);
}
this.privConnectionConfigPromise = this.connectImpl().then((connection) => connection);
return this.privConnectionConfigPromise;
}
getTranslations(serviceResultTranslations) {
let translations;
if (void 0 !== serviceResultTranslations) {
translations = new Exports_js_2.Translations();
for (const translation of serviceResultTranslations) {
translations.set(translation.lang, translation.translation);
}
}
return translations;
}
};
exports.ConversationServiceAdapter = ConversationServiceAdapter;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationTranslatorRecognizer.js
var require_ConversationTranslatorRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/ConversationTranslatorRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversationTranslatorRecognizer = exports.ConversationRecognizerFactory = void 0;
var Exports_js_1 = require_Exports7();
var Exports_js_2 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_3 = require_Exports3();
var ConversationConnectionFactory_js_1 = require_ConversationConnectionFactory();
var ConversationServiceAdapter_js_1 = require_ConversationServiceAdapter();
var ConversationRecognizerFactory = class {
static fromConfig(conversation, speechConfig, audioConfig) {
return new ConversationTranslatorRecognizer(conversation, speechConfig, audioConfig);
}
};
exports.ConversationRecognizerFactory = ConversationRecognizerFactory;
var ConversationTranslatorRecognizer = class extends Exports_js_3.Recognizer {
constructor(conversation, speechConfig, audioConfig) {
const serviceConfigImpl = speechConfig;
Contracts_js_1.Contracts.throwIfNull(serviceConfigImpl, "speechConfig");
const conversationImpl = conversation;
Contracts_js_1.Contracts.throwIfNull(conversationImpl, "conversationImpl");
super(audioConfig, serviceConfigImpl.properties, new ConversationConnectionFactory_js_1.ConversationConnectionFactory());
this.privConversation = conversationImpl;
this.privIsDisposed = false;
this.privProperties = serviceConfigImpl.properties.clone();
this.privConnection = Exports_js_3.Connection.fromRecognizer(this);
const webWorkerLoadType = this.privProperties.getProperty(Exports_js_3.PropertyId.WebWorkerLoadType, "on").toLowerCase();
if (webWorkerLoadType === "on" && typeof Blob !== "undefined" && typeof Worker !== "undefined") {
this.privSetTimeout = Exports_js_2.Timeout.setTimeout;
this.privClearTimeout = Exports_js_2.Timeout.clearTimeout;
} else {
if (typeof window !== "undefined") {
this.privSetTimeout = window.setTimeout.bind(window);
this.privClearTimeout = window.clearTimeout.bind(window);
} else {
this.privSetTimeout = setTimeout;
this.privClearTimeout = clearTimeout;
}
}
}
set connected(cb) {
this.privConnection.connected = cb;
}
set disconnected(cb) {
this.privConnection.disconnected = cb;
}
/**
* Return the speech language used by the recognizer
*/
get speechRecognitionLanguage() {
return this.privSpeechRecognitionLanguage;
}
/**
* Return the properties for the recognizer
*/
get properties() {
return this.privProperties;
}
isDisposed() {
return this.privIsDisposed;
}
/**
* Connect to the recognizer
* @param token
*/
connect(token, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token");
this.privReco.conversationTranslatorToken = token;
this.resetConversationTimeout();
this.privReco.connectAsync(cb, err);
} catch (error) {
if (!!err) {
if (error instanceof Error) {
const typedError = error;
err(typedError.name + ": " + typedError.message);
} else {
err(error);
}
}
}
}
/**
* Disconnect from the recognizer
*/
disconnect(cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
if (this.privTimeoutToken !== void 0) {
this.privClearTimeout(this.privTimeoutToken);
}
this.privReco.disconnect().then(() => {
if (!!cb) {
cb();
}
}, (error) => {
if (!!err) {
err(error);
}
});
} catch (error) {
if (!!err) {
if (error instanceof Error) {
const typedError = error;
err(typedError.name + ": " + typedError.message);
} else {
err(error);
}
}
this.dispose(true).catch((reason) => {
Exports_js_2.Events.instance.onEvent(new Exports_js_2.BackgroundEvent(reason));
});
}
}
/**
* Send the mute all participants command to the websocket
* @param conversationId
* @param participantId
* @param isMuted
*/
sendRequest(command, cb, err) {
try {
Contracts_js_1.Contracts.throwIfDisposed(this.privIsDisposed);
this.sendMessage(command, cb, err);
} catch (error) {
if (!!err) {
if (error instanceof Error) {
const typedError = error;
err(typedError.name + ": " + typedError.message);
} else {
err(error);
}
}
this.dispose(true).catch((reason) => {
Exports_js_2.Events.instance.onEvent(new Exports_js_2.BackgroundEvent(reason));
});
}
}
/**
* Handle update of service auth token (#694)
*/
onToken(token) {
this.privConversation.onToken(token);
}
/**
* Close and dispose the recognizer
*/
async close() {
if (!this.privIsDisposed) {
if (!!this.privConnection) {
this.privConnection.closeConnection();
this.privConnection.close();
}
this.privConnection = void 0;
await this.dispose(true);
}
}
/**
* Dispose the recognizer
* @param disposing
*/
async dispose(disposing) {
if (this.privIsDisposed) {
return;
}
if (disposing) {
if (this.privTimeoutToken !== void 0) {
this.privClearTimeout(this.privTimeoutToken);
}
this.privIsDisposed = true;
if (!!this.privConnection) {
this.privConnection.closeConnection();
this.privConnection.close();
this.privConnection = void 0;
}
await super.dispose(disposing);
}
}
/**
* Create the config for the recognizer
* @param speechConfig
*/
createRecognizerConfig(speechConfig) {
return new Exports_js_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
*/
createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) {
const audioSource = audioConfig;
return new ConversationServiceAdapter_js_1.ConversationServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this);
}
sendMessage(msg, cb, err) {
const withAsync = this.privReco;
const PromiseToEmptyCallback = (promise, cb2, err2) => {
if (promise !== void 0) {
promise.then(() => {
try {
if (!!cb2) {
cb2();
}
} catch (e) {
if (!!err2) {
err2(`'Unhandled error on promise callback: ${e}'`);
}
}
}, (reason) => {
try {
if (!!err2) {
err2(reason);
}
} catch (error) {
}
});
} else {
if (!!err2) {
err2("Null promise");
}
}
};
PromiseToEmptyCallback(withAsync.sendMessageAsync(msg), cb, err);
this.resetConversationTimeout();
}
resetConversationTimeout() {
if (this.privTimeoutToken !== void 0) {
this.privClearTimeout(this.privTimeoutToken);
}
this.privTimeoutToken = this.privSetTimeout(() => {
this.sendRequest(this.privConversation.getKeepAlive());
}, 6e4);
}
};
exports.ConversationTranslatorRecognizer = ConversationTranslatorRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/TranscriberRecognizer.js
var require_TranscriberRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/TranscriberRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranscriberRecognizer = void 0;
var Exports_js_1 = require_Exports();
var Contracts_js_1 = require_Contracts();
var Exports_js_2 = require_Exports3();
var Exports_js_3 = require_Exports7();
var PhraseDetectionContext_js_1 = require_PhraseDetectionContext();
var TranscriberRecognizer = class extends Exports_js_2.Recognizer {
/**
* TranscriberRecognizer constructor.
* @constructor
* @param {SpeechTranslationConfig} speechTranslationConfig - Non-audio configuration associated with the recognizer
* @param {AudioConfig} audioConfig - An audio configuration associated with the recognizer
*/
constructor(speechTranslationConfig, audioConfig) {
const speechTranslationConfigImpl = speechTranslationConfig;
Contracts_js_1.Contracts.throwIfNull(speechTranslationConfigImpl, "speechTranslationConfig");
const audioConfigImpl = audioConfig;
Contracts_js_1.Contracts.throwIfNull(audioConfigImpl, "audioConfigImpl");
Contracts_js_1.Contracts.throwIfNullOrWhitespace(speechTranslationConfigImpl.speechRecognitionLanguage, Exports_js_2.PropertyId[Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage]);
super(audioConfig, speechTranslationConfigImpl.properties, new Exports_js_3.TranscriberConnectionFactory());
this.privDisposedRecognizer = false;
this.isMeetingRecognizer = false;
}
get speechRecognitionLanguage() {
Contracts_js_1.Contracts.throwIfDisposed(this.privDisposedRecognizer);
return this.properties.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_RecoLanguage);
}
get properties() {
return this.privProperties;
}
get authorizationToken() {
return this.properties.getProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token);
}
set authorizationToken(token) {
Contracts_js_1.Contracts.throwIfNullOrWhitespace(token, "token");
this.properties.setProperty(Exports_js_2.PropertyId.SpeechServiceAuthorization_Token, token);
}
set conversation(c) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(c, "Conversation");
this.isMeetingRecognizer = false;
this.privConversation = c;
}
getConversationInfo() {
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privConversation, "Conversation");
return this.privConversation.conversationInfo;
}
set meeting(m) {
Contracts_js_1.Contracts.throwIfNullOrUndefined(m, "Meeting");
this.isMeetingRecognizer = true;
this.privMeeting = m;
}
getMeetingInfo() {
Contracts_js_1.Contracts.throwIfNullOrUndefined(this.privMeeting, "Meeting");
return this.privMeeting.meetingInfo;
}
IsMeetingRecognizer() {
return this.isMeetingRecognizer;
}
startContinuousRecognitionAsync(cb, err) {
(0, Exports_js_1.marshalPromiseToCallbacks)(this.startContinuousRecognitionAsyncImpl(PhraseDetectionContext_js_1.RecognitionMode.Conversation), cb, err);
}
stopContinuousRecognitionAsync(cb, err) {
(0, Exports_js_1.marshalPromiseToCallbacks)(this.stopContinuousRecognitionAsyncImpl(), cb, err);
}
async close() {
if (!this.privDisposedRecognizer) {
await this.dispose(true);
}
}
// Push async join/leave conversation message via serviceRecognizer
async pushConversationEvent(conversationInfo, command) {
const reco = this.privReco;
Contracts_js_1.Contracts.throwIfNullOrUndefined(reco, "serviceRecognizer");
await reco.sendSpeechEventAsync(conversationInfo, command);
}
// Push async join/leave meeting message via serviceRecognizer
async pushMeetingEvent(meetingInfo, command) {
const reco = this.privReco;
Contracts_js_1.Contracts.throwIfNullOrUndefined(reco, "serviceRecognizer");
await reco.sendMeetingSpeechEventAsync(meetingInfo, command);
}
async enforceAudioGating() {
const audioConfigImpl = this.audioConfig;
const format2 = await audioConfigImpl.format;
const channels = format2.channels;
if (channels === 1) {
if (this.properties.getProperty("f0f5debc-f8c9-4892-ac4b-90a7ab359fd2", "false").toLowerCase() !== "true") {
throw new Error("Single channel audio configuration for MeetingTranscriber is currently under private preview, please contact diarizationrequest@microsoft.com for more details");
}
} else if (channels !== 8) {
throw new Error(`Unsupported audio configuration: Detected ${channels}-channel audio`);
}
return;
}
connectMeetingCallbacks(transcriber) {
this.isMeetingRecognizer = true;
this.canceled = (s, e) => {
if (!!transcriber.canceled) {
transcriber.canceled(transcriber, e);
}
};
this.recognizing = (s, e) => {
if (!!transcriber.transcribing) {
transcriber.transcribing(transcriber, e);
}
};
this.recognized = (s, e) => {
if (!!transcriber.transcribed) {
transcriber.transcribed(transcriber, e);
}
};
this.sessionStarted = (s, e) => {
if (!!transcriber.sessionStarted) {
transcriber.sessionStarted(transcriber, e);
}
};
this.sessionStopped = (s, e) => {
if (!!transcriber.sessionStopped) {
transcriber.sessionStopped(transcriber, e);
}
};
}
disconnectCallbacks() {
this.canceled = void 0;
this.recognizing = void 0;
this.recognized = void 0;
this.sessionStarted = void 0;
this.sessionStopped = void 0;
}
/**
* Disposes any resources held by the object.
* @member ConversationTranscriber.prototype.dispose
* @function
* @public
* @param {boolean} disposing - true if disposing the object.
*/
async dispose(disposing) {
if (this.privDisposedRecognizer) {
return;
}
if (disposing) {
this.privDisposedRecognizer = true;
await this.implRecognizerStop();
}
await super.dispose(disposing);
}
createRecognizerConfig(speechConfig) {
return new Exports_js_3.RecognizerConfig(speechConfig, this.properties);
}
createServiceRecognizer(authentication, connectionFactory, audioConfig, recognizerConfig) {
const configImpl = audioConfig;
return new Exports_js_3.TranscriptionServiceRecognizer(authentication, connectionFactory, configImpl, recognizerConfig, this);
}
};
exports.TranscriberRecognizer = TranscriberRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/Exports.js
var require_Exports6 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Transcription/Exports.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InternalParticipants = exports.ConversationTranslatorMessageTypes = exports.ConversationTranslatorCommandTypes = exports.ParticipantsListEventArgs = exports.ParticipantEventArgs = exports.ParticipantAttributeEventArgs = exports.MuteAllEventArgs = exports.LockRoomEventArgs = exports.ConversationReceivedTranslationEventArgs = exports.TranscriberRecognizer = exports.ConversationRecognizerFactory = exports.ConversationConnectionConfig = exports.ConversationManager = void 0;
var ConversationManager_js_1 = require_ConversationManager();
Object.defineProperty(exports, "ConversationManager", { enumerable: true, get: function() {
return ConversationManager_js_1.ConversationManager;
} });
var ConversationConnectionConfig_js_1 = require_ConversationConnectionConfig();
Object.defineProperty(exports, "ConversationConnectionConfig", { enumerable: true, get: function() {
return ConversationConnectionConfig_js_1.ConversationConnectionConfig;
} });
var ConversationTranslatorRecognizer_js_1 = require_ConversationTranslatorRecognizer();
Object.defineProperty(exports, "ConversationRecognizerFactory", { enumerable: true, get: function() {
return ConversationTranslatorRecognizer_js_1.ConversationRecognizerFactory;
} });
var TranscriberRecognizer_js_1 = require_TranscriberRecognizer();
Object.defineProperty(exports, "TranscriberRecognizer", { enumerable: true, get: function() {
return TranscriberRecognizer_js_1.TranscriberRecognizer;
} });
var ConversationTranslatorEventArgs_js_1 = require_ConversationTranslatorEventArgs();
Object.defineProperty(exports, "ConversationReceivedTranslationEventArgs", { enumerable: true, get: function() {
return ConversationTranslatorEventArgs_js_1.ConversationReceivedTranslationEventArgs;
} });
Object.defineProperty(exports, "LockRoomEventArgs", { enumerable: true, get: function() {
return ConversationTranslatorEventArgs_js_1.LockRoomEventArgs;
} });
Object.defineProperty(exports, "MuteAllEventArgs", { enumerable: true, get: function() {
return ConversationTranslatorEventArgs_js_1.MuteAllEventArgs;
} });
Object.defineProperty(exports, "ParticipantAttributeEventArgs", { enumerable: true, get: function() {
return ConversationTranslatorEventArgs_js_1.ParticipantAttributeEventArgs;
} });
Object.defineProperty(exports, "ParticipantEventArgs", { enumerable: true, get: function() {
return ConversationTranslatorEventArgs_js_1.ParticipantEventArgs;
} });
Object.defineProperty(exports, "ParticipantsListEventArgs", { enumerable: true, get: function() {
return ConversationTranslatorEventArgs_js_1.ParticipantsListEventArgs;
} });
var ConversationTranslatorInterfaces_js_1 = require_ConversationTranslatorInterfaces();
Object.defineProperty(exports, "ConversationTranslatorCommandTypes", { enumerable: true, get: function() {
return ConversationTranslatorInterfaces_js_1.ConversationTranslatorCommandTypes;
} });
Object.defineProperty(exports, "ConversationTranslatorMessageTypes", { enumerable: true, get: function() {
return ConversationTranslatorInterfaces_js_1.ConversationTranslatorMessageTypes;
} });
Object.defineProperty(exports, "InternalParticipants", { enumerable: true, get: function() {
return ConversationTranslatorInterfaces_js_1.InternalParticipants;
} });
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SynthesisAudioMetadata.js
var require_SynthesisAudioMetadata = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/ServiceMessages/SynthesisAudioMetadata.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisAudioMetadata = exports.MetadataType = void 0;
var MetadataType;
(function(MetadataType2) {
MetadataType2["WordBoundary"] = "WordBoundary";
MetadataType2["Bookmark"] = "Bookmark";
MetadataType2["Viseme"] = "Viseme";
MetadataType2["SentenceBoundary"] = "SentenceBoundary";
MetadataType2["SessionEnd"] = "SessionEnd";
MetadataType2["AvatarSignal"] = "TalkingAvatarSignal";
})(MetadataType = exports.MetadataType || (exports.MetadataType = {}));
var SynthesisAudioMetadata = class _SynthesisAudioMetadata {
constructor(json) {
this.privSynthesisAudioMetadata = JSON.parse(json);
}
static fromJSON(json) {
return new _SynthesisAudioMetadata(json);
}
get Metadata() {
return this.privSynthesisAudioMetadata.Metadata;
}
};
exports.SynthesisAudioMetadata = SynthesisAudioMetadata;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesisEvents.js
var require_SynthesisEvents = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesisEvents.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisStartedEvent = exports.ConnectingToSynthesisServiceEvent = exports.SynthesisTriggeredEvent = exports.SpeechSynthesisEvent = void 0;
var Exports_js_1 = require_Exports();
var SpeechSynthesisEvent2 = class extends Exports_js_1.PlatformEvent {
constructor(eventName, requestId, eventType = Exports_js_1.EventType.Info) {
super(eventName, eventType);
this.privRequestId = requestId;
}
get requestId() {
return this.privRequestId;
}
};
exports.SpeechSynthesisEvent = SpeechSynthesisEvent2;
var SynthesisTriggeredEvent = class extends SpeechSynthesisEvent2 {
constructor(requestId, sessionAudioDestinationId, turnAudioDestinationId) {
super("SynthesisTriggeredEvent", requestId);
this.privSessionAudioDestinationId = sessionAudioDestinationId;
this.privTurnAudioDestinationId = turnAudioDestinationId;
}
get audioSessionDestinationId() {
return this.privSessionAudioDestinationId;
}
get audioTurnDestinationId() {
return this.privTurnAudioDestinationId;
}
};
exports.SynthesisTriggeredEvent = SynthesisTriggeredEvent;
var ConnectingToSynthesisServiceEvent = class extends SpeechSynthesisEvent2 {
constructor(requestId, authFetchEventId) {
super("ConnectingToSynthesisServiceEvent", requestId);
this.privAuthFetchEventId = authFetchEventId;
}
get authFetchEventId() {
return this.privAuthFetchEventId;
}
};
exports.ConnectingToSynthesisServiceEvent = ConnectingToSynthesisServiceEvent;
var SynthesisStartedEvent = class extends SpeechSynthesisEvent2 {
constructor(requestId, authFetchEventId) {
super("SynthesisStartedEvent", requestId);
this.privAuthFetchEventId = authFetchEventId;
}
get authFetchEventId() {
return this.privAuthFetchEventId;
}
};
exports.SynthesisStartedEvent = SynthesisStartedEvent;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesisTurn.js
var require_SynthesisTurn = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesisTurn.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisTurn = void 0;
var Exports_js_1 = require_Exports();
var AudioOutputStream_js_1 = require_AudioOutputStream();
var Exports_js_2 = require_Exports3();
var SynthesisAudioMetadata_js_1 = require_SynthesisAudioMetadata();
var SynthesisEvents_js_1 = require_SynthesisEvents();
var SynthesisTurn = class _SynthesisTurn {
constructor() {
this.privIsDisposed = false;
this.privIsSynthesizing = false;
this.privIsSynthesisEnded = false;
this.privBytesReceived = 0;
this.privInTurn = false;
this.privTextOffset = 0;
this.privNextSearchTextIndex = 0;
this.privSentenceOffset = 0;
this.privNextSearchSentenceIndex = 0;
this.privRequestId = (0, Exports_js_1.createNoDashGuid)();
this.privTurnDeferral = new Exports_js_1.Deferred();
this.privTurnDeferral.resolve();
}
get requestId() {
return this.privRequestId;
}
get streamId() {
return this.privStreamId;
}
set streamId(value) {
this.privStreamId = value;
}
get audioOutputFormat() {
return this.privAudioOutputFormat;
}
set audioOutputFormat(format2) {
this.privAudioOutputFormat = format2;
}
get turnCompletionPromise() {
return this.privTurnDeferral.promise;
}
get isSynthesisEnded() {
return this.privIsSynthesisEnded;
}
get isSynthesizing() {
return this.privIsSynthesizing;
}
get currentTextOffset() {
return this.privTextOffset;
}
get currentSentenceOffset() {
return this.privSentenceOffset;
}
// The number of bytes received for current turn
get bytesReceived() {
return this.privBytesReceived;
}
get audioDuration() {
return this.privAudioDuration;
}
get extraProperties() {
if (!!this.privWebRTCSDP) {
const properties = new Exports_js_2.PropertyCollection();
properties.setProperty(Exports_js_2.PropertyId.TalkingAvatarService_WebRTC_SDP, this.privWebRTCSDP);
return properties;
}
return void 0;
}
async getAllReceivedAudio() {
if (!!this.privReceivedAudio) {
return Promise.resolve(this.privReceivedAudio);
}
if (!this.privIsSynthesisEnded) {
return null;
}
await this.readAllAudioFromStream();
return Promise.resolve(this.privReceivedAudio);
}
async getAllReceivedAudioWithHeader() {
if (!!this.privReceivedAudioWithHeader) {
return this.privReceivedAudioWithHeader;
}
if (!this.privIsSynthesisEnded) {
return null;
}
if (this.audioOutputFormat.hasHeader) {
const audio = await this.getAllReceivedAudio();
this.privReceivedAudioWithHeader = this.audioOutputFormat.addHeader(audio);
return this.privReceivedAudioWithHeader;
} else {
return this.getAllReceivedAudio();
}
}
startNewSynthesis(requestId, rawText, isSSML2, audioDestination) {
this.privIsSynthesisEnded = false;
this.privIsSynthesizing = true;
this.privRequestId = requestId;
this.privRawText = rawText;
this.privIsSSML = isSSML2;
this.privAudioOutputStream = new AudioOutputStream_js_1.PullAudioOutputStreamImpl();
this.privAudioOutputStream.format = this.privAudioOutputFormat;
this.privReceivedAudio = null;
this.privReceivedAudioWithHeader = null;
this.privBytesReceived = 0;
this.privTextOffset = 0;
this.privNextSearchTextIndex = 0;
this.privSentenceOffset = 0;
this.privNextSearchSentenceIndex = 0;
this.privPartialVisemeAnimation = "";
this.privWebRTCSDP = "";
if (audioDestination !== void 0) {
this.privTurnAudioDestination = audioDestination;
this.privTurnAudioDestination.format = this.privAudioOutputFormat;
}
this.onEvent(new SynthesisEvents_js_1.SynthesisTriggeredEvent(this.requestId, void 0, audioDestination === void 0 ? void 0 : audioDestination.id()));
}
onPreConnectionStart(authFetchEventId) {
this.privAuthFetchEventId = authFetchEventId;
this.onEvent(new SynthesisEvents_js_1.ConnectingToSynthesisServiceEvent(this.privRequestId, this.privAuthFetchEventId));
}
onAuthCompleted(isError) {
if (isError) {
this.onComplete();
}
}
onConnectionEstablishCompleted(statusCode) {
if (statusCode === 200) {
this.onEvent(new SynthesisEvents_js_1.SynthesisStartedEvent(this.requestId, this.privAuthFetchEventId));
this.privBytesReceived = 0;
return;
} else if (statusCode === 403) {
this.onComplete();
}
}
onServiceResponseMessage(responseJson) {
const response = JSON.parse(responseJson);
this.streamId = response.audio.streamId;
}
onServiceTurnEndResponse() {
this.privInTurn = false;
this.privTurnDeferral.resolve();
this.onComplete();
}
onServiceTurnStartResponse(responseJson) {
if (!!this.privTurnDeferral && !!this.privInTurn) {
this.privTurnDeferral.reject("Another turn started before current completed.");
this.privTurnDeferral.promise.then().catch(() => {
});
}
this.privInTurn = true;
this.privTurnDeferral = new Exports_js_1.Deferred();
const response = JSON.parse(responseJson);
if (!!response.webrtc) {
this.privWebRTCSDP = response.webrtc.connectionString;
}
}
onAudioChunkReceived(data) {
if (this.isSynthesizing) {
this.privAudioOutputStream.write(data);
this.privBytesReceived += data.byteLength;
if (this.privTurnAudioDestination !== void 0) {
this.privTurnAudioDestination.write(data);
}
}
}
onTextBoundaryEvent(metadata) {
this.updateTextOffset(metadata.Data.text.Text, metadata.Type);
}
onVisemeMetadataReceived(metadata) {
if (metadata.Data.AnimationChunk !== void 0) {
this.privPartialVisemeAnimation += metadata.Data.AnimationChunk;
}
}
onSessionEnd(metadata) {
this.privAudioDuration = metadata.Data.Offset;
}
async constructSynthesisResult() {
const audioBuffer = await this.getAllReceivedAudioWithHeader();
return new Exports_js_2.SpeechSynthesisResult(this.requestId, Exports_js_2.ResultReason.SynthesizingAudioCompleted, audioBuffer, void 0, this.extraProperties, this.audioDuration);
}
dispose() {
if (!this.privIsDisposed) {
this.privIsDisposed = true;
}
}
onStopSynthesizing() {
this.onComplete();
}
/**
* Gets the viseme animation string (merged from animation chunk), and clears the internal
* partial animation.
*/
getAndClearVisemeAnimation() {
const animation = this.privPartialVisemeAnimation;
this.privPartialVisemeAnimation = "";
return animation;
}
onEvent(event) {
Exports_js_1.Events.instance.onEvent(event);
}
/**
* Check if the text is an XML(SSML) tag
* @param text
* @private
*/
static isXmlTag(text) {
return text.length >= 2 && text[0] === "<" && text[text.length - 1] === ">";
}
updateTextOffset(text, type) {
if (type === SynthesisAudioMetadata_js_1.MetadataType.WordBoundary) {
this.privTextOffset = this.privRawText.indexOf(text, this.privNextSearchTextIndex);
if (this.privTextOffset >= 0) {
this.privNextSearchTextIndex = this.privTextOffset + text.length;
if (this.privIsSSML) {
if (this.withinXmlTag(this.privTextOffset) && !_SynthesisTurn.isXmlTag(text)) {
this.updateTextOffset(text, type);
}
}
}
} else {
this.privSentenceOffset = this.privRawText.indexOf(text, this.privNextSearchSentenceIndex);
if (this.privSentenceOffset >= 0) {
this.privNextSearchSentenceIndex = this.privSentenceOffset + text.length;
if (this.privIsSSML) {
if (this.withinXmlTag(this.privSentenceOffset) && !_SynthesisTurn.isXmlTag(text)) {
this.updateTextOffset(text, type);
}
}
}
}
}
onComplete() {
if (this.privIsSynthesizing) {
this.privIsSynthesizing = false;
this.privIsSynthesisEnded = true;
this.privAudioOutputStream.close();
this.privInTurn = false;
if (this.privTurnAudioDestination !== void 0) {
this.privTurnAudioDestination.close();
this.privTurnAudioDestination = void 0;
}
}
}
async readAllAudioFromStream() {
if (this.privIsSynthesisEnded) {
this.privReceivedAudio = new ArrayBuffer(this.bytesReceived);
try {
await this.privAudioOutputStream.read(this.privReceivedAudio);
} catch (e) {
this.privReceivedAudio = new ArrayBuffer(0);
}
}
}
/**
* Check if current idx is in XML(SSML) tag
* @param idx
* @private
*/
withinXmlTag(idx) {
return this.privRawText.indexOf("<", idx + 1) > this.privRawText.indexOf(">", idx + 1);
}
};
exports.SynthesisTurn = SynthesisTurn;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesisAdapterBase.js
var require_SynthesisAdapterBase = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesisAdapterBase.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisAdapterBase = void 0;
var Exports_js_1 = require_Exports();
var Exports_js_2 = require_Exports3();
var Exports_js_3 = require_Exports7();
var SpeechConnectionMessage_Internal_js_1 = require_SpeechConnectionMessage_Internal();
var SynthesisAdapterBase = class {
constructor(authentication, connectionFactory, synthesizerConfig, audioDestination) {
this.speakOverride = void 0;
this.receiveMessageOverride = void 0;
this.connectImplOverride = void 0;
this.configConnectionOverride = void 0;
this.privConnectionConfigurationPromise = void 0;
if (!authentication) {
throw new Exports_js_1.ArgumentNullError("authentication");
}
if (!connectionFactory) {
throw new Exports_js_1.ArgumentNullError("connectionFactory");
}
if (!synthesizerConfig) {
throw new Exports_js_1.ArgumentNullError("synthesizerConfig");
}
this.privAuthentication = authentication;
this.privConnectionFactory = connectionFactory;
this.privSynthesizerConfig = synthesizerConfig;
this.privIsDisposed = false;
this.privSessionAudioDestination = audioDestination;
this.privSynthesisTurn = new Exports_js_3.SynthesisTurn();
this.privConnectionEvents = new Exports_js_1.EventSource();
this.privServiceEvents = new Exports_js_1.EventSource();
this.privSynthesisContext = new Exports_js_3.SynthesisContext();
this.privAgentConfig = new Exports_js_3.AgentConfig();
this.connectionEvents.attach((connectionEvent) => {
if (connectionEvent.name === "ConnectionClosedEvent") {
const connectionClosedEvent = connectionEvent;
if (connectionClosedEvent.statusCode !== 1e3) {
this.cancelSynthesisLocal(Exports_js_2.CancellationReason.Error, connectionClosedEvent.statusCode === 1007 ? Exports_js_2.CancellationErrorCode.BadRequestParameters : Exports_js_2.CancellationErrorCode.ConnectionFailure, `${connectionClosedEvent.reason} websocket error code: ${connectionClosedEvent.statusCode}`);
}
}
});
}
get synthesizerConfig() {
return this.privSynthesizerConfig;
}
get synthesisContext() {
return this.privSynthesisContext;
}
get agentConfig() {
return this.privAgentConfig;
}
get connectionEvents() {
return this.privConnectionEvents;
}
get serviceEvents() {
return this.privServiceEvents;
}
set activityTemplate(messagePayload) {
this.privActivityTemplate = messagePayload;
}
get activityTemplate() {
return this.privActivityTemplate;
}
set audioOutputFormat(format2) {
this.privAudioOutputFormat = format2;
this.privSynthesisTurn.audioOutputFormat = format2;
if (this.privSessionAudioDestination !== void 0) {
this.privSessionAudioDestination.format = format2;
}
if (this.synthesisContext !== void 0) {
this.synthesisContext.audioOutputFormat = format2;
}
}
isDisposed() {
return this.privIsDisposed;
}
async dispose(reason) {
this.privIsDisposed = true;
if (this.privSessionAudioDestination !== void 0) {
this.privSessionAudioDestination.close();
}
if (this.privConnectionConfigurationPromise !== void 0) {
const connection = await this.privConnectionConfigurationPromise;
await connection.dispose(reason);
}
}
async connect() {
await this.connectImpl();
}
async sendNetworkMessage(path, payload) {
const type = typeof payload === "string" ? Exports_js_1.MessageType.Text : Exports_js_1.MessageType.Binary;
const contentType = typeof payload === "string" ? "application/json" : "";
const connection = await this.fetchConnection();
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(type, path, this.privSynthesisTurn.requestId, contentType, payload));
}
async Speak(text, isSSML2, requestId, successCallback, errorCallBack, audioDestination) {
let ssml;
if (isSSML2) {
ssml = text;
} else {
ssml = this.privSynthesizer.buildSsml(text);
}
if (this.speakOverride !== void 0) {
return this.speakOverride(ssml, requestId, successCallback, errorCallBack);
}
this.privSuccessCallback = successCallback;
this.privErrorCallback = errorCallBack;
this.privSynthesisTurn.startNewSynthesis(requestId, text, isSSML2, audioDestination);
try {
await this.connectImpl();
const connection = await this.fetchConnection();
await this.sendSynthesisContext(connection);
await this.sendSsmlMessage(connection, ssml, requestId);
this.onSynthesisStarted(requestId);
void this.receiveMessage();
} catch (e) {
this.cancelSynthesisLocal(Exports_js_2.CancellationReason.Error, Exports_js_2.CancellationErrorCode.ConnectionFailure, e);
return Promise.reject(e);
}
}
async stopSpeaking() {
await this.connectImpl();
const connection = await this.fetchConnection();
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "synthesis.control", this.privSynthesisTurn.requestId, "application/json", JSON.stringify({
action: "stop"
})));
}
// Cancels synthesis.
cancelSynthesis(requestId, _cancellationReason, errorCode, error) {
const properties = new Exports_js_2.PropertyCollection();
properties.setProperty(Exports_js_3.CancellationErrorCodePropertyName, Exports_js_2.CancellationErrorCode[errorCode]);
const result = new Exports_js_2.SpeechSynthesisResult(requestId, Exports_js_2.ResultReason.Canceled, void 0, error, properties);
this.onSynthesisCancelled(result);
if (!!this.privSuccessCallback) {
try {
this.privSuccessCallback(result);
} catch {
}
}
}
// Cancels synthesis.
cancelSynthesisLocal(cancellationReason, errorCode, error) {
if (!!this.privSynthesisTurn.isSynthesizing) {
this.privSynthesisTurn.onStopSynthesizing();
this.cancelSynthesis(this.privSynthesisTurn.requestId, cancellationReason, errorCode, error);
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
processTypeSpecificMessages(_connectionMessage) {
return true;
}
async receiveMessage() {
try {
const connection = await this.fetchConnection();
const message = await connection.read();
if (this.receiveMessageOverride !== void 0) {
return this.receiveMessageOverride();
}
if (this.privIsDisposed) {
return;
}
if (!message) {
if (!this.privSynthesisTurn.isSynthesizing) {
return;
} else {
return this.receiveMessage();
}
}
const connectionMessage = SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage.fromConnectionMessage(message);
if (connectionMessage.requestId.toLowerCase() === this.privSynthesisTurn.requestId.toLowerCase()) {
switch (connectionMessage.path.toLowerCase()) {
case "turn.start":
this.privSynthesisTurn.onServiceTurnStartResponse(connectionMessage.textBody);
break;
case "response":
this.privSynthesisTurn.onServiceResponseMessage(connectionMessage.textBody);
break;
case "audio":
if (this.privSynthesisTurn.streamId.toLowerCase() === connectionMessage.streamId.toLowerCase() && !!connectionMessage.binaryBody) {
this.privSynthesisTurn.onAudioChunkReceived(connectionMessage.binaryBody);
this.onSynthesizing(connectionMessage.binaryBody);
if (this.privSessionAudioDestination !== void 0) {
this.privSessionAudioDestination.write(connectionMessage.binaryBody);
}
}
break;
case "audio.metadata":
const metadataList = Exports_js_3.SynthesisAudioMetadata.fromJSON(connectionMessage.textBody).Metadata;
for (const metadata of metadataList) {
switch (metadata.Type) {
case Exports_js_3.MetadataType.WordBoundary:
case Exports_js_3.MetadataType.SentenceBoundary:
this.privSynthesisTurn.onTextBoundaryEvent(metadata);
const wordBoundaryEventArgs = new Exports_js_2.SpeechSynthesisWordBoundaryEventArgs(metadata.Data.Offset, metadata.Data.Duration, metadata.Data.text.Text, metadata.Data.text.Length, metadata.Type === Exports_js_3.MetadataType.WordBoundary ? this.privSynthesisTurn.currentTextOffset : this.privSynthesisTurn.currentSentenceOffset, metadata.Data.text.BoundaryType);
this.onWordBoundary(wordBoundaryEventArgs);
break;
case Exports_js_3.MetadataType.Bookmark:
const bookmarkEventArgs = new Exports_js_2.SpeechSynthesisBookmarkEventArgs(metadata.Data.Offset, metadata.Data.Bookmark);
this.onBookmarkReached(bookmarkEventArgs);
break;
case Exports_js_3.MetadataType.Viseme:
this.privSynthesisTurn.onVisemeMetadataReceived(metadata);
if (metadata.Data.IsLastAnimation) {
const visemeEventArgs = new Exports_js_2.SpeechSynthesisVisemeEventArgs(metadata.Data.Offset, metadata.Data.VisemeId, this.privSynthesisTurn.getAndClearVisemeAnimation());
this.onVisemeReceived(visemeEventArgs);
}
break;
case Exports_js_3.MetadataType.AvatarSignal:
this.onAvatarEvent(metadata);
break;
case Exports_js_3.MetadataType.SessionEnd:
this.privSynthesisTurn.onSessionEnd(metadata);
break;
}
}
break;
case "turn.end":
this.privSynthesisTurn.onServiceTurnEndResponse();
let result;
try {
result = await this.privSynthesisTurn.constructSynthesisResult();
if (!!this.privSuccessCallback) {
this.privSuccessCallback(result);
}
} catch (error) {
if (!!this.privErrorCallback) {
this.privErrorCallback(error);
}
}
this.onSynthesisCompleted(result);
break;
default:
if (!this.processTypeSpecificMessages(connectionMessage)) {
if (!!this.privServiceEvents) {
this.serviceEvents.onEvent(new Exports_js_1.ServiceEvent(connectionMessage.path.toLowerCase(), connectionMessage.textBody));
}
}
}
}
return this.receiveMessage();
} catch (e) {
}
}
sendSynthesisContext(connection) {
this.setSynthesisContextSynthesisSection();
const synthesisContextJson = this.synthesisContext.toJSON();
if (synthesisContextJson) {
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "synthesis.context", this.privSynthesisTurn.requestId, "application/json", synthesisContextJson));
}
return;
}
setSpeechConfigSynthesisSection() {
return;
}
connectImpl(isUnAuthorized = false) {
if (this.privConnectionPromise != null) {
return this.privConnectionPromise.then((connection) => {
if (connection.state() === Exports_js_1.ConnectionState.Disconnected) {
this.privConnectionId = null;
this.privConnectionPromise = null;
return this.connectImpl();
}
return this.privConnectionPromise;
}, () => {
this.privConnectionId = null;
this.privConnectionPromise = null;
return this.connectImpl();
});
}
this.privAuthFetchEventId = (0, Exports_js_1.createNoDashGuid)();
this.privConnectionId = (0, Exports_js_1.createNoDashGuid)();
this.privSynthesisTurn.onPreConnectionStart(this.privAuthFetchEventId);
const authPromise = isUnAuthorized ? this.privAuthentication.fetchOnExpiry(this.privAuthFetchEventId) : this.privAuthentication.fetch(this.privAuthFetchEventId);
this.privConnectionPromise = authPromise.then(async (result) => {
this.privSynthesisTurn.onAuthCompleted(false);
const connection = await this.privConnectionFactory.create(this.privSynthesizerConfig, result, this.privConnectionId);
connection.events.attach((event) => {
this.connectionEvents.onEvent(event);
});
const response = await connection.open();
if (response.statusCode === 200) {
this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode);
return Promise.resolve(connection);
} else if (response.statusCode === 403 && !isUnAuthorized) {
return this.connectImpl(true);
} else {
this.privSynthesisTurn.onConnectionEstablishCompleted(response.statusCode);
return Promise.reject(`Unable to contact server. StatusCode: ${response.statusCode},
${this.privSynthesizerConfig.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Url)} Reason: ${response.reason}`);
}
}, (error) => {
this.privSynthesisTurn.onAuthCompleted(true);
throw new Error(error);
});
this.privConnectionPromise.catch(() => {
});
return this.privConnectionPromise;
}
sendSpeechServiceConfig(connection, SpeechServiceConfigJson) {
if (SpeechServiceConfigJson) {
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "speech.config", this.privSynthesisTurn.requestId, "application/json", SpeechServiceConfigJson));
}
}
sendSsmlMessage(connection, ssml, requestId) {
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_1.MessageType.Text, "ssml", requestId, "application/ssml+xml", ssml));
}
async fetchConnection() {
if (this.privConnectionConfigurationPromise !== void 0) {
return this.privConnectionConfigurationPromise.then((connection) => {
if (connection.state() === Exports_js_1.ConnectionState.Disconnected) {
this.privConnectionId = null;
this.privConnectionConfigurationPromise = void 0;
return this.fetchConnection();
}
return this.privConnectionConfigurationPromise;
}, () => {
this.privConnectionId = null;
this.privConnectionConfigurationPromise = void 0;
return this.fetchConnection();
});
}
this.privConnectionConfigurationPromise = this.configureConnection();
return await this.privConnectionConfigurationPromise;
}
// Takes an established websocket connection to the endpoint and sends speech configuration information.
async configureConnection() {
const connection = await this.connectImpl();
if (this.configConnectionOverride !== void 0) {
return this.configConnectionOverride(connection);
}
this.setSpeechConfigSynthesisSection();
await this.sendSpeechServiceConfig(connection, this.privSynthesizerConfig.SpeechServiceConfig.serialize());
return connection;
}
onAvatarEvent(_metadata) {
return;
}
onSynthesisStarted(_requestId) {
return;
}
onSynthesizing(_audio) {
return;
}
onSynthesisCancelled(_result) {
return;
}
onSynthesisCompleted(_result) {
return;
}
onWordBoundary(_wordBoundaryEventArgs) {
return;
}
onVisemeReceived(_visemeEventArgs) {
return;
}
onBookmarkReached(_bookmarkEventArgs) {
return;
}
};
exports.SynthesisAdapterBase = SynthesisAdapterBase;
SynthesisAdapterBase.telemetryDataEnabled = true;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/AvatarSynthesisAdapter.js
var require_AvatarSynthesisAdapter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/AvatarSynthesisAdapter.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AvatarSynthesisAdapter = void 0;
var Exports_js_1 = require_Exports3();
var Exports_js_2 = require_Exports7();
var AvatarSynthesisAdapter = class extends Exports_js_2.SynthesisAdapterBase {
constructor(authentication, connectionFactory, synthesizerConfig, avatarSynthesizer, avatarConfig) {
super(authentication, connectionFactory, synthesizerConfig, void 0);
this.privAvatarSynthesizer = avatarSynthesizer;
this.privSynthesizer = avatarSynthesizer;
this.privAvatarConfig = avatarConfig;
}
setSynthesisContextSynthesisSection() {
this.privSynthesisContext.setSynthesisSection(void 0);
}
setSpeechConfigSynthesisSection() {
this.privSynthesizerConfig.synthesisVideoSection = {
format: {
bitrate: this.privAvatarConfig.videoFormat?.bitrate,
codec: this.privAvatarConfig.videoFormat?.codec,
crop: {
bottomRight: {
x: this.privAvatarConfig.videoFormat?.cropRange?.bottomRight?.x,
y: this.privAvatarConfig.videoFormat?.cropRange?.bottomRight?.y
},
topLeft: {
x: this.privAvatarConfig.videoFormat?.cropRange?.topLeft?.x,
y: this.privAvatarConfig.videoFormat?.cropRange?.topLeft?.y
}
},
resolution: {
height: this.privAvatarConfig.videoFormat?.height,
width: this.privAvatarConfig.videoFormat?.width
}
},
protocol: {
name: "WebRTC",
webrtcConfig: {
clientDescription: btoa(this.privSynthesizerConfig.parameters.getProperty(Exports_js_1.PropertyId.TalkingAvatarService_WebRTC_SDP)),
iceServers: this.privAvatarConfig.remoteIceServers ?? this.privAvatarSynthesizer.iceServers
}
},
talkingAvatar: {
background: {
color: this.privAvatarConfig.backgroundColor,
image: {
url: this.privAvatarConfig.backgroundImage?.toString()
}
},
character: this.privAvatarConfig.character,
customized: this.privAvatarConfig.customized,
style: this.privAvatarConfig.style,
useBuiltInVoice: this.privAvatarConfig.useBuiltInVoice
}
};
}
onAvatarEvent(metadata) {
if (!!this.privAvatarSynthesizer.avatarEventReceived) {
const avatarEventArgs = new Exports_js_1.AvatarEventArgs(metadata.Data.Offset, metadata.Data.Name);
try {
this.privAvatarSynthesizer.avatarEventReceived(this.privAvatarSynthesizer, avatarEventArgs);
} catch (error) {
}
}
}
};
exports.AvatarSynthesisAdapter = AvatarSynthesisAdapter;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechSynthesisAdapter.js
var require_SpeechSynthesisAdapter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechSynthesisAdapter.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechSynthesisAdapter = void 0;
var Exports_js_1 = require_Exports3();
var Exports_js_2 = require_Exports7();
var SpeechSynthesisAdapter = class extends Exports_js_2.SynthesisAdapterBase {
constructor(authentication, connectionFactory, synthesizerConfig, speechSynthesizer, audioDestination) {
super(authentication, connectionFactory, synthesizerConfig, audioDestination);
this.privSpeechSynthesizer = speechSynthesizer;
this.privSynthesizer = speechSynthesizer;
}
setSynthesisContextSynthesisSection() {
this.privSynthesisContext.setSynthesisSection(this.privSpeechSynthesizer);
}
onSynthesisStarted(requestId) {
const synthesisStartEventArgs = new Exports_js_1.SpeechSynthesisEventArgs(new Exports_js_1.SpeechSynthesisResult(requestId, Exports_js_1.ResultReason.SynthesizingAudioStarted));
if (!!this.privSpeechSynthesizer.synthesisStarted) {
this.privSpeechSynthesizer.synthesisStarted(this.privSpeechSynthesizer, synthesisStartEventArgs);
}
}
onSynthesizing(audio) {
if (!!this.privSpeechSynthesizer.synthesizing) {
try {
const audioWithHeader = this.privSynthesisTurn.audioOutputFormat.addHeader(audio);
const ev = new Exports_js_1.SpeechSynthesisEventArgs(new Exports_js_1.SpeechSynthesisResult(this.privSynthesisTurn.requestId, Exports_js_1.ResultReason.SynthesizingAudio, audioWithHeader));
this.privSpeechSynthesizer.synthesizing(this.privSpeechSynthesizer, ev);
} catch (error) {
}
}
}
onSynthesisCancelled(result) {
if (!!this.privSpeechSynthesizer.SynthesisCanceled) {
const cancelEvent = new Exports_js_1.SpeechSynthesisEventArgs(result);
try {
this.privSpeechSynthesizer.SynthesisCanceled(this.privSpeechSynthesizer, cancelEvent);
} catch {
}
}
}
onSynthesisCompleted(result) {
if (this.privSpeechSynthesizer.synthesisCompleted) {
try {
this.privSpeechSynthesizer.synthesisCompleted(this.privSpeechSynthesizer, new Exports_js_1.SpeechSynthesisEventArgs(result));
} catch (e) {
}
}
}
onWordBoundary(wordBoundaryEventArgs) {
if (!!this.privSpeechSynthesizer.wordBoundary) {
try {
this.privSpeechSynthesizer.wordBoundary(this.privSpeechSynthesizer, wordBoundaryEventArgs);
} catch (error) {
}
}
}
onVisemeReceived(visemeEventArgs) {
if (!!this.privSpeechSynthesizer.visemeReceived) {
try {
this.privSpeechSynthesizer.visemeReceived(this.privSpeechSynthesizer, visemeEventArgs);
} catch (error) {
}
}
}
onBookmarkReached(bookmarkEventArgs) {
if (!!this.privSpeechSynthesizer.bookmarkReached) {
try {
this.privSpeechSynthesizer.bookmarkReached(this.privSpeechSynthesizer, bookmarkEventArgs);
} catch (error) {
}
}
}
};
exports.SpeechSynthesisAdapter = SpeechSynthesisAdapter;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesisRestAdapter.js
var require_SynthesisRestAdapter = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesisRestAdapter.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisRestAdapter = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports3();
var ConnectionFactoryBase_js_1 = require_ConnectionFactoryBase();
var HeaderNames_js_1 = require_HeaderNames();
var SynthesisRestAdapter = class {
constructor(config, authentication) {
let endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Endpoint, void 0);
if (!endpoint) {
const region = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Region, "westus");
const hostSuffix = ConnectionFactoryBase_js_1.ConnectionFactoryBase.getHostSuffix(region);
endpoint = config.parameters.getProperty(Exports_js_2.PropertyId.SpeechServiceConnection_Host, `https://${region}.tts.speech${hostSuffix}`);
}
this.privUri = `${endpoint}/cognitiveservices/voices/list`;
const options = Exports_js_1.RestConfigBase.requestOptions;
this.privRestAdapter = new Exports_js_1.RestMessageAdapter(options);
this.privAuthentication = authentication;
}
/**
* Sends list voices request to endpoint.
* @function
* @public
* @param connectionId - guid for connectionId
* @returns {Promise<IRestResponse>} rest response to status request
*/
getVoicesList(connectionId) {
this.privRestAdapter.setHeaders(HeaderNames_js_1.HeaderNames.ConnectionId, connectionId);
return this.privAuthentication.fetch(connectionId).then((authInfo) => {
this.privRestAdapter.setHeaders(authInfo.headerName, authInfo.token);
return this.privRestAdapter.request(Exports_js_1.RestRequestType.Get, this.privUri);
});
}
};
exports.SynthesisRestAdapter = SynthesisRestAdapter;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesizerConfig.js
var require_SynthesizerConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesizerConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesizerConfig = exports.SynthesisServiceType = void 0;
var Exports_js_1 = require_Exports7();
var SynthesisServiceType;
(function(SynthesisServiceType2) {
SynthesisServiceType2[SynthesisServiceType2["Standard"] = 0] = "Standard";
SynthesisServiceType2[SynthesisServiceType2["Custom"] = 1] = "Custom";
})(SynthesisServiceType = exports.SynthesisServiceType || (exports.SynthesisServiceType = {}));
var SynthesizerConfig = class {
constructor(speechServiceConfig, parameters) {
this.privSynthesisServiceType = SynthesisServiceType.Standard;
this.avatarEnabled = false;
this.privSpeechServiceConfig = speechServiceConfig ? speechServiceConfig : new Exports_js_1.SpeechServiceConfig(new Exports_js_1.Context(null));
this.privParameters = parameters;
}
get parameters() {
return this.privParameters;
}
get synthesisServiceType() {
return this.privSynthesisServiceType;
}
set synthesisServiceType(value) {
this.privSynthesisServiceType = value;
}
set synthesisVideoSection(value) {
this.privSpeechServiceConfig.Context.synthesis = {
video: value
};
}
get SpeechServiceConfig() {
return this.privSpeechServiceConfig;
}
setContextFromJson(contextJson) {
const context = JSON.parse(contextJson);
if (context.system) {
this.privSpeechServiceConfig.Context.system = context.system;
}
if (context.os) {
this.privSpeechServiceConfig.Context.os = context.os;
}
if (context.audio) {
this.privSpeechServiceConfig.Context.audio = context.audio;
}
if (context.synthesis) {
this.privSpeechServiceConfig.Context.synthesis = context.synthesis;
}
}
};
exports.SynthesizerConfig = SynthesizerConfig;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesisContext.js
var require_SynthesisContext = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SynthesisContext.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SynthesisContext = void 0;
var Exports_js_1 = require_Exports3();
var SynthesisContext = class {
constructor() {
this.privContext = {};
}
/**
* 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.
*/
setSection(sectionName, value) {
this.privContext[sectionName] = value;
}
/**
* Sets the audio output format for synthesis context generation.
* @param format {AudioOutputFormatImpl} the output format
*/
set audioOutputFormat(format2) {
this.privAudioOutputFormat = format2;
}
toJSON() {
return JSON.stringify(this.privContext);
}
setSynthesisSection(speechSynthesizer) {
const synthesisSection = this.buildSynthesisContext(speechSynthesizer);
this.setSection("synthesis", synthesisSection);
}
buildSynthesisContext(speechSynthesizer) {
return {
audio: {
metadataOptions: {
bookmarkEnabled: !!speechSynthesizer?.bookmarkReached,
punctuationBoundaryEnabled: speechSynthesizer?.properties.getProperty(Exports_js_1.PropertyId.SpeechServiceResponse_RequestPunctuationBoundary, !!speechSynthesizer?.wordBoundary),
sentenceBoundaryEnabled: speechSynthesizer?.properties.getProperty(Exports_js_1.PropertyId.SpeechServiceResponse_RequestSentenceBoundary, false),
sessionEndEnabled: true,
visemeEnabled: !!speechSynthesizer?.visemeReceived,
wordBoundaryEnabled: speechSynthesizer?.properties.getProperty(Exports_js_1.PropertyId.SpeechServiceResponse_RequestWordBoundary, !!speechSynthesizer?.wordBoundary)
},
outputFormat: this.privAudioOutputFormat.requestAudioFormatString
},
language: {
autoDetection: speechSynthesizer?.autoDetectSourceLanguage
}
};
}
};
exports.SynthesisContext = SynthesisContext;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeakerRecognitionConfig.js
var require_SpeakerRecognitionConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeakerRecognitionConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerRecognitionConfig = void 0;
var Exports_js_1 = require_Exports7();
var SpeakerRecognitionConfig = class {
constructor(context, parameters) {
this.privContext = context ? context : new Exports_js_1.Context(null);
this.privParameters = parameters;
}
get parameters() {
return this.privParameters;
}
get Context() {
return this.privContext;
}
};
exports.SpeakerRecognitionConfig = SpeakerRecognitionConfig;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeakerServiceRecognizer.js
var require_SpeakerServiceRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeakerServiceRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeakerServiceRecognizer = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports();
var Exports_js_3 = require_Exports3();
var Exports_js_4 = require_Exports7();
var SpeechConnectionMessage_Internal_js_1 = require_SpeechConnectionMessage_Internal();
var SpeakerServiceRecognizer = class extends Exports_js_4.ServiceRecognizerBase {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) {
super(authentication, connectionFactory, audioSource, recognizerConfig, recognizer);
this.privSpeakerRecognizer = recognizer;
this.privSpeakerAudioSource = audioSource;
this.recognizeSpeaker = (model) => this.recognizeSpeakerOnce(model);
this.sendPrePayloadJSONOverride = () => this.noOp();
}
processTypeSpecificMessages(connectionMessage) {
let processed = false;
const resultProps = new Exports_js_3.PropertyCollection();
if (connectionMessage.messageType === Exports_js_2.MessageType.Text) {
resultProps.setProperty(Exports_js_3.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
}
switch (connectionMessage.path.toLowerCase()) {
case "speaker.response":
const response = JSON.parse(connectionMessage.textBody);
let result;
if (response.status.statusCode.toLowerCase() !== "success") {
result = new Exports_js_3.SpeakerRecognitionResult(response, Exports_js_3.ResultReason.Canceled, Exports_js_3.CancellationErrorCode.ServiceError, response.status.reason);
} else {
result = new Exports_js_3.SpeakerRecognitionResult(response, Exports_js_3.ResultReason.RecognizedSpeaker);
}
if (!!this.privResultDeferral) {
this.privResultDeferral.resolve(result);
}
processed = true;
break;
default:
break;
}
const defferal = new Exports_js_2.Deferred();
defferal.resolve(processed);
return defferal.promise;
}
// Cancels recognition.
cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
const properties = new Exports_js_3.PropertyCollection();
properties.setProperty(Exports_js_4.CancellationErrorCodePropertyName, Exports_js_3.CancellationErrorCode[errorCode]);
if (!!this.privResultDeferral) {
const result = new Exports_js_3.SpeakerRecognitionResult({
scenario: this.privSpeakerModel.scenario,
status: { statusCode: error, reason: error }
}, Exports_js_3.ResultReason.Canceled, errorCode, error);
try {
this.privResultDeferral.resolve(result);
} catch (error2) {
this.privResultDeferral.reject(error2);
}
}
}
async recognizeSpeakerOnce(model) {
this.privSpeakerModel = model;
this.voiceProfileType = model.scenario;
if (!this.privResultDeferral) {
this.privResultDeferral = new Exports_js_2.Deferred();
}
this.privRequestSession.startNewRecognition();
this.privRequestSession.listenForServiceTelemetry(this.privSpeakerAudioSource.events);
this.privRecognizerConfig.parameters.setProperty(Exports_js_3.PropertyId.Speech_SessionId, this.privRequestSession.sessionId);
const conPromise = this.connectImpl();
const preAudioPromise = this.sendPreAudioMessages(this.extractSpeakerContext(model));
const node = await this.privSpeakerAudioSource.attach(this.privRequestSession.audioNodeId);
const format2 = await this.privSpeakerAudioSource.format;
const deviceInfo = await this.privSpeakerAudioSource.deviceInfo;
const audioNode = new Exports_js_1.ReplayableAudioNode(node, format2.avgBytesPerSec);
await this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false);
this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo };
try {
await conPromise;
await preAudioPromise;
} catch (err) {
this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.ConnectionFailure, err);
}
const sessionStartEventArgs = new Exports_js_3.SessionEventArgs(this.privRequestSession.sessionId);
if (!!this.privRecognizer.sessionStarted) {
this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs);
}
void this.receiveMessage();
const audioSendPromise = this.sendAudio(audioNode);
audioSendPromise.then(() => {
}, (error) => {
this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.RuntimeError, error);
});
return this.privResultDeferral.promise;
}
async sendPreAudioMessages(context) {
const connection = await this.fetchConnection();
await this.sendSpeakerRecognition(connection, context);
}
async sendSpeakerRecognition(connection, context) {
const speakerContextJson = JSON.stringify(context);
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "speaker.context", this.privRequestSession.requestId, "application/json; charset=utf-8", speakerContextJson));
}
extractSpeakerContext(model) {
return {
features: {
interimResult: "enabled",
progressiveDetection: "disabled"
},
profileIds: model.profileIds,
scenario: model.scenario
};
}
};
exports.SpeakerServiceRecognizer = SpeakerServiceRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/VoiceServiceRecognizer.js
var require_VoiceServiceRecognizer = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/VoiceServiceRecognizer.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceServiceRecognizer = void 0;
var Exports_js_1 = require_Exports4();
var Exports_js_2 = require_Exports();
var Exports_js_3 = require_Exports3();
var Exports_js_4 = require_Exports7();
var SpeechConnectionMessage_Internal_js_1 = require_SpeechConnectionMessage_Internal();
var VoiceServiceRecognizer = class extends Exports_js_4.ServiceRecognizerBase {
constructor(authentication, connectionFactory, audioSource, recognizerConfig, recognizer) {
super(authentication, connectionFactory, audioSource, recognizerConfig, recognizer);
this.privDeferralMap = new Exports_js_2.DeferralMap();
this.privSpeakerAudioSource = audioSource;
this.sendPrePayloadJSONOverride = () => this.noOp();
}
set SpeakerAudioSource(audioSource) {
this.privSpeakerAudioSource = audioSource;
}
processTypeSpecificMessages(connectionMessage) {
let processed = false;
const resultProps = new Exports_js_3.PropertyCollection();
if (connectionMessage.messageType === Exports_js_2.MessageType.Text) {
resultProps.setProperty(Exports_js_3.PropertyId.SpeechServiceResponse_JsonResult, connectionMessage.textBody);
}
switch (connectionMessage.path.toLowerCase()) {
// Profile management response for create, fetch, delete, reset
case "speaker.profiles":
const response = JSON.parse(connectionMessage.textBody);
switch (response.operation.toLowerCase()) {
case "create":
this.handleCreateResponse(response, connectionMessage.requestId);
break;
case "delete":
case "reset":
this.handleResultResponse(response, connectionMessage.requestId);
break;
case "fetch":
const enrollmentResponse2 = JSON.parse(connectionMessage.textBody);
this.handleFetchResponse(enrollmentResponse2, connectionMessage.requestId);
break;
default:
break;
}
processed = true;
break;
// Activation and authorization phrase response
case "speaker.phrases":
const phraseResponse = JSON.parse(connectionMessage.textBody);
this.handlePhrasesResponse(phraseResponse, connectionMessage.requestId);
processed = true;
break;
// Enrollment response
case "speaker.profile.enrollment":
const enrollmentResponse = JSON.parse(connectionMessage.textBody);
const result = new Exports_js_3.VoiceProfileEnrollmentResult(this.enrollmentReasonFrom(!!enrollmentResponse.enrollment ? enrollmentResponse.enrollment.enrollmentStatus : enrollmentResponse.status.statusCode), !!enrollmentResponse.enrollment ? JSON.stringify(enrollmentResponse.enrollment) : void 0, enrollmentResponse.status.reason);
if (!!this.privDeferralMap.getId(connectionMessage.requestId)) {
this.privDeferralMap.complete(connectionMessage.requestId, result);
}
this.privRequestSession.onSpeechEnded();
processed = true;
break;
default:
break;
}
const defferal = new Exports_js_2.Deferred();
defferal.resolve(processed);
return defferal.promise;
}
// Cancels recognition.
cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
const properties = new Exports_js_3.PropertyCollection();
properties.setProperty(Exports_js_4.CancellationErrorCodePropertyName, Exports_js_3.CancellationErrorCode[errorCode]);
const result = new Exports_js_3.VoiceProfileEnrollmentResult(Exports_js_3.ResultReason.Canceled, error, error);
if (!!this.privDeferralMap.getId(requestId)) {
this.privDeferralMap.complete(requestId, result);
}
}
async createProfile(profileType, locale) {
this.voiceProfileType = profileType.toString();
const conPromise = this.connectImpl();
try {
const createProfileDeferral = new Exports_js_2.Deferred();
await conPromise;
await this.sendCreateProfile(createProfileDeferral, profileType, locale);
void this.receiveMessage();
return createProfileDeferral.promise;
} catch (err) {
throw err;
}
}
async resetProfile(profile) {
this.voiceProfileType = profile.profileType.toString();
return this.sendCommonRequest("reset", profile.profileType, profile);
}
async deleteProfile(profile) {
this.voiceProfileType = profile.profileType.toString();
return this.sendCommonRequest("delete", profile.profileType, profile);
}
async retrieveEnrollmentResult(profile) {
this.voiceProfileType = profile.profileType.toString();
this.privExpectedProfileId = profile.profileId;
return this.sendCommonRequest("fetch", profile.profileType, profile);
}
async getAllProfiles(profileType) {
this.voiceProfileType = profileType.toString();
return this.sendCommonRequest("fetch", profileType);
}
async getActivationPhrases(profileType, lang) {
this.voiceProfileType = profileType.toString();
const conPromise = this.connectImpl();
try {
const getPhrasesDeferral = new Exports_js_2.Deferred();
await conPromise;
await this.sendPhrasesRequest(getPhrasesDeferral, profileType, lang);
void this.receiveMessage();
return getPhrasesDeferral.promise;
} catch (err) {
throw err;
}
}
async enrollProfile(profile) {
this.voiceProfileType = profile.profileType.toString();
const enrollmentDeferral = new Exports_js_2.Deferred();
this.privRequestSession.startNewRecognition();
this.privRequestSession.listenForServiceTelemetry(this.privSpeakerAudioSource.events);
this.privRecognizerConfig.parameters.setProperty(Exports_js_3.PropertyId.Speech_SessionId, this.privRequestSession.sessionId);
const conPromise = this.connectImpl();
const preAudioPromise = this.sendPreAudioMessages(profile, enrollmentDeferral);
const node = await this.privSpeakerAudioSource.attach(this.privRequestSession.audioNodeId);
const format2 = await this.privSpeakerAudioSource.format;
const deviceInfo = await this.privSpeakerAudioSource.deviceInfo;
const audioNode = new Exports_js_1.ReplayableAudioNode(node, format2.avgBytesPerSec);
await this.privRequestSession.onAudioSourceAttachCompleted(audioNode, false);
this.privRecognizerConfig.SpeechServiceConfig.Context.audio = { source: deviceInfo };
try {
await conPromise;
await preAudioPromise;
} catch (err) {
this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.ConnectionFailure, err);
}
const sessionStartEventArgs = new Exports_js_3.SessionEventArgs(this.privRequestSession.sessionId);
if (!!this.privRecognizer.sessionStarted) {
this.privRecognizer.sessionStarted(this.privRecognizer, sessionStartEventArgs);
}
void this.receiveMessage();
const audioSendPromise = this.sendAudio(audioNode);
audioSendPromise.then(() => {
}, (error) => {
this.cancelRecognition(this.privRequestSession.sessionId, this.privRequestSession.requestId, Exports_js_3.CancellationReason.Error, Exports_js_3.CancellationErrorCode.RuntimeError, error);
});
return enrollmentDeferral.promise;
}
async sendPreAudioMessages(profile, enrollmentDeferral) {
const connection = await this.fetchConnection();
this.privRequestSession.onSpeechContext();
this.privDeferralMap.add(this.privRequestSession.requestId, enrollmentDeferral);
await this.sendBaseRequest(connection, "enroll", this.scenarioFrom(profile.profileType), profile);
}
async sendPhrasesRequest(getPhrasesDeferral, profileType, locale) {
const connection = await this.fetchConnection();
this.privRequestSession.onSpeechContext();
this.privDeferralMap.add(this.privRequestSession.requestId, getPhrasesDeferral);
const scenario = this.scenarioFrom(profileType);
const profileCreateRequest = {
locale,
scenario
};
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "speaker.profile.phrases", this.privRequestSession.requestId, "application/json; charset=utf-8", JSON.stringify(profileCreateRequest)));
}
async sendCreateProfile(createProfileDeferral, profileType, locale) {
const connection = await this.fetchConnection();
this.privRequestSession.onSpeechContext();
this.privDeferralMap.add(this.privRequestSession.requestId, createProfileDeferral);
const scenario = profileType === Exports_js_3.VoiceProfileType.TextIndependentIdentification ? "TextIndependentIdentification" : profileType === Exports_js_3.VoiceProfileType.TextIndependentVerification ? "TextIndependentVerification" : "TextDependentVerification";
const profileCreateRequest = {
locale,
number: "1",
scenario
};
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, "speaker.profile.create", this.privRequestSession.requestId, "application/json; charset=utf-8", JSON.stringify(profileCreateRequest)));
}
async sendCommonRequest(operation, profileType, profile = void 0) {
const conPromise = this.connectImpl();
try {
const deferral = new Exports_js_2.Deferred();
this.privRequestSession.onSpeechContext();
await conPromise;
const connection = await this.fetchConnection();
this.privDeferralMap.add(this.privRequestSession.requestId, deferral);
await this.sendBaseRequest(connection, operation, this.scenarioFrom(profileType), profile);
void this.receiveMessage();
return deferral.promise;
} catch (err) {
throw err;
}
}
async sendBaseRequest(connection, operation, scenario, profile) {
const profileRequest = {
scenario
};
if (!!profile) {
profileRequest.profileIds = [profile.profileId];
} else {
profileRequest.maxPageSize = -1;
}
return connection.send(new SpeechConnectionMessage_Internal_js_1.SpeechConnectionMessage(Exports_js_2.MessageType.Text, `speaker.profile.${operation}`, this.privRequestSession.requestId, "application/json; charset=utf-8", JSON.stringify(profileRequest)));
}
extractSpeakerContext(model) {
return {
features: {
interimResult: "enabled",
progressiveDetection: "disabled"
},
profileIds: model.profileIds,
scenario: model.scenario
};
}
handlePhrasesResponse(response, requestId) {
if (!!this.privDeferralMap.getId(requestId)) {
if (response.status.statusCode.toLowerCase() !== "success") {
const reason = Exports_js_3.ResultReason.Canceled;
const result = new Exports_js_3.VoiceProfilePhraseResult(reason, response.status.statusCode, response.passPhraseType, []);
this.privDeferralMap.complete(requestId, result);
} else if (!!response.phrases && response.phrases.length > 0) {
const reason = Exports_js_3.ResultReason.EnrollingVoiceProfile;
const result = new Exports_js_3.VoiceProfilePhraseResult(reason, response.status.statusCode, response.passPhraseType, response.phrases);
this.privDeferralMap.complete(requestId, result);
} else {
throw new Error("Voice Profile get activation phrases failed, no phrases received");
}
} else {
throw new Error(`Voice Profile get activation phrases request for requestID ${requestId} not found`);
}
}
handleCreateResponse(response, requestId) {
if (!!response.profiles && response.profiles.length > 0) {
if (!!this.privDeferralMap.getId(requestId)) {
const profileIds = response.profiles.map((profile) => profile.profileId);
this.privDeferralMap.complete(requestId, profileIds);
} else {
throw new Error(`Voice Profile create request for requestID ${requestId} not found`);
}
} else {
throw new Error("Voice Profile create failed, no profile id received");
}
}
handleResultResponse(response, requestId) {
if (!!this.privDeferralMap.getId(requestId)) {
const successReason = response.operation.toLowerCase() === "delete" ? Exports_js_3.ResultReason.DeletedVoiceProfile : Exports_js_3.ResultReason.ResetVoiceProfile;
const reason = response.status.statusCode.toLowerCase() === "success" ? successReason : Exports_js_3.ResultReason.Canceled;
const result = new Exports_js_3.VoiceProfileResult(reason, `statusCode: ${response.status.statusCode}, errorDetails: ${response.status.reason}`);
this.privDeferralMap.complete(requestId, result);
} else {
throw new Error(`Voice Profile create request for requestID ${requestId} not found`);
}
}
handleFetchResponse(enrollmentResponse, requestId) {
if (!!this.privDeferralMap.getId(requestId) && !!enrollmentResponse.profiles[0]) {
if (!!this.privExpectedProfileId && enrollmentResponse.profiles.length === 1 && enrollmentResponse.profiles[0].profileId === this.privExpectedProfileId) {
this.privExpectedProfileId = void 0;
const profileInfo = enrollmentResponse.profiles[0];
const result = new Exports_js_3.VoiceProfileEnrollmentResult(this.enrollmentReasonFrom(profileInfo.enrollmentStatus), JSON.stringify(profileInfo), enrollmentResponse.status.reason);
this.privDeferralMap.complete(requestId, result);
} else if (enrollmentResponse.profiles.length > 0) {
const iProfiles = enrollmentResponse.profiles;
const profileResults = [];
for (const profile of iProfiles) {
profileResults.push(new Exports_js_3.VoiceProfileEnrollmentResult(this.enrollmentReasonFrom(profile.enrollmentStatus), JSON.stringify(profile), enrollmentResponse.status.reason));
}
this.privDeferralMap.complete(requestId, profileResults);
}
} else {
throw new Error(`Voice Profile fetch request for requestID ${requestId} not found`);
}
}
enrollmentReasonFrom(statusCode) {
switch (statusCode.toLowerCase()) {
case "enrolled":
return Exports_js_3.ResultReason.EnrolledVoiceProfile;
case "invalidlocale":
case "invalidphrase":
case "invalidaudioformat":
case "invalidscenario":
case "invalidprofilecount":
case "invalidoperation":
case "audiotooshort":
case "audiotoolong":
case "toomanyenrollments":
case "storageconflict":
case "profilenotfound":
case "incompatibleprofiles":
case "incompleteenrollment":
return Exports_js_3.ResultReason.Canceled;
default:
return Exports_js_3.ResultReason.EnrollingVoiceProfile;
}
}
scenarioFrom(profileType) {
return profileType === Exports_js_3.VoiceProfileType.TextIndependentIdentification ? "TextIndependentIdentification" : profileType === Exports_js_3.VoiceProfileType.TextIndependentVerification ? "TextIndependentVerification" : "TextDependentVerification";
}
};
exports.VoiceServiceRecognizer = VoiceServiceRecognizer;
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechServiceConfig.js
var require_SpeechServiceConfig = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/SpeechServiceConfig.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.type = exports.connectivity = exports.Device = exports.OS = exports.System = exports.Context = exports.SpeechServiceConfig = void 0;
var SpeechServiceConfig = class {
constructor(context) {
this.context = context;
}
serialize() {
return JSON.stringify(this, (key, value) => {
if (value && typeof value === "object" && !Array.isArray(value)) {
const replacement = {};
for (const k in value) {
if (Object.hasOwnProperty.call(value, k)) {
replacement[k && k.charAt(0).toLowerCase() + k.substring(1)] = value[k];
}
}
return replacement;
}
return value;
});
}
get Context() {
return this.context;
}
get Recognition() {
return this.recognition;
}
set Recognition(value) {
this.recognition = value.toLowerCase();
}
};
exports.SpeechServiceConfig = SpeechServiceConfig;
var Context = class {
constructor(os) {
this.system = new System();
this.os = os;
}
};
exports.Context = Context;
var System = class {
constructor() {
const SPEECHSDK_CLIENTSDK_VERSION = "1.45.0";
this.name = "SpeechSDK";
this.version = SPEECHSDK_CLIENTSDK_VERSION;
this.build = "JavaScript";
this.lang = "JavaScript";
}
};
exports.System = System;
var OS = class {
constructor(platform, name, version) {
this.platform = platform;
this.name = name;
this.version = version;
}
};
exports.OS = OS;
var Device = class {
constructor(manufacturer, model, version) {
this.manufacturer = manufacturer;
this.model = model;
this.version = version;
}
};
exports.Device = Device;
var connectivity;
(function(connectivity2) {
connectivity2["Bluetooth"] = "Bluetooth";
connectivity2["Wired"] = "Wired";
connectivity2["WiFi"] = "WiFi";
connectivity2["Cellular"] = "Cellular";
connectivity2["InBuilt"] = "InBuilt";
connectivity2["Unknown"] = "Unknown";
})(connectivity = exports.connectivity || (exports.connectivity = {}));
var type;
(function(type2) {
type2["Phone"] = "Phone";
type2["Speaker"] = "Speaker";
type2["Car"] = "Car";
type2["Headset"] = "Headset";
type2["Thermostat"] = "Thermostat";
type2["Microphones"] = "Microphones";
type2["Deskphone"] = "Deskphone";
type2["RemoteControl"] = "RemoteControl";
type2["Unknown"] = "Unknown";
type2["File"] = "File";
type2["Stream"] = "Stream";
})(type = exports.type || (exports.type = {}));
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Exports.js
var require_Exports7 = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/src/common.speech/Exports.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() {
return m[k];
} });
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AutoDetectSourceLanguagesOpenRangeOptionName = exports.ForceDictationPropertyName = exports.ServicePropertiesPropertyName = exports.CancellationErrorCodePropertyName = exports.OutputFormatPropertyName = exports.SpeechSynthesisAdapter = exports.AvatarSynthesisAdapter = void 0;
__exportStar(require_CognitiveSubscriptionKeyAuthentication(), exports);
__exportStar(require_CognitiveTokenAuthentication(), exports);
__exportStar(require_IAuthentication(), exports);
__exportStar(require_IConnectionFactory(), exports);
__exportStar(require_ISynthesisConnectionFactory(), exports);
__exportStar(require_IntentConnectionFactory(), exports);
__exportStar(require_SpeakerRecognitionConnectionFactory(), exports);
__exportStar(require_RecognitionEvents(), exports);
__exportStar(require_ServiceRecognizerBase(), exports);
__exportStar(require_ConversationServiceRecognizer(), exports);
__exportStar(require_RecognizerConfig(), exports);
__exportStar(require_SpeechServiceInterfaces(), exports);
__exportStar(require_WebsocketMessageFormatter(), exports);
__exportStar(require_SpeechConnectionFactory(), exports);
__exportStar(require_ConversationTranscriberConnectionFactory(), exports);
__exportStar(require_TranscriberConnectionFactory(), exports);
__exportStar(require_TranslationConnectionFactory(), exports);
__exportStar(require_SpeechSynthesisConnectionFactory(), exports);
__exportStar(require_EnumTranslation(), exports);
__exportStar(require_Enums(), exports);
__exportStar(require_TranslationSynthesisEnd(), exports);
__exportStar(require_TranslationHypothesis(), exports);
__exportStar(require_TranslationPhrase(), exports);
__exportStar(require_TranslationServiceRecognizer(), exports);
__exportStar(require_SpeechDetected(), exports);
__exportStar(require_SpeechHypothesis(), exports);
__exportStar(require_SpeechKeyword(), exports);
__exportStar(require_SpeechServiceRecognizer(), exports);
__exportStar(require_ConversationTranscriptionServiceRecognizer(), exports);
__exportStar(require_TranscriptionServiceRecognizer(), exports);
__exportStar(require_DetailedSpeechPhrase(), exports);
__exportStar(require_SimpleSpeechPhrase(), exports);
__exportStar(require_AddedLmIntent(), exports);
__exportStar(require_IntentServiceRecognizer(), exports);
__exportStar(require_IntentResponse(), exports);
__exportStar(require_SpeakerResponse(), exports);
__exportStar(require_RequestSession(), exports);
__exportStar(require_SpeechContext(), exports);
__exportStar(require_DynamicGrammarBuilder(), exports);
__exportStar(require_DialogServiceAdapter(), exports);
__exportStar(require_AgentConfig(), exports);
__exportStar(require_Exports6(), exports);
__exportStar(require_SynthesisAudioMetadata(), exports);
__exportStar(require_SynthesisTurn(), exports);
__exportStar(require_SynthesisAdapterBase(), exports);
var AvatarSynthesisAdapter_js_1 = require_AvatarSynthesisAdapter();
Object.defineProperty(exports, "AvatarSynthesisAdapter", { enumerable: true, get: function() {
return AvatarSynthesisAdapter_js_1.AvatarSynthesisAdapter;
} });
var SpeechSynthesisAdapter_js_1 = require_SpeechSynthesisAdapter();
Object.defineProperty(exports, "SpeechSynthesisAdapter", { enumerable: true, get: function() {
return SpeechSynthesisAdapter_js_1.SpeechSynthesisAdapter;
} });
__exportStar(require_SynthesisRestAdapter(), exports);
__exportStar(require_SynthesizerConfig(), exports);
__exportStar(require_SynthesisContext(), exports);
__exportStar(require_SpeakerRecognitionConfig(), exports);
__exportStar(require_SpeakerServiceRecognizer(), exports);
__exportStar(require_VoiceServiceRecognizer(), exports);
__exportStar(require_SpeechServiceConfig(), exports);
exports.OutputFormatPropertyName = "OutputFormat";
exports.CancellationErrorCodePropertyName = "CancellationErrorCode";
exports.ServicePropertiesPropertyName = "ServiceProperties";
exports.ForceDictationPropertyName = "ForceDictation";
exports.AutoDetectSourceLanguagesOpenRangeOptionName = "UND";
}
});
// ../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/microsoft.cognitiveservices.speech.sdk.js
var require_microsoft_cognitiveservices_speech_sdk = __commonJS({
"../../node_modules/microsoft-cognitiveservices-speech-sdk/distrib/lib/microsoft.cognitiveservices.speech.sdk.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() {
return m[k];
} });
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
var Exports_js_1 = require_Exports7();
void new Exports_js_1.AgentConfig();
__exportStar(require_Exports3(), exports);
}
});
// src/SpeechServices/SpeechToText/createSpeechRecognitionPonyfill.ts
var import_microsoft_cognitiveservices_speech_sdk2 = __toESM(require_microsoft_cognitiveservices_speech_sdk());
// ../../node_modules/valibot/dist/index.js
var store;
// @__NO_SIDE_EFFECTS__
function getGlobalConfig(config2) {
return {
lang: config2?.lang ?? store?.lang,
message: config2?.message,
abortEarly: config2?.abortEarly ?? store?.abortEarly,
abortPipeEarly: config2?.abortPipeEarly ?? store?.abortPipeEarly
};
}
var store2;
// @__NO_SIDE_EFFECTS__
function getGlobalMessage(lang) {
return store2?.get(lang);
}
var store3;
// @__NO_SIDE_EFFECTS__
function getSchemaMessage(lang) {
return store3?.get(lang);
}
var store4;
// @__NO_SIDE_EFFECTS__
function getSpecificMessage(reference, lang) {
return store4?.get(reference)?.get(lang);
}
// @__NO_SIDE_EFFECTS__
function _stringify(input) {
const type = typeof input;
if (type === "string") {
return `"${input}"`;
}
if (type === "number" || type === "bigint" || type === "boolean") {
return `${input}`;
}
if (type === "object" || type === "function") {
return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
}
return type;
}
function _addIssue(context, label, dataset, config2, other) {
const input = other && "input" in other ? other.input : dataset.value;
const expected = other?.expected ?? context.expects ?? null;
const received = other?.received ?? /* @__PURE__ */ _stringify(input);
const issue = {
kind: context.kind,
type: context.type,
input,
expected,
received,
message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
requirement: context.requirement,
path: other?.path,
issues: other?.issues,
lang: config2.lang,
abortEarly: config2.abortEarly,
abortPipeEarly: config2.abortPipeEarly
};
const isSchema = context.kind === "schema";
const message2 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config2.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);
if (message2 !== void 0) {
issue.message = typeof message2 === "function" ? (
// @ts-expect-error
message2(issue)
) : message2;
}
if (isSchema) {
dataset.typed = false;
}
if (dataset.issues) {
dataset.issues.push(issue);
} else {
dataset.issues = [issue];
}
}
// @__NO_SIDE_EFFECTS__
function _getStandardProps(context) {
return {
version: 1,
vendor: "valibot",
validate(value2) {
return context["~run"]({ value: value2 }, /* @__PURE__ */ getGlobalConfig());
}
};
}
// @__NO_SIDE_EFFECTS__
function _joinExpects(values2, separator) {
const list = [...new Set(values2)];
if (list.length > 1) {
return `(${list.join(` ${separator} `)})`;
}
return list[0] ?? "never";
}
var ValiError = class extends Error {
/**
* Creates a Valibot error with useful information.
*
* @param issues The error issues.
*/
constructor(issues) {
super(issues[0].message);
this.name = "ValiError";
this.issues = issues;
}
};
var EMOJI_REGEX = (
// eslint-disable-next-line redos-detector/no-unsafe-regex, regexp/no-dupe-disjunctions -- false positives
new RegExp("^(?:[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}))*)+$", "u")
);
// @__NO_SIDE_EFFECTS__
function maxValue(requirement, message2) {
return {
kind: "validation",
type: "max_value",
reference: maxValue,
async: false,
expects: `<=${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,
requirement,
message: message2,
"~run"(dataset, config2) {
if (dataset.typed && !(dataset.value <= this.requirement)) {
_addIssue(this, "value", dataset, config2, {
received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value)
});
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function minValue(requirement, message2) {
return {
kind: "validation",
type: "min_value",
reference: minValue,
async: false,
expects: `>=${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,
requirement,
message: message2,
"~run"(dataset, config2) {
if (dataset.typed && !(dataset.value >= this.requirement)) {
_addIssue(this, "value", dataset, config2, {
received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value)
});
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function readonly() {
return {
kind: "transformation",
type: "readonly",
reference: readonly,
async: false,
"~run"(dataset) {
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function transform(operation) {
return {
kind: "transformation",
type: "transform",
reference: transform,
async: false,
operation,
"~run"(dataset) {
dataset.value = this.operation(dataset.value);
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function getFallback(schema, dataset, config2) {
return typeof schema.fallback === "function" ? (
// @ts-expect-error
schema.fallback(dataset, config2)
) : (
// @ts-expect-error
schema.fallback
);
}
// @__NO_SIDE_EFFECTS__
function getDefault(schema, dataset, config2) {
return typeof schema.default === "function" ? (
// @ts-expect-error
schema.default(dataset, config2)
) : (
// @ts-expect-error
schema.default
);
}
// @__NO_SIDE_EFFECTS__
function array(item, message2) {
return {
kind: "schema",
type: "array",
reference: array,
expects: "Array",
async: false,
item,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
const input = dataset.value;
if (Array.isArray(input)) {
dataset.typed = true;
dataset.value = [];
for (let key = 0; key < input.length; key++) {
const value2 = input[key];
const itemDataset = this.item["~run"]({ value: value2 }, config2);
if (itemDataset.issues) {
const pathItem = {
type: "array",
origin: "value",
input,
key,
value: value2
};
for (const issue of itemDataset.issues) {
if (issue.path) {
issue.path.unshift(pathItem);
} else {
issue.path = [pathItem];
}
dataset.issues?.push(issue);
}
if (!dataset.issues) {
dataset.issues = itemDataset.issues;
}
if (config2.abortEarly) {
dataset.typed = false;
break;
}
}
if (!itemDataset.typed) {
dataset.typed = false;
}
dataset.value.push(itemDataset.value);
}
} else {
_addIssue(this, "type", dataset, config2);
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function boolean(message2) {
return {
kind: "schema",
type: "boolean",
reference: boolean,
expects: "boolean",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (typeof dataset.value === "boolean") {
dataset.typed = true;
} else {
_addIssue(this, "type", dataset, config2);
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function enum_(enum__, message2) {
const options = [];
for (const key in enum__) {
if (`${+key}` !== key || typeof enum__[key] !== "string" || !Object.is(enum__[enum__[key]], +key)) {
options.push(enum__[key]);
}
}
return {
kind: "schema",
type: "enum",
reference: enum_,
expects: /* @__PURE__ */ _joinExpects(options.map(_stringify), "|"),
async: false,
enum: enum__,
options,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (this.options.includes(dataset.value)) {
dataset.typed = true;
} else {
_addIssue(this, "type", dataset, config2);
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function function_(message2) {
return {
kind: "schema",
type: "function",
reference: function_,
expects: "Function",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (typeof dataset.value === "function") {
dataset.typed = true;
} else {
_addIssue(this, "type", dataset, config2);
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function _merge(value1, value2) {
if (typeof value1 === typeof value2) {
if (value1 === value2 || value1 instanceof Date && value2 instanceof Date && +value1 === +value2) {
return { value: value1 };
}
if (value1 && value2 && value1.constructor === Object && value2.constructor === Object) {
for (const key in value2) {
if (key in value1) {
const dataset = /* @__PURE__ */ _merge(value1[key], value2[key]);
if (dataset.issue) {
return dataset;
}
value1[key] = dataset.value;
} else {
value1[key] = value2[key];
}
}
return { value: value1 };
}
if (Array.isArray(value1) && Array.isArray(value2)) {
if (value1.length === value2.length) {
for (let index = 0; index < value1.length; index++) {
const dataset = /* @__PURE__ */ _merge(value1[index], value2[index]);
if (dataset.issue) {
return dataset;
}
value1[index] = dataset.value;
}
return { value: value1 };
}
}
}
return { issue: true };
}
// @__NO_SIDE_EFFECTS__
function intersect(options, message2) {
return {
kind: "schema",
type: "intersect",
reference: intersect,
expects: /* @__PURE__ */ _joinExpects(
options.map((option) => option.expects),
"&"
),
async: false,
options,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (this.options.length) {
const input = dataset.value;
let outputs;
dataset.typed = true;
for (const schema of this.options) {
const optionDataset = schema["~run"]({ value: input }, config2);
if (optionDataset.issues) {
if (dataset.issues) {
dataset.issues.push(...optionDataset.issues);
} else {
dataset.issues = optionDataset.issues;
}
if (config2.abortEarly) {
dataset.typed = false;
break;
}
}
if (!optionDataset.typed) {
dataset.typed = false;
}
if (dataset.typed) {
if (outputs) {
outputs.push(optionDataset.value);
} else {
outputs = [optionDataset.value];
}
}
}
if (dataset.typed) {
dataset.value = outputs[0];
for (let index = 1; index < outputs.length; index++) {
const mergeDataset = /* @__PURE__ */ _merge(dataset.value, outputs[index]);
if (mergeDataset.issue) {
_addIssue(this, "type", dataset, config2, {
received: "unknown"
});
break;
}
dataset.value = mergeDataset.value;
}
}
} else {
_addIssue(this, "type", dataset, config2);
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function number(message2) {
return {
kind: "schema",
type: "number",
reference: number,
expects: "number",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (typeof dataset.value === "number" && !isNaN(dataset.value)) {
dataset.typed = true;
} else {
_addIssue(this, "type", dataset, config2);
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function object(entries2, message2) {
return {
kind: "schema",
type: "object",
reference: object,
expects: "Object",
async: false,
entries: entries2,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
const input = dataset.value;
if (input && typeof input === "object") {
dataset.typed = true;
dataset.value = {};
for (const key in this.entries) {
const valueSchema = this.entries[key];
if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && // @ts-expect-error
valueSchema.default !== void 0) {
const value2 = key in input ? (
// @ts-expect-error
input[key]
) : /* @__PURE__ */ getDefault(valueSchema);
const valueDataset = valueSchema["~run"]({ value: value2 }, config2);
if (valueDataset.issues) {
const pathItem = {
type: "object",
origin: "value",
input,
key,
value: value2
};
for (const issue of valueDataset.issues) {
if (issue.path) {
issue.path.unshift(pathItem);
} else {
issue.path = [pathItem];
}
dataset.issues?.push(issue);
}
if (!dataset.issues) {
dataset.issues = valueDataset.issues;
}
if (config2.abortEarly) {
dataset.typed = false;
break;
}
}
if (!valueDataset.typed) {
dataset.typed = false;
}
dataset.value[key] = valueDataset.value;
} else if (valueSchema.fallback !== void 0) {
dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
} else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
_addIssue(this, "key", dataset, config2, {
input: void 0,
expected: `"${key}"`,
path: [
{
type: "object",
origin: "key",
input,
key,
// @ts-expect-error
value: input[key]
}
]
});
if (config2.abortEarly) {
break;
}
}
}
} else {
_addIssue(this, "type", dataset, config2);
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function optional(wrapped, default_) {
return {
kind: "schema",
type: "optional",
reference: optional,
expects: `(${wrapped.expects} | undefined)`,
async: false,
wrapped,
default: default_,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (dataset.value === void 0) {
if (this.default !== void 0) {
dataset.value = /* @__PURE__ */ getDefault(this, dataset, config2);
}
if (dataset.value === void 0) {
dataset.typed = true;
return dataset;
}
}
return this.wrapped["~run"](dataset, config2);
}
};
}
// @__NO_SIDE_EFFECTS__
function string(message2) {
return {
kind: "schema",
type: "string",
reference: string,
expects: "string",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (typeof dataset.value === "string") {
dataset.typed = true;
} else {
_addIssue(this, "type", dataset, config2);
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function undefined_(message2) {
return {
kind: "schema",
type: "undefined",
reference: undefined_,
expects: "undefined",
async: false,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
if (dataset.value === void 0) {
dataset.typed = true;
} else {
_addIssue(this, "type", dataset, config2);
}
return dataset;
}
};
}
// @__NO_SIDE_EFFECTS__
function _subIssues(datasets) {
let issues;
if (datasets) {
for (const dataset of datasets) {
if (issues) {
issues.push(...dataset.issues);
} else {
issues = dataset.issues;
}
}
}
return issues;
}
// @__NO_SIDE_EFFECTS__
function union(options, message2) {
return {
kind: "schema",
type: "union",
reference: union,
expects: /* @__PURE__ */ _joinExpects(
options.map((option) => option.expects),
"|"
),
async: false,
options,
message: message2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
let validDataset;
let typedDatasets;
let untypedDatasets;
for (const schema of this.options) {
const optionDataset = schema["~run"]({ value: dataset.value }, config2);
if (optionDataset.typed) {
if (optionDataset.issues) {
if (typedDatasets) {
typedDatasets.push(optionDataset);
} else {
typedDatasets = [optionDataset];
}
} else {
validDataset = optionDataset;
break;
}
} else {
if (untypedDatasets) {
untypedDatasets.push(optionDataset);
} else {
untypedDatasets = [optionDataset];
}
}
}
if (validDataset) {
return validDataset;
}
if (typedDatasets) {
if (typedDatasets.length === 1) {
return typedDatasets[0];
}
_addIssue(this, "type", dataset, config2, {
issues: /* @__PURE__ */ _subIssues(typedDatasets)
});
dataset.typed = true;
} else if (untypedDatasets?.length === 1) {
return untypedDatasets[0];
} else {
_addIssue(this, "type", dataset, config2, {
issues: /* @__PURE__ */ _subIssues(untypedDatasets)
});
}
return dataset;
}
};
}
function parse(schema, input, config2) {
const dataset = schema["~run"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config2));
if (dataset.issues) {
throw new ValiError(dataset.issues);
}
return dataset.value;
}
// @__NO_SIDE_EFFECTS__
function pipe(...pipe2) {
return {
...pipe2[0],
pipe: pipe2,
get "~standard"() {
return /* @__PURE__ */ _getStandardProps(this);
},
"~run"(dataset, config2) {
for (const item of pipe2) {
if (item.kind !== "metadata") {
if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
dataset.typed = false;
break;
}
if (!dataset.issues || !config2.abortEarly && !config2.abortPipeEarly) {
dataset = item["~run"](dataset, config2);
}
}
}
return dataset;
}
};
}
// src/SpeechServices/resolveFunctionOrReturnValue.ts
function isFunction(value) {
return typeof value === "function";
}
function resolveFunctionOrReturnValue(fnOrValue) {
return isFunction(fnOrValue) ? fnOrValue() : fnOrValue;
}
// src/SpeechServices/SpeechSDK.ts
var import_microsoft_cognitiveservices_speech_sdk = __toESM(require_microsoft_cognitiveservices_speech_sdk());
var SpeechSDK_default = {
AudioConfig: import_microsoft_cognitiveservices_speech_sdk.AudioConfig,
OutputFormat: import_microsoft_cognitiveservices_speech_sdk.OutputFormat,
ResultReason: import_microsoft_cognitiveservices_speech_sdk.ResultReason,
SpeechConfig: import_microsoft_cognitiveservices_speech_sdk.SpeechConfig,
SpeechRecognizer: import_microsoft_cognitiveservices_speech_sdk.SpeechRecognizer
};
// src/SpeechServices/SpeechToText/validation/credentialsSchema.ts
var credentialsSchema = pipe(
intersect([
union(
[
object({
authorizationToken: string(),
subscriptionKey: optional(undefined_('"subscriptionKey" must be unset when "authorizationToken" is set.'))
}),
object({
authorizationToken: optional(undefined_('"authorizationToken" must be unset when "subscriptionKey" is set.')),
subscriptionKey: string()
})
],
'The object must either have either "authorizationToken" or "subscriptionKey" set, but not both.'
),
union(
[
object({
customVoiceHostname: optional(undefined_('"customVoiceHostname" must be unest when "region" is set.')),
region: string(),
speechRecognitionHostname: optional(
undefined_('"speechRecognitionHostname" must be unest when "region" is set.')
),
speechSynthesisHostname: optional(undefined_('"speechSynthesisHostname" must be unest when "region" is set.'))
}),
object({
customVoiceHostname: optional(union([string(), undefined_()])),
region: optional(undefined_('"region" must be unset when "*Hostname" is set.')),
speechRecognitionHostname: string(),
speechSynthesisHostname: string()
})
],
'The object must either have either "region" or "*Hostname" set, but not both.'
)
]),
readonly()
);
var credentialsSchema_default = credentialsSchema;
// src/SpeechServices/SpeechToText/validation/enableTelemetrySchema.ts
var enableTelemetrySchema = optional(boolean());
var enableTelemetrySchema_default = enableTelemetrySchema;
// src/SpeechServices/SpeechToText/validation/initialSilenceTimeoutSchema.ts
var initialSilenceTimeoutSchema = optional(pipe(number(), minValue(1), maxValue(6e4)));
var initialSilenceTimeoutSchema_default = initialSilenceTimeoutSchema;
// src/SpeechServices/SpeechToText/validation/looseEventsSchema.ts
var looseEventsSchema = optional(boolean(), false);
var looseEventsSchema_default = looseEventsSchema;
// src/SpeechServices/SpeechToText/validation/referenceGrammarsSchema.ts
var referenceGrammarsSchema = pipe(
optional(array(string()), []),
// any(),
// array(string()),
// transform<string[], readonly string[]>(value => (Object.isFrozen(value) ? value : Object.freeze([...value])))
transform((value) => Object.isFrozen(value) ? value : Object.freeze([...value]))
);
var referenceGrammarsSchema_default = referenceGrammarsSchema;
// src/SpeechServices/SpeechToText/validation/speechRecognitionEndpointIdSchema.ts
var speechRecognitionEndpointIdSchema = optional(string());
var speechRecognitionEndpointIdSchema_default = speechRecognitionEndpointIdSchema;
// src/SpeechServices/SpeechToText/validation/textNormalizationSchema.ts
var textNormalizationSchema = optional(
enum_({
display: "display",
itn: "itn",
lexical: "lexical",
maskeditn: "maskeditn"
}),
"display"
);
var textNormalizationSchema_default = textNormalizationSchema;
// src/SpeechServices/patchOptions.ts
var { AudioConfig: AudioConfig2 } = SpeechSDK_default;
var shouldWarnOnSubscriptionKey = true;
function patchOptions(init) {
const {
audioConfig,
credentials,
enableTelemetry,
initialSilenceTimeout,
looseEvent,
referenceGrammars,
speechRecognitionEndpointId,
textNormalization
} = init;
let { looseEvents } = init;
if (typeof looseEvent !== "undefined") {
console.warn('web-speech-cognitive-services: The option "looseEvent" should be named as "looseEvents".');
looseEvents = looseEvent;
}
return Object.freeze({
audioConfig: audioConfig || AudioConfig2.fromDefaultMicrophoneInput(),
// We set telemetry to true to honor the default telemetry settings of Speech SDK
// https://github.com/Microsoft/cognitive-services-speech-sdk-js#data--telemetry
enableTelemetry: parse(enableTelemetrySchema_default, enableTelemetry),
fetchCredentials: async () => {
const parsedCredentials = parse(credentialsSchema_default, await resolveFunctionOrReturnValue(credentials));
if (shouldWarnOnSubscriptionKey && parsedCredentials.subscriptionKey) {
console.warn(
"web-speech-cognitive-services: In production environment, subscription key should not be used, authorization token should be used instead."
);
shouldWarnOnSubscriptionKey = false;
}
return parsedCredentials;
},
initialSilenceTimeout: parse(initialSilenceTimeoutSchema_default, initialSilenceTimeout),
looseEvents: parse(looseEventsSchema_default, looseEvents),
referenceGrammars: parse(referenceGrammarsSchema_default, referenceGrammars),
speechRecognitionEndpointId: parse(speechRecognitionEndpointIdSchema_default, speechRecognitionEndpointId),
textNormalization: parse(textNormalizationSchema_default, textNormalization)
});
}
// ../../node_modules/p-defer/index.js
function pDefer() {
const deferred = {};
deferred.promise = new Promise((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
}
// src/Util/createPromiseQueue.js
function createPromiseQueue_default() {
let shiftDeferred;
const queue = [];
const push = (value) => {
if (shiftDeferred) {
const { resolve } = shiftDeferred;
shiftDeferred = null;
resolve(value);
} else {
queue.push(value);
}
};
const shift = () => {
if (queue.length) {
return Promise.resolve(queue.shift());
}
return (shiftDeferred || (shiftDeferred = pDefer())).promise;
};
return {
push,
shift
};
}
// src/SpeechServices/SpeechToText/SpeechRecognitionAlternative.ts
var SpeechRecognitionAlternative = class {
constructor({ confidence, transcript }) {
this.#confidence = confidence;
this.#transcript = transcript;
}
#confidence;
#transcript;
get confidence() {
return this.#confidence;
}
get transcript() {
return this.#transcript;
}
};
// src/SpeechServices/SpeechToText/private/FakeArray.ts
var FakeArray = class {
constructor(array2) {
if (!array2) {
throw new Error("array must be set.");
}
this.#array = array2;
for (const key in array2) {
Object.defineProperty(this, key, {
enumerable: true,
get() {
return array2[key];
}
});
}
}
#array;
[Symbol.iterator]() {
return this.#array[Symbol.iterator]();
}
get length() {
return this.#array.length;
}
};
// src/SpeechServices/SpeechToText/SpeechRecognitionResult.ts
var SpeechRecognitionResult = class extends FakeArray {
constructor(init) {
super(init.results);
this.#isFinal = init.isFinal;
}
#isFinal;
get isFinal() {
return this.#isFinal;
}
};
// src/SpeechServices/SpeechToText/cognitiveServiceEventResultToWebSpeechRecognitionResult.ts
var {
ResultReason: { RecognizingSpeech, RecognizedSpeech }
} = SpeechSDK_default;
function cognitiveServiceEventResultToWebSpeechRecognitionResult_default(result, init) {
const { maxAlternatives = Infinity, textNormalization = "display" } = init || {};
const json = typeof result.json === "string" ? JSON.parse(result.json) : result.json;
if (result.reason === RecognizingSpeech || result.reason === RecognizedSpeech && !json.NBest) {
return new SpeechRecognitionResult({
isFinal: result.reason === RecognizedSpeech,
results: [
new SpeechRecognitionAlternative({
confidence: 0.5,
transcript: result.text
})
]
});
} else if (result.reason === RecognizedSpeech) {
return new SpeechRecognitionResult({
isFinal: true,
results: (json.NBest || []).slice(0, maxAlternatives).map(
({ Confidence: confidence, Display: display, ITN: itn, Lexical: lexical, MaskedITN: maskedITN }) => new SpeechRecognitionAlternative({
confidence,
transcript: textNormalization === "itn" ? itn : textNormalization === "lexical" ? lexical : textNormalization === "maskeditn" ? maskedITN : display
})
)
});
}
return new SpeechRecognitionResult({ isFinal: false, results: [] });
}
// src/SpeechServices/SpeechToText/cognitiveServicesAsyncToPromise.ts
function cognitiveServicesAsyncToPromise(fn, context = void 0) {
return (...args) => (
// eslint-disable-next-line prefer-spread
new Promise((resolve, reject) => fn.apply(context, [...args, resolve, reject]))
);
}
// src/SpeechServices/SpeechToText/private/EventListenerMap.ts
var EventListenerMap = class {
constructor(eventTarget) {
this.#eventTarget = eventTarget;
this.#propertyMap = {};
}
#eventTarget;
#propertyMap;
getProperty(name) {
return this.#propertyMap[name];
}
setProperty(name, value) {
const existing = this.#propertyMap[name];
existing && this.#eventTarget.removeEventListener(name, existing);
if (value) {
this.#eventTarget.addEventListener(name, value);
}
this.#propertyMap[name] = value;
}
};
// src/SpeechServices/SpeechToText/private/prepareAudioConfig.ts
var import_AudioSourceEvents = __toESM(require_AudioSourceEvents());
// src/SpeechServices/SpeechToText/private/averageAmplitude.ts
function averageAmplitude(arrayBuffer) {
const array2 = Array.from(new Int16Array(arrayBuffer));
return array2.reduce((averageAmplitude2, amplitude) => averageAmplitude2 + Math.abs(amplitude), 0) / array2.length;
}
// src/SpeechServices/SpeechToText/private/prepareAudioConfig.ts
function prepareAudioConfig(audioConfig) {
const audioConfigImpl = audioConfig;
const originalAttach = audioConfigImpl.attach;
const boundOriginalAttach = audioConfigImpl.attach.bind(audioConfigImpl);
let firstChunk = false;
let muted = false;
audioConfigImpl.attach = async () => {
const reader = await boundOriginalAttach("");
return {
...reader,
read: async () => {
const chunk = await reader.read();
if (!firstChunk && averageAmplitude(chunk.buffer) > 150) {
audioConfigImpl.events.onEvent(new import_AudioSourceEvents.AudioSourceEvent("FirstAudibleChunk", ""));
firstChunk = true;
}
if (muted) {
return { buffer: new ArrayBuffer(0), isEnd: true, timeReceived: Date.now() };
}
return chunk;
}
};
};
return {
audioConfig,
pause: () => {
muted = true;
},
unprepare: () => {
audioConfigImpl.attach = originalAttach;
}
};
}
// src/SpeechServices/SpeechToText/private/serializeRecognitionResult.ts
function serializeRecognitionResult({
duration,
errorDetails,
json,
offset,
properties,
reason,
resultId,
text
}) {
return Object.freeze({
duration,
errorDetails,
json: json && JSON.parse(json),
offset,
properties,
reason,
resultId,
text
});
}
// src/SpeechServices/SpeechToText/SpeechGrammarList.ts
var SpeechGrammarList = class {
constructor() {
this.#phrases = [];
}
addFromString() {
throw new Error("JSGF is not supported");
}
addFromURI() {
throw new Error("JSGF is not supported");
}
item() {
throw new Error("JSGF is not supported");
}
get length() {
throw new Error("JSGF is not supported");
}
#phrases;
get phrases() {
return this.#phrases;
}
set phrases(value) {
if (Array.isArray(value)) {
this.#phrases = Object.freeze([...value]);
} else if (typeof value === "string") {
this.#phrases = Object.freeze([value]);
} else {
throw new Error(`The provided value is not an array or of type 'string'`);
}
}
};
// src/SpeechServices/SpeechToText/SpeechRecognitionErrorEvent.ts
var SpeechRecognitionErrorEvent = class extends Event {
constructor(type, { error, message }) {
super(type);
this.#error = error;
this.#message = message;
}
#error;
#message;
get error() {
return this.#error;
}
get message() {
return this.#message;
}
get type() {
return "error";
}
};
// src/SpeechServices/SpeechToText/SpeechRecognitionResultList.ts
var SpeechRecognitionResultList = class extends FakeArray {
constructor(result) {
super(result);
}
};
// src/SpeechServices/SpeechToText/SpeechRecognitionEvent.ts
var SpeechRecognitionEvent = class extends Event {
constructor(type, { data, resultIndex, results } = {}) {
super(type);
this.#data = data;
this.#resultIndex = resultIndex;
this.#results = results || new SpeechRecognitionResultList([]);
}
#data;
// TODO: "resultIndex" should be set.
#resultIndex;
#results;
get data() {
return this.#data;
}
get resultIndex() {
return this.#resultIndex;
}
get results() {
return this.#results;
}
get type() {
return super.type;
}
};
// src/SpeechServices/SpeechToText/createSpeechRecognitionPonyfillFromRecognizer.ts
var { ResultReason: ResultReason2, SpeechRecognizer: SpeechRecognizer2 } = SpeechSDK_default;
var enableTelemetrySchema2 = union([boolean(), undefined_()]);
function createSpeechRecognitionPonyfillFromRecognizer({
createRecognizer,
enableTelemetry,
looseEvents,
referenceGrammars,
textNormalization
}) {
createRecognizer = parse(function_(), createRecognizer);
enableTelemetry = parse(enableTelemetrySchema2, enableTelemetry);
looseEvents = parse(boolean(), looseEvents);
referenceGrammars = parse(referenceGrammarsSchema_default, referenceGrammars);
textNormalization = parse(textNormalizationSchema_default, textNormalization);
typeof enableTelemetry !== "undefined" && SpeechRecognizer2.enableTelemetry(enableTelemetry);
class SpeechRecognition extends EventTarget {
#continuous = false;
#eventListenerMap = new EventListenerMap(this);
#grammars = new SpeechGrammarList();
#interimResults = false;
#lang = typeof window !== "undefined" ? window.document.documentElement.getAttribute("lang") || window.navigator.language : "en-US";
// eslint-disable-next-line no-magic-numbers
#maxAlternatives = 1;
emitCognitiveServices(type, event) {
this.dispatchEvent(
new SpeechRecognitionEvent("cognitiveservices", {
data: {
...event,
type
}
})
);
}
get continuous() {
return this.#continuous;
}
set continuous(value) {
this.#continuous = value;
}
get grammars() {
return this.#grammars;
}
set grammars(value) {
if (value instanceof SpeechGrammarList) {
this.#grammars = value;
} else {
throw new Error(`The provided value is not of type 'SpeechGrammarList'`);
}
}
get interimResults() {
return this.#interimResults;
}
set interimResults(value) {
this.#interimResults = value;
}
get maxAlternatives() {
return this.#maxAlternatives;
}
set maxAlternatives(value) {
this.#maxAlternatives = value;
}
get lang() {
return this.#lang;
}
set lang(value) {
this.#lang = value;
}
get onaudioend() {
return this.#eventListenerMap.getProperty("audioend");
}
set onaudioend(value) {
this.#eventListenerMap.setProperty("audioend", value);
}
/** @type { ((event: SpeechRecognitionEvent<'audiostart'>) => void) | undefined } */
get onaudiostart() {
return this.#eventListenerMap.getProperty("audiostart");
}
set onaudiostart(value) {
this.#eventListenerMap.setProperty("audiostart", value);
}
/** @type { ((event: SpeechRecognitionEvent<'cognitiveservices'>) => void) | undefined } */
get oncognitiveservices() {
return this.#eventListenerMap.getProperty("cognitiveservices");
}
set oncognitiveservices(value) {
this.#eventListenerMap.setProperty("cognitiveservices", value);
}
/** @type { ((event: SpeechRecognitionEvent<'end'>) => void) | undefined } */
get onend() {
return this.#eventListenerMap.getProperty("end");
}
set onend(value) {
this.#eventListenerMap.setProperty("end", value);
}
/** @type { ((event: SpeechRecognitionErrorEvent) => void) | undefined } */
get onerror() {
return this.#eventListenerMap.getProperty("error");
}
set onerror(value) {
this.#eventListenerMap.setProperty("error", value);
}
/** @type { ((event: SpeechRecognitionEvent<'result'>) => void) | undefined } */
get onresult() {
return this.#eventListenerMap.getProperty("result");
}
set onresult(value) {
this.#eventListenerMap.setProperty("result", value);
}
/** @type { ((event: SpeechRecognitionEvent<'soundend'>) => void) | undefined } */
get onsoundend() {
return this.#eventListenerMap.getProperty("soundend");
}
set onsoundend(value) {
this.#eventListenerMap.setProperty("soundend", value);
}
/** @type { ((event: SpeechRecognitionEvent<'soundstart'>) => void) | undefined } */
get onsoundstart() {
return this.#eventListenerMap.getProperty("soundstart");
}
set onsoundstart(value) {
this.#eventListenerMap.setProperty("soundstart", value);
}
/** @type { ((event: SpeechRecognitionEvent<'speechend'>) => void) | undefined } */
get onspeechend() {
return this.#eventListenerMap.getProperty("speechend");
}
set onspeechend(value) {
this.#eventListenerMap.setProperty("speechend", value);
}
/** @type { ((event: SpeechRecognitionEvent<'speechstart'>) => void) | undefined } */
get onspeechstart() {
return this.#eventListenerMap.getProperty("speechstart");
}
set onspeechstart(value) {
this.#eventListenerMap.setProperty("speechstart", value);
}
/** @type { ((event: SpeechRecognitionEvent<'start'>) => void) | undefined } */
get onstart() {
return this.#eventListenerMap.getProperty("start");
}
set onstart(value) {
this.#eventListenerMap.setProperty("start", value);
}
abort;
stop;
start() {
this._startOnce().catch((err) => {
this.dispatchEvent(
new SpeechRecognitionErrorEvent("error", { error: err, message: err && (err.stack || err.message) })
);
});
}
async _startOnce() {
const recognizer = await createRecognizer(this.lang);
const { pause, unprepare } = prepareAudioConfig(recognizer["audioConfig"]);
try {
const queue = createPromiseQueue_default();
let soundStarted;
let speechStarted;
let stopping;
const { detach: detachAudioConfigEvent } = recognizer["audioConfig"].events.attach(
(event) => {
const { name } = event;
if (name === "AudioSourceReadyEvent") {
queue.push({ audioSourceReady: {} });
} else if (name === "AudioSourceOffEvent") {
queue.push({ audioSourceOff: {} });
} else if (name === "FirstAudibleChunk") {
queue.push({ firstAudibleChunk: {} });
}
}
);
recognizer.canceled = (_, { errorDetails, offset, reason, sessionId }) => {
queue.push({
canceled: {
errorDetails,
offset,
reason,
sessionId
}
});
};
recognizer.recognized = (_, { offset, result, sessionId }) => {
queue.push({
recognized: {
offset,
result: serializeRecognitionResult(result),
sessionId
}
});
};
recognizer.recognizing = (_, { offset, result, sessionId }) => {
queue.push({
recognizing: {
offset,
result: serializeRecognitionResult(result),
sessionId
}
});
};
recognizer.sessionStarted = (_, { sessionId }) => {
queue.push({ sessionStarted: { sessionId } });
};
recognizer.sessionStopped = (_, { sessionId }) => {
queue.push({ sessionStopped: { sessionId } });
};
recognizer.speechStartDetected = (_, { offset, sessionId }) => {
queue.push({ speechStartDetected: { offset, sessionId } });
};
recognizer.speechEndDetected = (_, { sessionId }) => {
queue.push({ speechEndDetected: { sessionId } });
};
const { phrases } = this.grammars;
const { dynamicGrammar } = recognizer["privReco"];
referenceGrammars && referenceGrammars.length && dynamicGrammar.addReferenceGrammar([...referenceGrammars]);
phrases && phrases.length && dynamicGrammar.addPhrase([...phrases]);
await cognitiveServicesAsyncToPromise(recognizer.startContinuousRecognitionAsync, recognizer)();
if (typeof recognizer.stopContinuousRecognitionAsync === "function") {
this.abort = () => queue.push({ abort: {} });
this.stop = () => queue.push({ stop: {} });
} else {
this.abort = this.stop = void 0;
}
let audioStarted;
let finalEvent = void 0;
let finalizedResults = [];
for (let loop = 0; !stopping || audioStarted; loop++) {
const event = await queue.shift();
const {
abort,
audioSourceOff,
audioSourceReady,
canceled,
firstAudibleChunk,
recognized,
recognizing,
stop
} = event;
Object.keys(event).forEach((name) => this.emitCognitiveServices(name, event[name]));
const errorMessage = canceled && canceled.errorDetails;
if (/Permission\sdenied/u.test(errorMessage || "")) {
finalEvent = new SpeechRecognitionErrorEvent("error", { error: "not-allowed" });
break;
}
if (!loop) {
this.dispatchEvent(new SpeechRecognitionEvent("start"));
}
if (errorMessage) {
if (/1006/u.test(errorMessage)) {
if (!audioStarted) {
this.dispatchEvent(new SpeechRecognitionEvent("audiostart"));
this.dispatchEvent(new SpeechRecognitionEvent("audioend"));
}
finalEvent = new SpeechRecognitionErrorEvent("error", { error: "network" });
} else {
finalEvent = new SpeechRecognitionErrorEvent("error", { error: "unknown" });
}
break;
} else if (abort || stop) {
if (abort) {
finalEvent = new SpeechRecognitionErrorEvent("error", { error: "aborted" });
stopping = "abort";
} else {
pause();
stopping = "stop";
}
if (abort && recognizer.stopContinuousRecognitionAsync) {
await cognitiveServicesAsyncToPromise(recognizer.stopContinuousRecognitionAsync, recognizer)();
}
} else if (audioSourceReady) {
this.dispatchEvent(new SpeechRecognitionEvent("audiostart"));
audioStarted = true;
} else if (firstAudibleChunk) {
this.dispatchEvent(new SpeechRecognitionEvent("soundstart"));
soundStarted = true;
} else if (audioSourceOff) {
speechStarted && this.dispatchEvent(new SpeechRecognitionEvent("speechend"));
soundStarted && this.dispatchEvent(new SpeechRecognitionEvent("soundend"));
audioStarted && this.dispatchEvent(new SpeechRecognitionEvent("audioend"));
audioStarted = soundStarted = speechStarted = false;
break;
} else if (stopping !== "abort") {
if (recognized && recognized.result && recognized.result.reason === ResultReason2.NoMatch) {
if (!this.continuous || stopping === "stop") {
finalEvent = new SpeechRecognitionEvent("result", {
results: new SpeechRecognitionResultList(finalizedResults)
});
recognizer.stopContinuousRecognitionAsync && await cognitiveServicesAsyncToPromise(
recognizer.stopContinuousRecognitionAsync,
recognizer
)();
break;
}
} else if (recognized || recognizing) {
if (!audioStarted) {
this.dispatchEvent(new SpeechRecognitionEvent("audiostart"));
audioStarted = true;
}
if (!soundStarted) {
this.dispatchEvent(new SpeechRecognitionEvent("soundstart"));
soundStarted = true;
}
if (!speechStarted) {
this.dispatchEvent(new SpeechRecognitionEvent("speechstart"));
speechStarted = true;
}
if (recognized) {
const result = cognitiveServiceEventResultToWebSpeechRecognitionResult_default(recognized.result, {
maxAlternatives: this.maxAlternatives,
textNormalization
});
const recognizable = !!result[0]?.transcript;
if (recognizable) {
finalizedResults = [...finalizedResults, result];
this.continuous && this.dispatchEvent(
new SpeechRecognitionEvent("result", {
results: new SpeechRecognitionResultList(finalizedResults)
})
);
}
if (this.continuous && recognizable) {
finalEvent = void 0;
} else {
finalEvent = new SpeechRecognitionEvent("result", {
results: new SpeechRecognitionResultList(finalizedResults)
});
}
if ((!this.continuous || stopping === "stop") && recognizer.stopContinuousRecognitionAsync) {
await cognitiveServicesAsyncToPromise(recognizer.stopContinuousRecognitionAsync, recognizer)();
}
if (looseEvents && finalEvent && recognizable) {
this.dispatchEvent(finalEvent);
finalEvent = void 0;
}
} else if (recognizing) {
this.interimResults && this.dispatchEvent(
new SpeechRecognitionEvent("result", {
results: new SpeechRecognitionResultList([
...finalizedResults,
cognitiveServiceEventResultToWebSpeechRecognitionResult_default(recognizing.result, {
maxAlternatives: this.maxAlternatives,
textNormalization
})
])
})
);
}
}
}
}
if (speechStarted) {
this.dispatchEvent(new SpeechRecognitionEvent("speechend"));
}
if (soundStarted) {
this.dispatchEvent(new SpeechRecognitionEvent("soundend"));
}
if (audioStarted) {
this.dispatchEvent(new SpeechRecognitionEvent("audioend"));
}
if (finalEvent) {
if (finalEvent.type === "result" && !finalEvent.results.length) {
finalEvent = new SpeechRecognitionErrorEvent("error", { error: "no-speech" });
}
this.dispatchEvent(finalEvent);
}
this.dispatchEvent(new SpeechRecognitionEvent("end"));
detachAudioConfigEvent();
} catch (err) {
console.error(err);
throw err;
} finally {
unprepare();
recognizer["dispose"](false);
}
}
}
return {
SpeechGrammarList,
SpeechRecognition,
SpeechRecognitionEvent
};
}
// src/SpeechServices/SpeechToText/createSpeechRecognitionPonyfill.ts
var { OutputFormat: OutputFormat2, SpeechConfig: SpeechConfig2, SpeechRecognizer: SpeechRecognizer3 } = SpeechSDK_default;
function createSpeechRecognitionPonyfill(options) {
const {
audioConfig,
enableTelemetry,
fetchCredentials,
initialSilenceTimeout,
looseEvents,
referenceGrammars,
speechRecognitionEndpointId,
textNormalization
} = patchOptions(options);
if (!audioConfig && (!window.navigator.mediaDevices || !window.navigator.mediaDevices.getUserMedia)) {
throw new Error(
"web-speech-cognitive-services: This browser does not support Media Capture and Streams API and it will not work with Cognitive Services Speech Services."
);
}
const createRecognizer = async (lang) => {
const credentials = await fetchCredentials();
let speechConfig;
if (typeof credentials.speechRecognitionHostname !== "undefined") {
const host = new URL("wss://localhost:443");
host.hostname = credentials.speechRecognitionHostname;
if (credentials.authorizationToken) {
speechConfig = SpeechConfig2.fromHost(host);
speechConfig.authorizationToken = credentials.authorizationToken;
} else {
speechConfig = SpeechConfig2.fromHost(host, credentials.subscriptionKey);
}
} else {
speechConfig = typeof credentials.authorizationToken !== "undefined" ? SpeechConfig2.fromAuthorizationToken(credentials.authorizationToken, credentials.region) : SpeechConfig2.fromSubscription(credentials.subscriptionKey, credentials.region);
}
if (speechRecognitionEndpointId) {
speechConfig.endpointId = speechRecognitionEndpointId;
}
speechConfig.outputFormat = OutputFormat2.Detailed;
speechConfig.speechRecognitionLanguage = lang || "en-US";
typeof initialSilenceTimeout === "number" && speechConfig.setProperty(import_microsoft_cognitiveservices_speech_sdk2.PropertyId.SpeechServiceConnection_InitialSilenceTimeoutMs, "" + initialSilenceTimeout);
return new SpeechRecognizer3(speechConfig, audioConfig);
};
return createSpeechRecognitionPonyfillFromRecognizer({
createRecognizer,
enableTelemetry,
looseEvents,
referenceGrammars,
textNormalization
});
}
// ../../node_modules/event-target-shim/index.mjs
function assertType(condition, message, ...args) {
if (!condition) {
throw new TypeError(format(message, args));
}
}
function format(message, args) {
let i = 0;
return message.replace(/%[os]/gu, () => anyToString(args[i++]));
}
function anyToString(x) {
if (typeof x !== "object" || x === null) {
return String(x);
}
return Object.prototype.toString.call(x);
}
var currentErrorHandler;
function reportError(maybeError) {
try {
const error = maybeError instanceof Error ? maybeError : new Error(anyToString(maybeError));
if (currentErrorHandler) {
currentErrorHandler(error);
return;
}
if (typeof dispatchEvent === "function" && typeof ErrorEvent === "function") {
dispatchEvent(new ErrorEvent("error", { error, message: error.message }));
} else if (typeof process !== "undefined" && typeof process.emit === "function") {
process.emit("uncaughtException", error);
return;
}
console.error(error);
} catch (_a) {
}
}
var Global = typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : typeof globalThis !== "undefined" ? globalThis : void 0;
var currentWarnHandler;
var Warning = class {
constructor(code, message) {
this.code = code;
this.message = message;
}
/**
* Report this warning.
* @param args The arguments of the warning.
*/
warn(...args) {
var _a;
try {
if (currentWarnHandler) {
currentWarnHandler({ ...this, args });
return;
}
const stack = ((_a = new Error().stack) !== null && _a !== void 0 ? _a : "").replace(/^(?:.+?\n){2}/gu, "\n");
console.warn(this.message, ...args, stack);
} catch (_b) {
}
}
};
var InitEventWasCalledWhileDispatching = new Warning("W01", "Unable to initialize event under dispatching.");
var FalsyWasAssignedToCancelBubble = new Warning("W02", "Assigning any falsy value to 'cancelBubble' property has no effect.");
var TruthyWasAssignedToReturnValue = new Warning("W03", "Assigning any truthy value to 'returnValue' property has no effect.");
var NonCancelableEventWasCanceled = new Warning("W04", "Unable to preventDefault on non-cancelable events.");
var CanceledInPassiveListener = new Warning("W05", "Unable to preventDefault inside passive event listener invocation.");
var EventListenerWasDuplicated = new Warning("W06", "An event listener wasn't added because it has been added already: %o, %o");
var OptionWasIgnored = new Warning("W07", "The %o option value was abandoned because the event listener wasn't added as duplicated.");
var InvalidEventListener = new Warning("W08", "The 'callback' argument must be a function or an object that has 'handleEvent' method: %o");
var InvalidAttributeHandler = new Warning("W09", "Event attribute handler must be a function: %o");
var Event2 = class {
/**
* @see https://dom.spec.whatwg.org/#dom-event-none
*/
static get NONE() {
return NONE;
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-capturing_phase
*/
static get CAPTURING_PHASE() {
return CAPTURING_PHASE;
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-at_target
*/
static get AT_TARGET() {
return AT_TARGET;
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-bubbling_phase
*/
static get BUBBLING_PHASE() {
return BUBBLING_PHASE;
}
/**
* Initialize this event instance.
* @param type The type of this event.
* @param eventInitDict Options to initialize.
* @see https://dom.spec.whatwg.org/#dom-event-event
*/
constructor(type, eventInitDict) {
Object.defineProperty(this, "isTrusted", {
value: false,
enumerable: true
});
const opts = eventInitDict !== null && eventInitDict !== void 0 ? eventInitDict : {};
internalDataMap.set(this, {
type: String(type),
bubbles: Boolean(opts.bubbles),
cancelable: Boolean(opts.cancelable),
composed: Boolean(opts.composed),
target: null,
currentTarget: null,
stopPropagationFlag: false,
stopImmediatePropagationFlag: false,
canceledFlag: false,
inPassiveListenerFlag: false,
dispatchFlag: false,
timeStamp: Date.now()
});
}
/**
* The type of this event.
* @see https://dom.spec.whatwg.org/#dom-event-type
*/
get type() {
return $(this).type;
}
/**
* The event target of the current dispatching.
* @see https://dom.spec.whatwg.org/#dom-event-target
*/
get target() {
return $(this).target;
}
/**
* The event target of the current dispatching.
* @deprecated Use the `target` property instead.
* @see https://dom.spec.whatwg.org/#dom-event-srcelement
*/
get srcElement() {
return $(this).target;
}
/**
* The event target of the current dispatching.
* @see https://dom.spec.whatwg.org/#dom-event-currenttarget
*/
get currentTarget() {
return $(this).currentTarget;
}
/**
* The event target of the current dispatching.
* This doesn't support node tree.
* @see https://dom.spec.whatwg.org/#dom-event-composedpath
*/
composedPath() {
const currentTarget = $(this).currentTarget;
if (currentTarget) {
return [currentTarget];
}
return [];
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-none
*/
get NONE() {
return NONE;
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-capturing_phase
*/
get CAPTURING_PHASE() {
return CAPTURING_PHASE;
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-at_target
*/
get AT_TARGET() {
return AT_TARGET;
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-bubbling_phase
*/
get BUBBLING_PHASE() {
return BUBBLING_PHASE;
}
/**
* The current event phase.
* @see https://dom.spec.whatwg.org/#dom-event-eventphase
*/
get eventPhase() {
return $(this).dispatchFlag ? 2 : 0;
}
/**
* Stop event bubbling.
* Because this shim doesn't support node tree, this merely changes the `cancelBubble` property value.
* @see https://dom.spec.whatwg.org/#dom-event-stoppropagation
*/
stopPropagation() {
$(this).stopPropagationFlag = true;
}
/**
* `true` if event bubbling was stopped.
* @deprecated
* @see https://dom.spec.whatwg.org/#dom-event-cancelbubble
*/
get cancelBubble() {
return $(this).stopPropagationFlag;
}
/**
* Stop event bubbling if `true` is set.
* @deprecated Use the `stopPropagation()` method instead.
* @see https://dom.spec.whatwg.org/#dom-event-cancelbubble
*/
set cancelBubble(value) {
if (value) {
$(this).stopPropagationFlag = true;
} else {
FalsyWasAssignedToCancelBubble.warn();
}
}
/**
* Stop event bubbling and subsequent event listener callings.
* @see https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation
*/
stopImmediatePropagation() {
const data = $(this);
data.stopPropagationFlag = data.stopImmediatePropagationFlag = true;
}
/**
* `true` if this event will bubble.
* @see https://dom.spec.whatwg.org/#dom-event-bubbles
*/
get bubbles() {
return $(this).bubbles;
}
/**
* `true` if this event can be canceled by the `preventDefault()` method.
* @see https://dom.spec.whatwg.org/#dom-event-cancelable
*/
get cancelable() {
return $(this).cancelable;
}
/**
* `true` if the default behavior will act.
* @deprecated Use the `defaultPrevented` proeprty instead.
* @see https://dom.spec.whatwg.org/#dom-event-returnvalue
*/
get returnValue() {
return !$(this).canceledFlag;
}
/**
* Cancel the default behavior if `false` is set.
* @deprecated Use the `preventDefault()` method instead.
* @see https://dom.spec.whatwg.org/#dom-event-returnvalue
*/
set returnValue(value) {
if (!value) {
setCancelFlag($(this));
} else {
TruthyWasAssignedToReturnValue.warn();
}
}
/**
* Cancel the default behavior.
* @see https://dom.spec.whatwg.org/#dom-event-preventdefault
*/
preventDefault() {
setCancelFlag($(this));
}
/**
* `true` if the default behavior was canceled.
* @see https://dom.spec.whatwg.org/#dom-event-defaultprevented
*/
get defaultPrevented() {
return $(this).canceledFlag;
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-composed
*/
get composed() {
return $(this).composed;
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-istrusted
*/
//istanbul ignore next
get isTrusted() {
return false;
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-timestamp
*/
get timeStamp() {
return $(this).timeStamp;
}
/**
* @deprecated Don't use this method. The constructor did initialization.
*/
initEvent(type, bubbles = false, cancelable = false) {
const data = $(this);
if (data.dispatchFlag) {
InitEventWasCalledWhileDispatching.warn();
return;
}
internalDataMap.set(this, {
...data,
type: String(type),
bubbles: Boolean(bubbles),
cancelable: Boolean(cancelable),
target: null,
currentTarget: null,
stopPropagationFlag: false,
stopImmediatePropagationFlag: false,
canceledFlag: false
});
}
};
var NONE = 0;
var CAPTURING_PHASE = 1;
var AT_TARGET = 2;
var BUBBLING_PHASE = 3;
var internalDataMap = /* @__PURE__ */ new WeakMap();
function $(event, name = "this") {
const retv = internalDataMap.get(event);
assertType(retv != null, "'%s' must be an object that Event constructor created, but got another one: %o", name, event);
return retv;
}
function setCancelFlag(data) {
if (data.inPassiveListenerFlag) {
CanceledInPassiveListener.warn();
return;
}
if (!data.cancelable) {
NonCancelableEventWasCanceled.warn();
return;
}
data.canceledFlag = true;
}
Object.defineProperty(Event2, "NONE", { enumerable: true });
Object.defineProperty(Event2, "CAPTURING_PHASE", { enumerable: true });
Object.defineProperty(Event2, "AT_TARGET", { enumerable: true });
Object.defineProperty(Event2, "BUBBLING_PHASE", { enumerable: true });
var keys = Object.getOwnPropertyNames(Event2.prototype);
for (let i = 0; i < keys.length; ++i) {
if (keys[i] === "constructor") {
continue;
}
Object.defineProperty(Event2.prototype, keys[i], { enumerable: true });
}
if (typeof Global !== "undefined" && typeof Global.Event !== "undefined") {
Object.setPrototypeOf(Event2.prototype, Global.Event.prototype);
}
function createInvalidStateError(message) {
if (Global.DOMException) {
return new Global.DOMException(message, "InvalidStateError");
}
if (DOMException == null) {
DOMException = class DOMException2 extends Error {
constructor(msg) {
super(msg);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, DOMException2);
}
}
// eslint-disable-next-line class-methods-use-this
get code() {
return 11;
}
// eslint-disable-next-line class-methods-use-this
get name() {
return "InvalidStateError";
}
};
Object.defineProperties(DOMException.prototype, {
code: { enumerable: true },
name: { enumerable: true }
});
defineErrorCodeProperties(DOMException);
defineErrorCodeProperties(DOMException.prototype);
}
return new DOMException(message);
}
var DOMException;
var ErrorCodeMap = {
INDEX_SIZE_ERR: 1,
DOMSTRING_SIZE_ERR: 2,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
INVALID_CHARACTER_ERR: 5,
NO_DATA_ALLOWED_ERR: 6,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INUSE_ATTRIBUTE_ERR: 10,
INVALID_STATE_ERR: 11,
SYNTAX_ERR: 12,
INVALID_MODIFICATION_ERR: 13,
NAMESPACE_ERR: 14,
INVALID_ACCESS_ERR: 15,
VALIDATION_ERR: 16,
TYPE_MISMATCH_ERR: 17,
SECURITY_ERR: 18,
NETWORK_ERR: 19,
ABORT_ERR: 20,
URL_MISMATCH_ERR: 21,
QUOTA_EXCEEDED_ERR: 22,
TIMEOUT_ERR: 23,
INVALID_NODE_TYPE_ERR: 24,
DATA_CLONE_ERR: 25
};
function defineErrorCodeProperties(obj) {
const keys2 = Object.keys(ErrorCodeMap);
for (let i = 0; i < keys2.length; ++i) {
const key = keys2[i];
const value = ErrorCodeMap[key];
Object.defineProperty(obj, key, {
get() {
return value;
},
configurable: true,
enumerable: true
});
}
}
var EventWrapper = class extends Event2 {
/**
* Wrap a given event object to control states.
* @param event The event-like object to wrap.
*/
static wrap(event) {
return new (getWrapperClassOf(event))(event);
}
constructor(event) {
super(event.type, {
bubbles: event.bubbles,
cancelable: event.cancelable,
composed: event.composed
});
if (event.cancelBubble) {
super.stopPropagation();
}
if (event.defaultPrevented) {
super.preventDefault();
}
internalDataMap$1.set(this, { original: event });
const keys2 = Object.keys(event);
for (let i = 0; i < keys2.length; ++i) {
const key = keys2[i];
if (!(key in this)) {
Object.defineProperty(this, key, defineRedirectDescriptor(event, key));
}
}
}
stopPropagation() {
super.stopPropagation();
const { original } = $$1(this);
if ("stopPropagation" in original) {
original.stopPropagation();
}
}
get cancelBubble() {
return super.cancelBubble;
}
set cancelBubble(value) {
super.cancelBubble = value;
const { original } = $$1(this);
if ("cancelBubble" in original) {
original.cancelBubble = value;
}
}
stopImmediatePropagation() {
super.stopImmediatePropagation();
const { original } = $$1(this);
if ("stopImmediatePropagation" in original) {
original.stopImmediatePropagation();
}
}
get returnValue() {
return super.returnValue;
}
set returnValue(value) {
super.returnValue = value;
const { original } = $$1(this);
if ("returnValue" in original) {
original.returnValue = value;
}
}
preventDefault() {
super.preventDefault();
const { original } = $$1(this);
if ("preventDefault" in original) {
original.preventDefault();
}
}
get timeStamp() {
const { original } = $$1(this);
if ("timeStamp" in original) {
return original.timeStamp;
}
return super.timeStamp;
}
};
var internalDataMap$1 = /* @__PURE__ */ new WeakMap();
function $$1(event) {
const retv = internalDataMap$1.get(event);
assertType(retv != null, "'this' is expected an Event object, but got", event);
return retv;
}
var wrapperClassCache = /* @__PURE__ */ new WeakMap();
wrapperClassCache.set(Object.prototype, EventWrapper);
if (typeof Global !== "undefined" && typeof Global.Event !== "undefined") {
wrapperClassCache.set(Global.Event.prototype, EventWrapper);
}
function getWrapperClassOf(originalEvent) {
const prototype = Object.getPrototypeOf(originalEvent);
if (prototype == null) {
return EventWrapper;
}
let wrapper = wrapperClassCache.get(prototype);
if (wrapper == null) {
wrapper = defineWrapper(getWrapperClassOf(prototype), prototype);
wrapperClassCache.set(prototype, wrapper);
}
return wrapper;
}
function defineWrapper(BaseEventWrapper, originalPrototype) {
class CustomEventWrapper extends BaseEventWrapper {
}
const keys2 = Object.keys(originalPrototype);
for (let i = 0; i < keys2.length; ++i) {
Object.defineProperty(CustomEventWrapper.prototype, keys2[i], defineRedirectDescriptor(originalPrototype, keys2[i]));
}
return CustomEventWrapper;
}
function defineRedirectDescriptor(obj, key) {
const d = Object.getOwnPropertyDescriptor(obj, key);
return {
get() {
const original = $$1(this).original;
const value = original[key];
if (typeof value === "function") {
return value.bind(original);
}
return value;
},
set(value) {
const original = $$1(this).original;
original[key] = value;
},
configurable: d.configurable,
enumerable: d.enumerable
};
}
function createListener(callback, capture, passive, once, signal, signalListener) {
return {
callback,
flags: (capture ? 1 : 0) | (passive ? 2 : 0) | (once ? 4 : 0),
signal,
signalListener
};
}
function setRemoved(listener) {
listener.flags |= 8;
}
function isCapture(listener) {
return (listener.flags & 1) === 1;
}
function isPassive(listener) {
return (listener.flags & 2) === 2;
}
function isOnce(listener) {
return (listener.flags & 4) === 4;
}
function isRemoved(listener) {
return (listener.flags & 8) === 8;
}
function invokeCallback({ callback }, target, event) {
try {
if (typeof callback === "function") {
callback.call(target, event);
} else if (typeof callback.handleEvent === "function") {
callback.handleEvent(event);
}
} catch (thrownError) {
reportError(thrownError);
}
}
function findIndexOfListener({ listeners }, callback, capture) {
for (let i = 0; i < listeners.length; ++i) {
if (listeners[i].callback === callback && isCapture(listeners[i]) === capture) {
return i;
}
}
return -1;
}
function addListener(list, callback, capture, passive, once, signal) {
let signalListener;
if (signal) {
signalListener = removeListener.bind(null, list, callback, capture);
signal.addEventListener("abort", signalListener);
}
const listener = createListener(callback, capture, passive, once, signal, signalListener);
if (list.cow) {
list.cow = false;
list.listeners = [...list.listeners, listener];
} else {
list.listeners.push(listener);
}
return listener;
}
function removeListener(list, callback, capture) {
const index = findIndexOfListener(list, callback, capture);
if (index !== -1) {
return removeListenerAt(list, index);
}
return false;
}
function removeListenerAt(list, index, disableCow = false) {
const listener = list.listeners[index];
setRemoved(listener);
if (listener.signal) {
listener.signal.removeEventListener("abort", listener.signalListener);
}
if (list.cow && !disableCow) {
list.cow = false;
list.listeners = list.listeners.filter((_, i) => i !== index);
return false;
}
list.listeners.splice(index, 1);
return true;
}
function createListenerListMap() {
return /* @__PURE__ */ Object.create(null);
}
function ensureListenerList(listenerMap, type) {
var _a;
return (_a = listenerMap[type]) !== null && _a !== void 0 ? _a : listenerMap[type] = {
attrCallback: void 0,
attrListener: void 0,
cow: false,
listeners: []
};
}
var EventTarget2 = class {
/**
* Initialize this instance.
*/
constructor() {
internalDataMap$2.set(this, createListenerListMap());
}
// Implementation
addEventListener(type0, callback0, options0) {
const listenerMap = $$2(this);
const { callback, capture, once, passive, signal, type } = normalizeAddOptions(type0, callback0, options0);
if (callback == null || (signal === null || signal === void 0 ? void 0 : signal.aborted)) {
return;
}
const list = ensureListenerList(listenerMap, type);
const i = findIndexOfListener(list, callback, capture);
if (i !== -1) {
warnDuplicate(list.listeners[i], passive, once, signal);
return;
}
addListener(list, callback, capture, passive, once, signal);
}
// Implementation
removeEventListener(type0, callback0, options0) {
const listenerMap = $$2(this);
const { callback, capture, type } = normalizeOptions(type0, callback0, options0);
const list = listenerMap[type];
if (callback != null && list) {
removeListener(list, callback, capture);
}
}
// Implementation
dispatchEvent(e) {
const list = $$2(this)[String(e.type)];
if (list == null) {
return true;
}
const event = e instanceof Event2 ? e : EventWrapper.wrap(e);
const eventData = $(event, "event");
if (eventData.dispatchFlag) {
throw createInvalidStateError("This event has been in dispatching.");
}
eventData.dispatchFlag = true;
eventData.target = eventData.currentTarget = this;
if (!eventData.stopPropagationFlag) {
const { cow, listeners } = list;
list.cow = true;
for (let i = 0; i < listeners.length; ++i) {
const listener = listeners[i];
if (isRemoved(listener)) {
continue;
}
if (isOnce(listener) && removeListenerAt(list, i, !cow)) {
i -= 1;
}
eventData.inPassiveListenerFlag = isPassive(listener);
invokeCallback(listener, this, event);
eventData.inPassiveListenerFlag = false;
if (eventData.stopImmediatePropagationFlag) {
break;
}
}
if (!cow) {
list.cow = false;
}
}
eventData.target = null;
eventData.currentTarget = null;
eventData.stopImmediatePropagationFlag = false;
eventData.stopPropagationFlag = false;
eventData.dispatchFlag = false;
return !eventData.canceledFlag;
}
};
var internalDataMap$2 = /* @__PURE__ */ new WeakMap();
function $$2(target, name = "this") {
const retv = internalDataMap$2.get(target);
assertType(retv != null, "'%s' must be an object that EventTarget constructor created, but got another one: %o", name, target);
return retv;
}
function normalizeAddOptions(type, callback, options) {
var _a;
assertCallback(callback);
if (typeof options === "object" && options !== null) {
return {
type: String(type),
callback: callback !== null && callback !== void 0 ? callback : void 0,
capture: Boolean(options.capture),
passive: Boolean(options.passive),
once: Boolean(options.once),
signal: (_a = options.signal) !== null && _a !== void 0 ? _a : void 0
};
}
return {
type: String(type),
callback: callback !== null && callback !== void 0 ? callback : void 0,
capture: Boolean(options),
passive: false,
once: false,
signal: void 0
};
}
function normalizeOptions(type, callback, options) {
assertCallback(callback);
if (typeof options === "object" && options !== null) {
return {
type: String(type),
callback: callback !== null && callback !== void 0 ? callback : void 0,
capture: Boolean(options.capture)
};
}
return {
type: String(type),
callback: callback !== null && callback !== void 0 ? callback : void 0,
capture: Boolean(options)
};
}
function assertCallback(callback) {
if (typeof callback === "function" || typeof callback === "object" && callback !== null && typeof callback.handleEvent === "function") {
return;
}
if (callback == null || typeof callback === "object") {
InvalidEventListener.warn(callback);
return;
}
throw new TypeError(format(InvalidEventListener.message, [callback]));
}
function warnDuplicate(listener, passive, once, signal) {
EventListenerWasDuplicated.warn(isCapture(listener) ? "capture" : "bubble", listener.callback);
if (isPassive(listener) !== passive) {
OptionWasIgnored.warn("passive");
}
if (isOnce(listener) !== once) {
OptionWasIgnored.warn("once");
}
if (listener.signal !== signal) {
OptionWasIgnored.warn("signal");
}
}
var keys$1 = Object.getOwnPropertyNames(EventTarget2.prototype);
for (let i = 0; i < keys$1.length; ++i) {
if (keys$1[i] === "constructor") {
continue;
}
Object.defineProperty(EventTarget2.prototype, keys$1[i], { enumerable: true });
}
if (typeof Global !== "undefined" && typeof Global.EventTarget !== "undefined") {
Object.setPrototypeOf(EventTarget2.prototype, Global.EventTarget.prototype);
}
function getEventAttributeValue(target, type) {
var _a, _b;
const listMap = $$2(target, "target");
return (_b = (_a = listMap[type]) === null || _a === void 0 ? void 0 : _a.attrCallback) !== null && _b !== void 0 ? _b : null;
}
function setEventAttributeValue(target, type, callback) {
if (callback != null && typeof callback !== "function") {
InvalidAttributeHandler.warn(callback);
}
if (typeof callback === "function" || typeof callback === "object" && callback !== null) {
upsertEventAttributeListener(target, type, callback);
} else {
removeEventAttributeListener(target, type);
}
}
function upsertEventAttributeListener(target, type, callback) {
const list = ensureListenerList($$2(target, "target"), String(type));
list.attrCallback = callback;
if (list.attrListener == null) {
list.attrListener = addListener(list, defineEventAttributeCallback(list), false, false, false, void 0);
}
}
function removeEventAttributeListener(target, type) {
const listMap = $$2(target, "target");
const list = listMap[String(type)];
if (list && list.attrListener) {
removeListener(list, list.attrListener.callback, false);
list.attrCallback = list.attrListener = void 0;
}
}
function defineEventAttributeCallback(list) {
return function(event) {
const callback = list.attrCallback;
if (typeof callback === "function") {
callback.call(this, event);
}
};
}
// ../../node_modules/on-error-resume-next/dist/chunk-MBTBSBLB.mjs
function isPromise(value) {
return !!((typeof value === "function" || typeof value === "object") && value && "then" in value && typeof value.then === "function");
}
// ../../node_modules/on-error-resume-next/dist/on-error-resume-next.async.mjs
function onErrorResumeNext(fn, context) {
return new Promise((resolve) => {
try {
const result = fn.call(context);
if (isPromise(result)) {
result.then(resolve, () => resolve(void 0));
} else {
resolve(result);
}
} catch {
resolve(void 0);
}
});
}
// ../../node_modules/memoize-one/dist/memoize-one.esm.js
var safeIsNaN = Number.isNaN || function ponyfill(value) {
return typeof value === "number" && value !== value;
};
function isEqual(first, second) {
if (first === second) {
return true;
}
if (safeIsNaN(first) && safeIsNaN(second)) {
return true;
}
return false;
}
function areInputsEqual(newInputs, lastInputs) {
if (newInputs.length !== lastInputs.length) {
return false;
}
for (var i = 0; i < newInputs.length; i++) {
if (!isEqual(newInputs[i], lastInputs[i])) {
return false;
}
}
return true;
}
function memoizeOne(resultFn, isEqual2) {
if (isEqual2 === void 0) {
isEqual2 = areInputsEqual;
}
var cache = null;
function memoized() {
var newArgs = [];
for (var _i = 0; _i < arguments.length; _i++) {
newArgs[_i] = arguments[_i];
}
if (cache && cache.lastThis === this && isEqual2(newArgs, cache.lastArgs)) {
return cache.lastResult;
}
var lastResult = resultFn.apply(this, newArgs);
cache = {
lastResult,
lastArgs: newArgs,
lastThis: this
};
return lastResult;
}
memoized.clear = function clear() {
cache = null;
};
return memoized;
}
// src/SpeechServices/TextToSpeech/AudioContextConsumer.js
var AudioContextConsumer_default = class {
constructor(audioContext) {
this.audioContext = audioContext;
}
pause() {
this.audioContext && this.audioContext.suspend();
this.playingUtterance && this.playingUtterance.dispatchEvent(new CustomEvent("pause"));
}
resume() {
this.audioContext && this.audioContext.resume();
this.playingUtterance && this.playingUtterance.dispatchEvent(new CustomEvent("resume"));
}
async start(queue) {
let utterance;
while (utterance = queue.shift()) {
this.playingUtterance = utterance;
await utterance.play(this.audioContext);
this.playingUtterance = null;
}
}
stop() {
this.playingUtterance && this.playingUtterance.stop();
if (this.audioContext.state === "suspended") {
this.audioContext.resume();
}
}
};
// src/SpeechServices/TextToSpeech/AudioContextQueue.js
var AudioContextQueue_default = class {
constructor({ audioContext, ponyfill: ponyfill2 }) {
this.consumer = null;
this.paused = false;
this.queue = [];
this.getAudioContext = memoizeOne(() => audioContext || new ponyfill2.AudioContext());
}
pause() {
this.paused = true;
this.consumer && this.consumer.pause();
}
push(utterance) {
this.queue.push(utterance);
this.startConsumer();
}
resume() {
this.paused = false;
if (this.consumer) {
this.consumer.resume();
} else {
this.startConsumer();
}
}
get speaking() {
return !!this.consumer;
}
async startConsumer() {
while (!this.paused && this.queue.length && !this.consumer) {
this.consumer = new AudioContextConsumer_default(this.getAudioContext());
await this.consumer.start(this.queue);
this.consumer = null;
}
}
stop() {
this.queue.splice(0);
this.consumer && this.consumer.stop();
}
};
// src/SpeechServices/TextToSpeech/SpeechSynthesisEvent.js
var SpeechSynthesisEvent = class extends Event2 {
constructor(type) {
super(type);
}
};
// node_modules/event-as-promise/dist/event-as-promise.mjs
function withResolvers() {
const resolvers = {};
resolvers.promise = new Promise((resolve, reject) => {
resolvers.reject = reject;
resolvers.resolve = resolve;
});
return resolvers;
}
var EventAsPromise = class {
constructor() {
this.#eventListener = (event) => {
const deferred = this.#orderedResolvers.shift();
deferred && deferred.resolve(event);
if (this.#upcomingResolvers) {
this.#upcomingResolvers.resolve(event);
this.#upcomingResolvers = void 0;
}
};
}
#eventListener;
#orderedResolvers = [];
#upcomingResolvers = void 0;
get eventListener() {
return this.#eventListener;
}
[Symbol.iterator]() {
return {
next: () => ({
done: false,
value: this.upcoming()
})
};
}
one() {
const deferred = withResolvers();
this.#orderedResolvers.push(deferred);
return deferred.promise;
}
upcoming() {
if (!this.#upcomingResolvers) {
this.#upcomingResolvers = withResolvers();
}
return this.#upcomingResolvers.promise;
}
};
// ../../node_modules/base64-arraybuffer/dist/base64-arraybuffer.es5.js
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
for (i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
var i;
var decode = function(base64) {
var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i + 1)];
encoded3 = lookup[base64.charCodeAt(i + 2)];
encoded4 = lookup[base64.charCodeAt(i + 3)];
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return arraybuffer;
};
// src/SpeechServices/TextToSpeech/buildSSML.js
function relativePercentage(value) {
let relative = Math.round((value - 1) * 100);
if (relative >= 0) {
relative = "+" + relative;
}
return relative + "%";
}
function buildSSML({ lang, pitch = 1, rate = 1, text, voice, volume }) {
return `<speak version="1.0" xml:lang="${lang}">
<voice xml:lang="${lang}" name="${voice}">
<prosody pitch="${relativePercentage(pitch)}" rate="${relativePercentage(rate)}" volume="${relativePercentage(
volume
)}">
${text}
</prosody>
</voice>
</speak>`;
}
// src/SpeechServices/TextToSpeech/isSSML.js
var SPEAK_TAG_PATTERN = /^\s*<speak(\s|\/?>)/u;
var XML_PROLOG_PATTERN = /^\s*<\?xml\s/u;
function isSSML(text) {
return SPEAK_TAG_PATTERN.test(text) || XML_PROLOG_PATTERN.test(text);
}
// src/SpeechServices/TextToSpeech/fetchSpeechData.js
var DEFAULT_LANGUAGE = "en-US";
var DEFAULT_OUTPUT_FORMAT = "riff-16khz-16bit-mono-pcm";
var DEFAULT_VOICE = "Microsoft Server Speech Text to Speech Voice (en-US, AriaNeural)";
var EMPTY_MP3_BASE64 = "SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjU2LjEwMQAAAAAAAAAAAAAA//tAwAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAACAAABhgC7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7u7//////////////////////////////////////////////////////////////////8AAAAATGF2YzU3LjY0AAAAAAAAAAAAAAAAJAUHAAAAAAAAAYYoRBqpAAAAAAD/+xDEAAPAAAGkAAAAIAAANIAAAARMQU1FMy45OS41VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7EMQpg8AAAaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV";
async function fetchSpeechData_default({
deploymentId,
fetchCredentials,
lang = DEFAULT_LANGUAGE,
outputFormat = DEFAULT_OUTPUT_FORMAT,
pitch,
rate,
text,
voice = DEFAULT_VOICE,
volume
}) {
if (!text) {
return decode(EMPTY_MP3_BASE64);
}
const { authorizationToken, region, speechSynthesisHostname, subscriptionKey } = await fetchCredentials();
if (authorizationToken && subscriptionKey || !authorizationToken && !subscriptionKey) {
throw new Error('Only "authorizationToken" or "subscriptionKey" should be set.');
} else if (region && speechSynthesisHostname || !region && !speechSynthesisHostname) {
throw new Error('Only "region" or "speechSynthesisHostnamename" should be set.');
}
const ssml = isSSML(text) ? text : buildSSML({ lang, pitch, rate, text, voice, volume });
const hostname = speechSynthesisHostname || (deploymentId ? `${encodeURI(region)}.voice.speech.microsoft.com` : `${encodeURI(region)}.tts.speech.microsoft.com`);
const search = deploymentId ? `?deploymentId=${encodeURI(deploymentId)}` : "";
const url = `https://${hostname}/cognitiveservices/v1${search}`;
const res = await fetch(url, {
headers: {
"Content-Type": "application/ssml+xml",
"X-Microsoft-OutputFormat": outputFormat,
...authorizationToken ? {
Authorization: `Bearer ${authorizationToken}`
} : {
"Ocp-Apim-Subscription-Key": subscriptionKey
}
},
method: "POST",
body: ssml
});
if (!res.ok) {
throw new Error(`web-speech-cognitive-services: Failed to syntheis speech, server returned ${res.status}`);
}
return res.arrayBuffer();
}
// src/SpeechServices/TextToSpeech/subscribeEvent.js
function subscribeEvent(target, name, handler) {
target.addEventListener(name, handler);
return () => target.removeEventListener(name, handler);
}
// src/SpeechServices/TextToSpeech/SpeechSynthesisUtterance.js
function asyncDecodeAudioData(audioContext, arrayBuffer) {
return new Promise((resolve, reject) => {
const promise = audioContext.decodeAudioData(arrayBuffer, resolve, reject);
promise && typeof promise.then === "function" && resolve(promise);
});
}
function playDecoded(audioContext, audioBuffer, source) {
return new Promise((resolve, reject) => {
const audioContextClosed = new EventAsPromise();
const sourceEnded = new EventAsPromise();
const unsubscribe = subscribeEvent(
audioContext,
"statechange",
({ target: { state } }) => state === "closed" && audioContextClosed.eventListener()
);
try {
source.buffer = audioBuffer;
source.onended = sourceEnded.eventListener;
source.connect(audioContext.destination);
source.start(0);
Promise.race([audioContextClosed.upcoming(), sourceEnded.upcoming()]).then(resolve);
} catch (err) {
reject(err);
} finally {
unsubscribe();
}
});
}
var SpeechSynthesisUtterance = class extends EventTarget2 {
constructor(text) {
super();
this._lang = null;
this._pitch = 1;
this._rate = 1;
this._voice = null;
this._volume = 1;
this.text = text;
this.onboundary = null;
this.onend = null;
this.onerror = null;
this.onmark = null;
this.onpause = null;
this.onresume = null;
this.onstart = null;
}
get lang() {
return this._lang;
}
set lang(value) {
this._lang = value;
}
get onboundary() {
return getEventAttributeValue(this, "boundary");
}
set onboundary(value) {
setEventAttributeValue(this, "boundary", value);
}
get onend() {
return getEventAttributeValue(this, "end");
}
set onend(value) {
setEventAttributeValue(this, "end", value);
}
get onerror() {
return getEventAttributeValue(this, "error");
}
set onerror(value) {
setEventAttributeValue(this, "error", value);
}
get onmark() {
return getEventAttributeValue(this, "mark");
}
set onmark(value) {
setEventAttributeValue(this, "mark", value);
}
get onpause() {
return getEventAttributeValue(this, "pause");
}
set onpause(value) {
setEventAttributeValue(this, "pause", value);
}
get onresume() {
return getEventAttributeValue(this, "resume");
}
set onresume(value) {
setEventAttributeValue(this, "resume", value);
}
get onstart() {
return getEventAttributeValue(this, "start");
}
set onstart(value) {
setEventAttributeValue(this, "start", value);
}
get pitch() {
return this._pitch;
}
set pitch(value) {
this._pitch = value;
}
get rate() {
return this._rate;
}
set rate(value) {
this._rate = value;
}
get voice() {
return this._voice;
}
set voice(value) {
this._voice = value;
}
get volume() {
return this._volume;
}
set volume(value) {
this._volume = value;
}
preload({ deploymentId, fetchCredentials, outputFormat }) {
this.arrayBufferPromise = fetchSpeechData_default({
fetchCredentials,
deploymentId,
lang: this.lang || window.navigator.language,
outputFormat,
pitch: this.pitch,
rate: this.rate,
text: this.text,
voice: this.voice && this.voice.voiceURI,
volume: this.volume
});
this.arrayBufferPromise.catch();
}
async play(audioContext) {
try {
this.dispatchEvent(new SpeechSynthesisEvent("start"));
const source = audioContext.createBufferSource();
const audioBuffer = await asyncDecodeAudioData(audioContext, await this.arrayBufferPromise);
this._playingSource = source;
await playDecoded(audioContext, audioBuffer, source);
this._playingSource = null;
this.dispatchEvent(new SpeechSynthesisEvent("end"));
} catch (error) {
this.dispatchEvent(new ErrorEvent("error", { error: "synthesis-failed", message: error.stack }));
}
}
stop() {
this._playingSource && this._playingSource.stop();
}
};
var SpeechSynthesisUtterance_default = SpeechSynthesisUtterance;
// src/SpeechServices/TextToSpeech/SpeechSynthesisVoice.js
var SpeechSynthesisVoice_default = class {
constructor({ gender, lang, voiceURI }) {
this._default = false;
this._gender = gender;
this._lang = lang;
this._localService = false;
this._name = voiceURI;
this._voiceURI = voiceURI;
}
get default() {
return this._default;
}
get gender() {
return this._gender;
}
get lang() {
return this._lang;
}
get localService() {
return this._localService;
}
get name() {
return this._name;
}
get voiceURI() {
return this._voiceURI;
}
};
// src/SpeechServices/TextToSpeech/fetchCustomVoices.js
async function fetchCustomVoices({ customVoiceHostname, deploymentId, region, subscriptionKey }) {
const hostname = customVoiceHostname || `${region}.customvoice.api.speech.microsoft.com`;
const res = await fetch(
`https://${encodeURI(hostname)}/api/texttospeech/v2.0/endpoints/${encodeURIComponent(deploymentId)}`,
{
headers: {
accept: "application/json",
"ocp-apim-subscription-key": subscriptionKey
}
}
);
if (!res.ok) {
throw new Error("Failed to fetch custom voices");
}
return res.json();
}
async function fetchCustomVoices_default({ customVoiceHostname, deploymentId, region, subscriptionKey }) {
const { models } = await fetchCustomVoices({ customVoiceHostname, deploymentId, region, subscriptionKey });
return models.map(
({ properties: { Gender: gender }, locale: lang, name: voiceURI }) => new SpeechSynthesisVoice_default({ gender, lang, voiceURI })
).sort(({ name: x }, { name: y }) => x > y ? 1 : x < y ? -1 : 0);
}
// src/SpeechServices/TextToSpeech/fetchVoices.js
async function fetchVoices({ authorizationToken, region, speechSynthesisHostname, subscriptionKey }) {
const hostname = speechSynthesisHostname || `${encodeURI(region)}.tts.speech.microsoft.com`;
const res = await fetch(`https://${hostname}/cognitiveservices/voices/list`, {
headers: {
"content-type": "application/json",
...authorizationToken ? {
authorization: `Bearer ${authorizationToken}`
} : {
"Ocp-Apim-Subscription-Key": subscriptionKey
}
}
});
if (!res.ok) {
throw new Error("Failed to fetch voices");
}
const voices = await res.json();
return voices.map(({ Gender: gender, Locale: lang, Name: voiceURI }) => new SpeechSynthesisVoice_default({ gender, lang, voiceURI })).sort(({ name: x }, { name: y }) => x > y ? 1 : x < y ? -1 : 0);
}
// src/SpeechServices/TextToSpeech/createSpeechSynthesisPonyfill.js
var DEFAULT_OUTPUT_FORMAT2 = "audio-24khz-160kbitrate-mono-mp3";
var EMPTY_ARRAY = [];
var createSpeechSynthesisPonyfill_default = (options) => {
const {
audioContext,
fetchCredentials,
ponyfill: ponyfill2 = {
AudioContext: window.AudioContext || window.webkitAudioContext
},
speechSynthesisDeploymentId,
speechSynthesisOutputFormat = DEFAULT_OUTPUT_FORMAT2
} = patchOptions(options);
if (!audioContext && !ponyfill2.AudioContext) {
console.warn(
"web-speech-cognitive-services: This browser does not support Web Audio and it will not work with Cognitive Services Speech Services."
);
return {};
}
class SpeechSynthesis extends EventTarget2 {
constructor() {
super();
this.queue = new AudioContextQueue_default({ audioContext, ponyfill: ponyfill2 });
this.updateVoices();
}
cancel() {
this.queue.stop();
}
getVoices() {
return EMPTY_ARRAY;
}
get onvoiceschanged() {
return getEventAttributeValue(this, "voiceschanged");
}
set onvoiceschanged(value) {
setEventAttributeValue(this, "voiceschanged", value);
}
pause() {
this.queue.pause();
}
resume() {
this.queue.resume();
}
speak(utterance) {
if (!(utterance instanceof SpeechSynthesisUtterance_default)) {
throw new Error("invalid utterance");
}
const { reject, resolve, promise } = pDefer();
const handleError = ({ error: errorCode, message }) => {
const error = new Error(errorCode);
error.stack = message;
reject(error);
};
utterance.addEventListener("end", resolve);
utterance.addEventListener("error", handleError);
utterance.preload({
deploymentId: speechSynthesisDeploymentId,
fetchCredentials,
outputFormat: speechSynthesisOutputFormat
});
this.queue.push(utterance);
return promise.finally(() => {
utterance.removeEventListener("end", resolve);
utterance.removeEventListener("error", handleError);
});
}
get speaking() {
return this.queue.speaking;
}
async updateVoices() {
const { customVoiceHostname, region, speechSynthesisHostname, subscriptionKey } = await fetchCredentials();
if (speechSynthesisDeploymentId) {
if (subscriptionKey) {
console.warn(
"web-speech-cognitive-services: Listing of custom voice models are only available when using subscription key."
);
await onErrorResumeNext(async () => {
const voices = await fetchCustomVoices_default({
customVoiceHostname,
deploymentId: speechSynthesisDeploymentId,
region,
speechSynthesisHostname,
subscriptionKey
});
this.getVoices = () => voices;
});
}
} else {
await onErrorResumeNext(async () => {
const voices = await fetchVoices(await fetchCredentials());
this.getVoices = () => voices;
});
}
this.dispatchEvent(new SpeechSynthesisEvent("voiceschanged"));
}
}
return {
speechSynthesis: new SpeechSynthesis(),
SpeechSynthesisEvent,
SpeechSynthesisUtterance: SpeechSynthesisUtterance_default
};
};
// src/SpeechServices/TextToSpeech.js
var TextToSpeech_default = createSpeechSynthesisPonyfill_default;
// src/SpeechServices.ts
function createSpeechServicesPonyfill(options = {}) {
return {
...createSpeechRecognitionPonyfill(options),
...TextToSpeech_default(options)
};
}
var meta = document.createElement("meta");
meta.setAttribute("name", "web-speech-cognitive-services");
meta.setAttribute("content", `version=${"8.1.3"}`);
document.head.appendChild(meta);
// src/index.umd.js
globalThis.WebSpeechCognitiveServices = {
create: createSpeechServicesPonyfill,
createSpeechRecognitionPonyfillFromRecognizer
};
})();
//# sourceMappingURL=web-speech-cognitive-services.development.js.map