UNPKG

11 kBJavaScriptView Raw
1/*
2 * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
5 * the License. A copy of the License is located at
6 *
7 * http://aws.amazon.com/apache2.0/
8 *
9 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
10 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
11 * and limitations under the License.
12 */
13var __extends = (this && this.__extends) || (function () {
14 var extendStatics = function (d, b) {
15 extendStatics = Object.setPrototypeOf ||
16 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
17 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
18 return extendStatics(d, b);
19 };
20 return function (d, b) {
21 extendStatics(d, b);
22 function __() { this.constructor = d; }
23 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
24 };
25})();
26var __assign = (this && this.__assign) || function () {
27 __assign = Object.assign || function(t) {
28 for (var s, i = 1, n = arguments.length; i < n; i++) {
29 s = arguments[i];
30 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
31 t[p] = s[p];
32 }
33 return t;
34 };
35 return __assign.apply(this, arguments);
36};
37var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
38 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
39 return new (P || (P = Promise))(function (resolve, reject) {
40 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
41 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
42 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
43 step((generator = generator.apply(thisArg, _arguments || [])).next());
44 });
45};
46var __generator = (this && this.__generator) || function (thisArg, body) {
47 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
48 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
49 function verb(n) { return function (v) { return step([n, v]); }; }
50 function step(op) {
51 if (f) throw new TypeError("Generator is already executing.");
52 while (_) try {
53 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
54 if (y = 0, t) op = [op[0] & 2, t.value];
55 switch (op[0]) {
56 case 0: case 1: t = op; break;
57 case 4: _.label++; return { value: op[1], done: false };
58 case 5: _.label++; y = op[1]; op = [0]; continue;
59 case 7: op = _.ops.pop(); _.trys.pop(); continue;
60 default:
61 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
62 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
63 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
64 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
65 if (t[2]) _.ops.pop();
66 _.trys.pop(); continue;
67 }
68 op = body.call(thisArg, _);
69 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
70 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
71 }
72};
73import { AbstractInteractionsProvider } from './InteractionsProvider';
74import { LexRuntimeServiceClient, PostTextCommand, PostContentCommand, } from '@aws-sdk/client-lex-runtime-service';
75import { ConsoleLogger as Logger, Credentials, getAmplifyUserAgent, } from '@aws-amplify/core';
76import { convert } from './AWSLexProviderHelper/convert';
77var logger = new Logger('AWSLexProvider');
78var AWSLexProvider = /** @class */ (function (_super) {
79 __extends(AWSLexProvider, _super);
80 function AWSLexProvider(options) {
81 if (options === void 0) { options = {}; }
82 var _this = _super.call(this, options) || this;
83 _this._botsCompleteCallback = {};
84 return _this;
85 }
86 AWSLexProvider.prototype.getProviderName = function () {
87 return 'AWSLexProvider';
88 };
89 AWSLexProvider.prototype.reportBotStatus = function (data, botname) {
90 var _this = this;
91 // Check if state is fulfilled to resolve onFullfilment promise
92 logger.debug('postContent state', data.dialogState);
93 if (data.dialogState === 'ReadyForFulfillment' ||
94 data.dialogState === 'Fulfilled') {
95 if (typeof this._botsCompleteCallback[botname] === 'function') {
96 setTimeout(function () {
97 return _this._botsCompleteCallback[botname](null, { slots: data.slots });
98 }, 0);
99 }
100 if (this._config &&
101 typeof this._config[botname].onComplete === 'function') {
102 setTimeout(function () { return _this._config[botname].onComplete(null, { slots: data.slots }); }, 0);
103 }
104 }
105 if (data.dialogState === 'Failed') {
106 if (typeof this._botsCompleteCallback[botname] === 'function') {
107 setTimeout(function () { return _this._botsCompleteCallback[botname]('Bot conversation failed'); }, 0);
108 }
109 if (this._config &&
110 typeof this._config[botname].onComplete === 'function') {
111 setTimeout(function () { return _this._config[botname].onComplete('Bot conversation failed'); }, 0);
112 }
113 }
114 };
115 AWSLexProvider.prototype.sendMessage = function (botname, message) {
116 return __awaiter(this, void 0, void 0, function () {
117 var credentials, params, postTextCommand, data, err_1, content, messageType, postContentCommand, data, audioArray, err_2;
118 return __generator(this, function (_a) {
119 switch (_a.label) {
120 case 0:
121 if (!this._config[botname]) {
122 return [2 /*return*/, Promise.reject('Bot ' + botname + ' does not exist')];
123 }
124 return [4 /*yield*/, Credentials.get()];
125 case 1:
126 credentials = _a.sent();
127 if (!credentials) {
128 return [2 /*return*/, Promise.reject('No credentials')];
129 }
130 this.lexRuntimeServiceClient = new LexRuntimeServiceClient({
131 region: this._config[botname].region,
132 credentials: credentials,
133 customUserAgent: getAmplifyUserAgent(),
134 });
135 if (!(typeof message === 'string')) return [3 /*break*/, 6];
136 params = {
137 botAlias: this._config[botname].alias,
138 botName: botname,
139 inputText: message,
140 userId: credentials.identityId,
141 };
142 logger.debug('postText to lex', message);
143 _a.label = 2;
144 case 2:
145 _a.trys.push([2, 4, , 5]);
146 postTextCommand = new PostTextCommand(params);
147 return [4 /*yield*/, this.lexRuntimeServiceClient.send(postTextCommand)];
148 case 3:
149 data = _a.sent();
150 this.reportBotStatus(data, botname);
151 return [2 /*return*/, data];
152 case 4:
153 err_1 = _a.sent();
154 return [2 /*return*/, Promise.reject(err_1)];
155 case 5: return [3 /*break*/, 11];
156 case 6:
157 content = message.content, messageType = message.options.messageType;
158 if (messageType === 'voice') {
159 params = {
160 botAlias: this._config[botname].alias,
161 botName: botname,
162 contentType: 'audio/x-l16; sample-rate=16000',
163 inputStream: content,
164 userId: credentials.identityId,
165 accept: 'audio/mpeg',
166 };
167 }
168 else {
169 params = {
170 botAlias: this._config[botname].alias,
171 botName: botname,
172 contentType: 'text/plain; charset=utf-8',
173 inputStream: content,
174 userId: credentials.identityId,
175 accept: 'audio/mpeg',
176 };
177 }
178 logger.debug('postContent to lex', message);
179 _a.label = 7;
180 case 7:
181 _a.trys.push([7, 10, , 11]);
182 postContentCommand = new PostContentCommand(params);
183 return [4 /*yield*/, this.lexRuntimeServiceClient.send(postContentCommand)];
184 case 8:
185 data = _a.sent();
186 return [4 /*yield*/, convert(data.audioStream)];
187 case 9:
188 audioArray = _a.sent();
189 this.reportBotStatus(data, botname);
190 return [2 /*return*/, __assign(__assign({}, data), { audioStream: audioArray })];
191 case 10:
192 err_2 = _a.sent();
193 return [2 /*return*/, Promise.reject(err_2)];
194 case 11: return [2 /*return*/];
195 }
196 });
197 });
198 };
199 AWSLexProvider.prototype.onComplete = function (botname, callback) {
200 if (!this._config[botname]) {
201 throw new ErrorEvent('Bot ' + botname + ' does not exist');
202 }
203 this._botsCompleteCallback[botname] = callback;
204 };
205 return AWSLexProvider;
206}(AbstractInteractionsProvider));
207export { AWSLexProvider };
208//# sourceMappingURL=AWSLexProvider.js.map
\No newline at end of file