@charisma-ai/sdk
Version:
Charisma.ai SDK for Javascript (browser)
1,233 lines (1,001 loc) • 35 kB
JavaScript
var fetch = require('isomorphic-unfetch');
var querystring = require('query-string');
var EventEmitter = require('eventemitter3');
var Colyseus = require('colyseus.js');
var jwtDecode = require('jwt-decode');
var PQueue = require('p-queue');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
var querystring__default = /*#__PURE__*/_interopDefaultLegacy(querystring);
var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);
var jwtDecode__default = /*#__PURE__*/_interopDefaultLegacy(jwtDecode);
var PQueue__default = /*#__PURE__*/_interopDefaultLegacy(PQueue);
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
_setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _catch(body, recover) {
try {
var result = body();
} catch (e) {
return recover(e);
}
if (result && result.then) {
return result.then(void 0, recover);
}
return result;
}
var restartFromEventId = function restartFromEventId(token, eventId, apiOptions) {
try {
return Promise.resolve(fetchHelper(((apiOptions == null ? void 0 : apiOptions.baseUrl) || globalBaseUrl) + "/play/restart-from-event", {
body: JSON.stringify({
eventId: eventId
}),
headers: {
Authorization: "Bearer " + token
},
method: "POST"
})).then(function () {});
} catch (e) {
return Promise.reject(e);
}
};
var restartFromEpisodeIndex = function restartFromEpisodeIndex(token, episodeIndex, apiOptions) {
try {
return Promise.resolve(fetchHelper(((apiOptions == null ? void 0 : apiOptions.baseUrl) || globalBaseUrl) + "/play/restart-from-episode", {
body: JSON.stringify({
episodeIndex: episodeIndex
}),
headers: {
Authorization: "Bearer " + token
},
method: "POST"
})).then(function () {});
} catch (e) {
return Promise.reject(e);
}
};
var restartFromEpisodeId = function restartFromEpisodeId(token, episodeId, apiOptions) {
try {
return Promise.resolve(fetchHelper(((apiOptions == null ? void 0 : apiOptions.baseUrl) || globalBaseUrl) + "/play/restart-from-episode", {
body: JSON.stringify({
episodeId: episodeId
}),
headers: {
Authorization: "Bearer " + token
},
method: "POST"
})).then(function () {});
} catch (e) {
return Promise.reject(e);
}
};
var setMemory = function setMemory(token, memoryIdOrRecallValue, saveValue, apiOptions) {
try {
return Promise.resolve(fetchHelper(((apiOptions == null ? void 0 : apiOptions.baseUrl) || globalBaseUrl) + "/play/set-memory", {
body: JSON.stringify(_extends({}, typeof memoryIdOrRecallValue === "number" ? {
memoryId: memoryIdOrRecallValue
} : {
memoryRecallValue: memoryIdOrRecallValue
}, {
saveValue: saveValue
})),
headers: {
Authorization: "Bearer " + token
},
method: "POST"
})).then(function () {});
} catch (e) {
return Promise.reject(e);
}
};
var getPlaythroughInfo = function getPlaythroughInfo(token, apiOptions) {
try {
return Promise.resolve(fetchHelper(((apiOptions == null ? void 0 : apiOptions.baseUrl) || globalBaseUrl) + "/play/playthrough-info", {
headers: {
Authorization: "Bearer " + token
},
method: "GET"
}));
} catch (e) {
return Promise.reject(e);
}
};
var getMessageHistory = function getMessageHistory(token, conversationId, minEventId, apiOptions) {
try {
var query = querystring__default['default'].stringify({
conversationId: conversationId,
minEventId: minEventId
});
return Promise.resolve(fetchHelper(((apiOptions == null ? void 0 : apiOptions.baseUrl) || globalBaseUrl) + "/play/message-history?" + query, {
headers: {
Authorization: "Bearer " + token
},
method: "GET"
}));
} catch (e) {
return Promise.reject(e);
}
};
var createCharacterConversation = function createCharacterConversation(token, characterId, apiOptions) {
try {
return Promise.resolve(fetchHelper(((apiOptions == null ? void 0 : apiOptions.baseUrl) || globalBaseUrl) + "/play/conversation/character", {
body: JSON.stringify({
characterId: characterId
}),
headers: {
Authorization: "Bearer " + token
},
method: "POST"
})).then(function (_ref3) {
var conversationId = _ref3.conversationId;
return conversationId;
});
} catch (e) {
return Promise.reject(e);
}
};
var createConversation = function createConversation(token, apiOptions) {
try {
return Promise.resolve(fetchHelper(((apiOptions == null ? void 0 : apiOptions.baseUrl) || globalBaseUrl) + "/play/conversation", {
body: JSON.stringify({}),
headers: {
Authorization: "Bearer " + token
},
method: "POST"
})).then(function (_ref2) {
var conversationId = _ref2.conversationId;
return conversationId;
});
} catch (e) {
return Promise.reject(e);
}
};
var createPlaythroughToken = function createPlaythroughToken(options, apiOptions) {
try {
if (options.version === -1 && options.userToken === undefined && options.apiKey === undefined) {
throw new Error("To play the draft version (-1) of a story, an `apiKey` or `userToken` must also be passed.");
}
var authHeader;
if (options.apiKey) {
authHeader = "API-Key " + options.apiKey;
} else if (options.userToken) {
authHeader = "Bearer " + options.userToken;
}
return Promise.resolve(_catch(function () {
return Promise.resolve(fetchHelper(((apiOptions == null ? void 0 : apiOptions.baseUrl) || globalBaseUrl) + "/play/token", {
body: JSON.stringify({
storyId: options.storyId,
version: options.version
}),
headers: authHeader ? {
Authorization: authHeader
} : undefined,
method: "POST"
})).then(function (_ref) {
var token = _ref.token;
return token;
});
}, function (err) {
throw new Error("A playthrough token could not be generated: " + err);
}));
} catch (e) {
return Promise.reject(e);
}
};
var fetchHelper = function fetchHelper(endpoint, options) {
if (options === void 0) {
options = {};
}
try {
var headers = _extends({
Accept: "application/json"
}, options.headers);
if (typeof options.method === "string" && options.method.toLowerCase() === "post") {
headers = _extends({
"Content-Type": "application/json"
}, headers);
}
return Promise.resolve(fetch__default['default'](endpoint, _extends({
mode: "cors"
}, options, {
headers: headers
}))).then(function (response) {
function _temp2() {
if (!response.ok) {
throw new Error(data.error || "Something went wrong calling `" + endpoint + "`");
}
return data;
}
var data = {};
var _temp = _catch(function () {
return Promise.resolve(response.json()).then(function (_response$json) {
data = _response$json;
});
}, function () {});
return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
});
} catch (e) {
return Promise.reject(e);
}
};
var globalBaseUrl = "https://play.charisma.ai";
var getGlobalBaseUrl = function getGlobalBaseUrl() {
return globalBaseUrl;
};
var setGlobalBaseUrl = function setGlobalBaseUrl(newBaseUrl) {
globalBaseUrl = newBaseUrl;
};
var api = {
__proto__: null,
restartFromEventId: restartFromEventId,
restartFromEpisodeIndex: restartFromEpisodeIndex,
restartFromEpisodeId: restartFromEpisodeId,
setMemory: setMemory,
getPlaythroughInfo: getPlaythroughInfo,
getMessageHistory: getMessageHistory,
createCharacterConversation: createCharacterConversation,
createConversation: createConversation,
createPlaythroughToken: createPlaythroughToken,
getGlobalBaseUrl: getGlobalBaseUrl,
setGlobalBaseUrl: setGlobalBaseUrl
};
function _finallyRethrows(body, finalizer) {
try {
var result = body();
} catch (e) {
return finalizer(true, e);
}
if (result && result.then) {
return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
}
return finalizer(false, result);
}
var Conversation = /*#__PURE__*/function (_EventEmitter) {
_inheritsLoose(Conversation, _EventEmitter);
function Conversation(conversationId, playthroughInstance, options) {
var _this, _this2;
_this2 = _EventEmitter.call(this) || this;
_this = this;
_this2.eventQueue = new PQueue__default['default']();
_this2.options = {};
_this2.addIncomingEvent = function (eventName) {
var _arguments = arguments;
_this.eventQueue.add(function () {
var _this3;
return (_this3 = _this).emit.apply(_this3, [eventName].concat([].slice.call(_arguments, 1)));
});
return true;
};
_this2.start = function (event) {
if (event === void 0) {
event = {};
}
return _this2.playthroughInstance.addOutgoingEvent("start", _extends({}, _this2.options, event, {
conversationId: _this2.id
}));
};
_this2.reply = function (event) {
return _this2.playthroughInstance.addOutgoingEvent("reply", _extends({}, _this2.options, event, {
conversationId: _this2.id
}));
};
_this2.tap = function () {
return _this2.playthroughInstance.addOutgoingEvent("tap", _extends({}, _this2.options, {
conversationId: _this2.id
}));
};
_this2.action = function (event) {
return _this2.playthroughInstance.addOutgoingEvent("action", _extends({}, _this2.options, event, {
conversationId: _this2.id
}));
};
_this2.resume = function () {
return _this2.playthroughInstance.addOutgoingEvent("resume", _extends({}, _this2.options, {
conversationId: _this2.id
}));
};
_this2.setSpeechConfig = function (speechConfig) {
_this2.options.speechConfig = speechConfig;
};
_this2.reconnect = function () {
try {
var _temp3 = function () {
if (typeof _this2.lastEventId === "string") {
_this2.eventQueue.pause();
var _temp4 = _finallyRethrows(function () {
return Promise.resolve(_this2.playthroughInstance.getMessageHistory(_this2.id, _this2.lastEventId)).then(function (_ref) {
var messages = _ref.messages;
if (messages.length > 0) {
_this2.emit("playback-start");
messages.forEach(function (message) {
if (typeof BigInt === "undefined") {
if (message.timestamp > _this2.lastTimestamp) {
_this2.emit("message", _extends({}, message, {
conversationId: _this2.id
}));
}
} else if (BigInt(message.eventId) > BigInt(_this2.lastEventId)) {
_this2.emit("message", _extends({}, message, {
conversationId: _this2.id
}));
}
});
_this2.emit("playback-stop");
}
});
}, function (_wasThrown, _result) {
_this2.eventQueue.start();
if (_wasThrown) throw _result;
return _result;
});
if (_temp4 && _temp4.then) return _temp4.then(function () {});
}
}();
return Promise.resolve(_temp3 && _temp3.then ? _temp3.then(function () {}) : void 0);
} catch (e) {
return Promise.reject(e);
}
};
_this2.id = conversationId;
_this2.playthroughInstance = playthroughInstance;
if (options) {
_this2.options = options;
}
_this2.on("message", function (message) {
_this2.lastEventId = message.eventId;
_this2.lastTimestamp = message.timestamp;
});
return _this2;
}
return Conversation;
}(EventEmitter__default['default']);
function _catch$1(body, recover) {
try {
var result = body();
} catch (e) {
return recover(e);
}
if (result && result.then) {
return result.then(void 0, recover);
}
return result;
}
var Playthrough = /*#__PURE__*/function (_EventEmitter) {
_inheritsLoose(Playthrough, _EventEmitter);
function Playthrough(token, baseUrl) {
var _this;
_this = _EventEmitter.call(this) || this;
_this.connectionStatus = "disconnected";
_this.shouldReconnect = true;
_this.activeConversations = new Map();
_this.joinConversation = function (conversationId, options) {
var conversation = new Conversation(conversationId, _assertThisInitialized(_this), options);
if (_this.activeConversations.has(conversationId)) {
return _this.activeConversations.get(conversationId);
}
_this.activeConversations.set(conversationId, conversation);
return conversation;
};
_this.leaveConversation = function (conversationId) {
if (!_this.activeConversations.has(conversationId)) {
throw new Error("The conversation with id `" + conversationId + "` has not been joined, so cannot be left.");
}
_this.activeConversations["delete"](conversationId);
};
_this.getConversation = function (conversationId) {
return _this.activeConversations.get(conversationId);
};
_this.addOutgoingEvent = function (eventName, eventData) {
if (_this.room) {
if (_this.connectionStatus === "connected") {
_this.room.send(eventName, eventData);
} else {
console.warn("Event `" + eventName + "` was not sent as the socket was not ready. Wait for the `connection-status` event to be called with `connected` before sending events.");
}
} else {
console.log("Event `" + eventName + "` was not sent as the socket was not initialised. Call `playthrough.connect()` to connect the socket.");
}
};
_this.connect = function () {
try {
var _baseUrl = _this.baseUrl || getGlobalBaseUrl();
if (!_this.client) {
_this.client = new Colyseus.Client(_baseUrl.replace(/^http/, "ws"));
}
return Promise.resolve(_this.client.joinOrCreate("chat", {
playthroughId: _this.playthroughId,
token: _this.token
})).then(function (_this$client$joinOrCr) {
_this.room = _this$client$joinOrCr;
_this.attachRoomHandlers(_this.room);
_this.shouldReconnect = true;
});
} catch (e) {
return Promise.reject(e);
}
};
_this.pause = function () {
_this.addOutgoingEvent("pause");
};
_this.play = function () {
_this.addOutgoingEvent("play");
};
_this.attachRoomHandlers = function (room) {
room.onMessage("status", _this.onConnected);
room.onMessage("problem", _this.onProblem);
room.onMessage("start-typing", _this.onStartTyping);
room.onMessage("stop-typing", _this.onStopTyping);
room.onMessage("message", _this.onMessage);
room.onMessage("episode-complete", _this.onEpisodeComplete);
room.onError(_this.onError);
room.onLeave(function (code) {
try {
var _exit3;
var _temp7 = function _temp7(_result5) {
if (_exit3) return _result5;
_this.onDisconnect();
};
room.removeAllListeners();
_this.room = undefined;
if (code === 4000 || !_this.shouldReconnect) {
_this.onDisconnect();
return Promise.resolve();
}
var roomExpired = false;
var _attempts = 0;
var _temp8 = _for(function () {
return !_exit3 && _attempts < 20;
}, function () {
return !!(_attempts += 1);
}, function () {
function _temp4(_result2) {
var _exit2;
if (_exit3) return _result2;
function _temp2(_result4) {
return _exit2 ? _result4 : Promise.resolve(new Promise(function (resolve) {
return setTimeout(function () {
return resolve();
}, 5000 + Math.floor(Math.random() * 1000));
})).then(function () {});
}
var _temp = function () {
if (roomExpired) {
return _catch$1(function () {
var _this$client;
return Promise.resolve((_this$client = _this.client) == null ? void 0 : _this$client.joinOrCreate("chat", {
playthroughId: _this.playthroughId,
token: _this.token
})).then(function (newRoom) {
if (newRoom) {
_this.attachRoomHandlers(newRoom);
_this.room = newRoom;
_this.onReconnect();
_this.onConnected();
_exit3 = 1;
}
});
}, function (err2) {
console.error("Could not reconnect to a Charisma playthrough.", err2);
});
}
}();
return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp);
}
var _temp3 = function () {
if (!roomExpired) {
return _catch$1(function () {
var _this$client2;
_this.onReconnecting();
return Promise.resolve((_this$client2 = _this.client) == null ? void 0 : _this$client2.reconnect(room.id, room.sessionId)).then(function (newRoom) {
if (newRoom) {
_this.attachRoomHandlers(newRoom);
_this.room = newRoom;
_this.onReconnect();
_this.onConnected();
_exit3 = 1;
}
});
}, function (err) {
if (/room ".*" not found/.test(err.message)) {
roomExpired = true;
}
});
}
}();
return _temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3);
});
return Promise.resolve(_temp8 && _temp8.then ? _temp8.then(_temp7) : _temp7(_temp8));
} catch (e) {
return Promise.reject(e);
}
});
};
_this.disconnect = function () {
_this.shouldReconnect = false;
if (_this.room) {
_this.room.leave();
}
};
_this.changeConnectionStatus = function (newStatus) {
if (newStatus !== _this.connectionStatus) {
_this.connectionStatus = newStatus;
_this.emit("connection-status", newStatus);
}
};
_this.onReconnect = function () {
_this.activeConversations.forEach(function (conversation) {
conversation.reconnect()["catch"](function (err) {
console.error("Something went wrong reconnecting to conversation:", err);
});
});
};
_this.onReconnecting = function () {
_this.changeConnectionStatus("connecting");
};
_this.onDisconnect = function () {
_this.changeConnectionStatus("disconnected");
};
_this.onConnected = function () {
_this.changeConnectionStatus("connected");
};
_this.onError = function (code, message) {
_this.emit("error", {
message: message,
code: code
});
};
_this.onProblem = function (problem) {
_this.emit("problem", problem);
};
_this.onStartTyping = function (event) {
var conversation = _this.activeConversations.get(event.conversationId);
if (conversation) {
conversation.addIncomingEvent("start-typing", event);
}
};
_this.onStopTyping = function (event) {
var conversation = _this.activeConversations.get(event.conversationId);
if (conversation) {
conversation.addIncomingEvent("stop-typing", event);
}
};
_this.onMessage = function (event) {
var conversation = _this.activeConversations.get(event.conversationId);
if (conversation) {
conversation.addIncomingEvent("message", event);
}
};
_this.onEpisodeComplete = function (event) {
var conversation = _this.activeConversations.get(event.conversationId);
if (conversation) {
conversation.addIncomingEvent("episode-complete", event);
}
};
_this.token = token;
var _jwtDecode = jwtDecode__default['default'](_this.token),
playthroughId = _jwtDecode.playthrough_id;
_this.playthroughId = playthroughId;
_this.baseUrl = baseUrl;
return _this;
}
var _proto = Playthrough.prototype;
_proto.createConversation = function createConversation$1() {
return createConversation(this.token, {
baseUrl: this.baseUrl
});
};
_proto.createCharacterConversation = function createCharacterConversation$1(characterId) {
return createCharacterConversation(this.token, characterId, {
baseUrl: this.baseUrl
});
};
_proto.getMessageHistory = function getMessageHistory$1(conversationId, minEventId) {
return getMessageHistory(this.token, conversationId, minEventId, {
baseUrl: this.baseUrl
});
};
_proto.getPlaythroughInfo = function getPlaythroughInfo$1() {
return getPlaythroughInfo(this.token, {
baseUrl: this.baseUrl
});
};
_proto.setMemory = function setMemory$1(memoryIdOrRecallValue, saveValue) {
return setMemory(this.token, memoryIdOrRecallValue, saveValue, {
baseUrl: this.baseUrl
});
};
_proto.restartFromEpisodeId = function restartFromEpisodeId$1(episodeId) {
return restartFromEpisodeId(this.token, episodeId, {
baseUrl: this.baseUrl
});
};
_proto.restartFromEpisodeIndex = function restartFromEpisodeIndex$1(episodeIndex) {
return restartFromEpisodeIndex(this.token, episodeIndex, {
baseUrl: this.baseUrl
});
};
_proto.restartFromEventId = function restartFromEventId$1(eventId) {
return restartFromEventId(this.token, eventId, {
baseUrl: this.baseUrl
});
};
return Playthrough;
}(EventEmitter__default['default']);
function _settle(pact, state, value) {
if (!pact.s) {
if (value instanceof _Pact) {
if (value.s) {
if (state & 1) {
state = value.s;
}
value = value.v;
} else {
value.o = _settle.bind(null, pact, state);
return;
}
}
if (value && value.then) {
value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2));
return;
}
pact.s = state;
pact.v = value;
var observer = pact.o;
if (observer) {
observer(pact);
}
}
}
var _Pact = /*#__PURE__*/function () {
function _Pact() {}
_Pact.prototype.then = function (onFulfilled, onRejected) {
var result = new _Pact();
var state = this.s;
if (state) {
var callback = state & 1 ? onFulfilled : onRejected;
if (callback) {
try {
_settle(result, 1, callback(this.v));
} catch (e) {
_settle(result, 2, e);
}
return result;
} else {
return this;
}
}
this.o = function (_this) {
try {
var value = _this.v;
if (_this.s & 1) {
_settle(result, 1, onFulfilled ? onFulfilled(value) : value);
} else if (onRejected) {
_settle(result, 1, onRejected(value));
} else {
_settle(result, 2, value);
}
} catch (e) {
_settle(result, 2, e);
}
};
return result;
};
return _Pact;
}();
function _isSettledPact(thenable) {
return thenable instanceof _Pact && thenable.s & 1;
}
function _for(test, update, body) {
var stage;
for (;;) {
var shouldContinue = test();
if (_isSettledPact(shouldContinue)) {
shouldContinue = shouldContinue.v;
}
if (!shouldContinue) {
return result;
}
if (shouldContinue.then) {
stage = 0;
break;
}
var result = body();
if (result && result.then) {
if (_isSettledPact(result)) {
result = result.s;
} else {
stage = 1;
break;
}
}
if (update) {
var updateValue = update();
if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
stage = 2;
break;
}
}
}
var pact = new _Pact();
var reject = _settle.bind(null, pact, 2);
(stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
return pact;
function _resumeAfterBody(value) {
result = value;
do {
if (update) {
updateValue = update();
if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
updateValue.then(_resumeAfterUpdate).then(void 0, reject);
return;
}
}
shouldContinue = test();
if (!shouldContinue || _isSettledPact(shouldContinue) && !shouldContinue.v) {
_settle(pact, 1, result);
return;
}
if (shouldContinue.then) {
shouldContinue.then(_resumeAfterTest).then(void 0, reject);
return;
}
result = body();
if (_isSettledPact(result)) {
result = result.v;
}
} while (!result || !result.then);
result.then(_resumeAfterBody).then(void 0, reject);
}
function _resumeAfterTest(shouldContinue) {
if (shouldContinue) {
result = body();
if (result && result.then) {
result.then(_resumeAfterBody).then(void 0, reject);
} else {
_resumeAfterBody(result);
}
} else {
_settle(pact, 1, result);
}
}
function _resumeAfterUpdate() {
if (shouldContinue = test()) {
if (shouldContinue.then) {
shouldContinue.then(_resumeAfterTest).then(void 0, reject);
} else {
_resumeAfterTest(shouldContinue);
}
} else {
_settle(pact, 1, result);
}
}
}
var SpeechRecognitionClass = typeof window !== "undefined" ? window.SpeechRecognition || window.webkitSpeechRecognition : undefined;
var Microphone = /*#__PURE__*/function (_EventEmitter) {
_inheritsLoose(Microphone, _EventEmitter);
function Microphone() {
var _this;
_this = _EventEmitter.apply(this, arguments) || this;
_this.recognition = SpeechRecognitionClass ? new SpeechRecognitionClass() : undefined;
_this.isSupported = SpeechRecognitionClass !== undefined;
_this.startListening = function (_temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$continuous = _ref.continuous,
continuous = _ref$continuous === void 0 ? false : _ref$continuous,
_ref$interimResults = _ref.interimResults,
interimResults = _ref$interimResults === void 0 ? true : _ref$interimResults,
_ref$lang = _ref.lang,
lang = _ref$lang === void 0 ? "en-GB" : _ref$lang,
timeout = _ref.timeout;
if (!_this.recognition) {
return;
}
if (_this.timeoutId !== undefined) {
clearTimeout(_this.timeoutId);
}
var _assertThisInitialize = _assertThisInitialized(_this),
recognition = _assertThisInitialize.recognition;
recognition.continuous = continuous;
recognition.interimResults = interimResults;
recognition.lang = lang;
recognition.onresult = _this.onRecognitionResult;
recognition.onstart = function () {
_this.emit("start");
};
recognition.onend = function () {
_this.emit("stop");
recognition.start();
};
recognition.onerror = function (event) {
_this.emit("error", event.error);
};
try {
recognition.start();
} catch (err) {}
if (timeout !== undefined) {
_this.timeoutId = window.setTimeout(_this.onTimeout, timeout);
}
};
_this.stopListening = function (_temp2) {
var _ref2 = _temp2 === void 0 ? {} : _temp2,
_ref2$waitForLastResu = _ref2.waitForLastResult,
waitForLastResult = _ref2$waitForLastResu === void 0 ? false : _ref2$waitForLastResu;
if (_this.timeoutId !== undefined) {
clearTimeout(_this.timeoutId);
}
var _assertThisInitialize2 = _assertThisInitialized(_this),
recognition = _assertThisInitialize2.recognition;
if (recognition) {
if (!waitForLastResult) {
recognition.onresult = function () {
return undefined;
};
}
recognition.onend = function () {
_this.emit("stop");
};
try {
if (waitForLastResult) {
recognition.stop();
} else {
recognition.abort();
}
} catch (err) {}
}
};
_this.resetTimeout = function (timeout) {
if (_this.timeoutId !== undefined) {
clearTimeout(_this.timeoutId);
}
_this.timeoutId = window.setTimeout(_this.onTimeout, timeout);
};
_this.onTimeout = function () {
_this.timeoutId = undefined;
_this.emit("timeout");
_this.stopListening();
};
_this.onRecognitionResult = function (event) {
if (event.results && event.results[0] && event.results[0][0]) {
var message = event.results[0][0].transcript.trim();
if (event.results[0].isFinal === false) {
_this.emit("recognise-interim", message);
} else {
_this.emit("recognise", message);
}
}
};
return _this;
}
return Microphone;
}(EventEmitter__default['default']);
var Speaker = /*#__PURE__*/function (_EventEmitter) {
_inheritsLoose(Speaker, _EventEmitter);
function Speaker() {
var _this;
_this = _EventEmitter.apply(this, arguments) || this;
_this.currentSources = [];
_this.getAudioContext = function () {
if (_this.audioContext) {
return _this.audioContext;
}
var AudioContextClass = window.AudioContext || window.webkitAudioContext;
if (!AudioContextClass) {
throw new Error("AudioContext isn't supported in this browser.");
}
var audioContext = new AudioContextClass();
_this.audioContext = audioContext;
return audioContext;
};
_this.play = function (audio, options) {
if (options === void 0) {
options = {};
}
try {
if (typeof options === "boolean") {
console.warn("Passing a boolean as the second parameter to `speaker.play()` is deprecated, and should be updated to use an `options` object.");
options = {
interrupt: options ? "all" : "none"
};
}
var _options = options,
_options$interrupt = _options.interrupt,
interrupt = _options$interrupt === void 0 ? "none" : _options$interrupt,
trackId = _options.trackId;
var audioContext = _this.getAudioContext();
var source = audioContext.createBufferSource();
source.connect(audioContext.destination);
return Promise.resolve(new Promise(function (resolve, reject) {
audioContext.decodeAudioData(audio, resolve, reject);
})).then(function (_Promise) {
source.buffer = _Promise;
return audioContext.state !== "running" ? Promise.resolve() : new Promise(function (resolve) {
source.onended = function () {
resolve();
_this.currentSources = _this.currentSources.filter(function (currentSource) {
return currentSource.sourceNode !== source;
});
if (_this.currentSources.length === 0) {
_this.emit("stop");
}
};
if (_this.currentSources.length > 0 && interrupt !== "none") {
_this.currentSources.forEach(function (currentSource) {
if (interrupt === "all" || interrupt === "track" && currentSource.trackId === trackId) {
currentSource.sourceNode.stop();
}
});
}
if (_this.currentSources.length === 0) {
_this.emit("start");
}
_this.currentSources.push({
sourceNode: source,
trackId: trackId
});
source.start();
});
});
} catch (e) {
return Promise.reject(e);
}
};
return _this;
}
return Speaker;
}(EventEmitter__default['default']);
exports.ImageLayerResizeMode = void 0;
(function (ImageLayerResizeMode) {
ImageLayerResizeMode["Contain"] = "contain";
ImageLayerResizeMode["Cover"] = "cover";
})(exports.ImageLayerResizeMode || (exports.ImageLayerResizeMode = {}));
exports.AudioTrackBehaviour = void 0;
(function (AudioTrackBehaviour) {
AudioTrackBehaviour["Continue"] = "continue";
AudioTrackBehaviour["Restart"] = "restart";
})(exports.AudioTrackBehaviour || (exports.AudioTrackBehaviour = {}));
exports.Conversation = Conversation;
exports.Microphone = Microphone;
exports.Playthrough = Playthrough;
exports.Speaker = Speaker;
exports.api = api;
exports.createCharacterConversation = createCharacterConversation;
exports.createConversation = createConversation;
exports.createPlaythroughToken = createPlaythroughToken;
exports.getGlobalBaseUrl = getGlobalBaseUrl;
exports.getMessageHistory = getMessageHistory;
exports.getPlaythroughInfo = getPlaythroughInfo;
exports.restartFromEpisodeId = restartFromEpisodeId;
exports.restartFromEpisodeIndex = restartFromEpisodeIndex;
exports.restartFromEventId = restartFromEventId;
exports.setGlobalBaseUrl = setGlobalBaseUrl;
exports.setMemory = setMemory;
//# sourceMappingURL=index.js.map