@aws-amplify/interactions 4.0.51 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/aws-amplify-interactions.js +23054 -6091
  3. package/dist/aws-amplify-interactions.js.map +1 -1
  4. package/dist/aws-amplify-interactions.min.js +4 -4
  5. package/dist/aws-amplify-interactions.min.js.map +1 -1
  6. package/lib/Providers/AWSLexProvider.d.ts +12 -1
  7. package/lib/Providers/AWSLexProvider.js +48 -36
  8. package/lib/Providers/AWSLexProvider.js.map +1 -1
  9. package/lib/Providers/AWSLexProviderHelper/commonUtils.d.ts +1 -0
  10. package/lib/Providers/AWSLexProviderHelper/{convert.native.js → commonUtils.js} +36 -18
  11. package/lib/Providers/AWSLexProviderHelper/commonUtils.js.map +1 -0
  12. package/lib/Providers/AWSLexProviderHelper/utils.d.ts +3 -0
  13. package/lib/Providers/AWSLexProviderHelper/utils.js +83 -0
  14. package/lib/Providers/AWSLexProviderHelper/utils.js.map +1 -0
  15. package/lib/Providers/AWSLexProviderHelper/utils.native.d.ts +3 -0
  16. package/lib/Providers/AWSLexProviderHelper/utils.native.js +100 -0
  17. package/lib/Providers/AWSLexProviderHelper/utils.native.js.map +1 -0
  18. package/lib/Providers/AWSLexV2Provider.d.ts +58 -0
  19. package/lib/Providers/AWSLexV2Provider.js +351 -0
  20. package/lib/Providers/AWSLexV2Provider.js.map +1 -0
  21. package/lib/Providers/index.d.ts +1 -0
  22. package/lib/Providers/index.js +1 -0
  23. package/lib/Providers/index.js.map +1 -1
  24. package/lib/index.d.ts +1 -0
  25. package/lib/index.js +1 -0
  26. package/lib/index.js.map +1 -1
  27. package/lib/types/Providers/AWSLexV2Provider.d.ts +12 -0
  28. package/lib/types/Providers/AWSLexV2Provider.js +3 -0
  29. package/lib/types/Providers/AWSLexV2Provider.js.map +1 -0
  30. package/lib/types/index.d.ts +1 -0
  31. package/lib-esm/Providers/AWSLexProvider.d.ts +12 -1
  32. package/lib-esm/Providers/AWSLexProvider.js +47 -35
  33. package/lib-esm/Providers/AWSLexProvider.js.map +1 -1
  34. package/lib-esm/Providers/AWSLexProviderHelper/commonUtils.d.ts +1 -0
  35. package/lib-esm/Providers/AWSLexProviderHelper/{convert.native.js → commonUtils.js} +36 -18
  36. package/lib-esm/Providers/AWSLexProviderHelper/commonUtils.js.map +1 -0
  37. package/lib-esm/Providers/AWSLexProviderHelper/utils.d.ts +3 -0
  38. package/lib-esm/Providers/AWSLexProviderHelper/utils.js +81 -0
  39. package/lib-esm/Providers/AWSLexProviderHelper/utils.js.map +1 -0
  40. package/lib-esm/Providers/AWSLexProviderHelper/utils.native.d.ts +3 -0
  41. package/lib-esm/Providers/AWSLexProviderHelper/utils.native.js +98 -0
  42. package/lib-esm/Providers/AWSLexProviderHelper/utils.native.js.map +1 -0
  43. package/lib-esm/Providers/AWSLexV2Provider.d.ts +58 -0
  44. package/lib-esm/Providers/AWSLexV2Provider.js +349 -0
  45. package/lib-esm/Providers/AWSLexV2Provider.js.map +1 -0
  46. package/lib-esm/Providers/index.d.ts +1 -0
  47. package/lib-esm/Providers/index.js +1 -0
  48. package/lib-esm/Providers/index.js.map +1 -1
  49. package/lib-esm/index.d.ts +1 -0
  50. package/lib-esm/index.js +1 -0
  51. package/lib-esm/index.js.map +1 -1
  52. package/lib-esm/types/Providers/AWSLexV2Provider.d.ts +12 -0
  53. package/lib-esm/types/Providers/AWSLexV2Provider.js +1 -0
  54. package/lib-esm/types/Providers/AWSLexV2Provider.js.map +1 -0
  55. package/lib-esm/types/index.d.ts +1 -0
  56. package/package.json +8 -4
  57. package/src/Providers/AWSLexProvider.ts +28 -18
  58. package/src/Providers/AWSLexProviderHelper/commonUtils.ts +27 -0
  59. package/src/Providers/AWSLexProviderHelper/utils.native.ts +56 -0
  60. package/src/Providers/AWSLexProviderHelper/utils.ts +39 -0
  61. package/src/Providers/AWSLexV2Provider.ts +343 -0
  62. package/src/Providers/index.ts +1 -0
  63. package/src/index.ts +1 -0
  64. package/src/types/Providers/AWSLexProvider.ts +12 -0
  65. package/src/types/Providers/AWSLexV2Provider.ts +25 -0
  66. package/src/types/index.ts +1 -0
  67. package/lib/Providers/AWSLexProviderHelper/convert.d.ts +0 -3
  68. package/lib/Providers/AWSLexProviderHelper/convert.js +0 -13
  69. package/lib/Providers/AWSLexProviderHelper/convert.js.map +0 -1
  70. package/lib/Providers/AWSLexProviderHelper/convert.native.d.ts +0 -1
  71. package/lib/Providers/AWSLexProviderHelper/convert.native.js.map +0 -1
  72. package/lib-esm/Providers/AWSLexProviderHelper/convert.d.ts +0 -3
  73. package/lib-esm/Providers/AWSLexProviderHelper/convert.js +0 -11
  74. package/lib-esm/Providers/AWSLexProviderHelper/convert.js.map +0 -1
  75. package/lib-esm/Providers/AWSLexProviderHelper/convert.native.d.ts +0 -1
  76. package/lib-esm/Providers/AWSLexProviderHelper/convert.native.js.map +0 -1
  77. package/src/Providers/AWSLexProviderHelper/convert.native.ts +0 -13
  78. package/src/Providers/AWSLexProviderHelper/convert.ts +0 -12
@@ -0,0 +1,349 @@
1
+ var __extends = (this && this.__extends) || (function () {
2
+ var extendStatics = function (d, b) {
3
+ extendStatics = Object.setPrototypeOf ||
4
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6
+ return extendStatics(d, b);
7
+ };
8
+ return function (d, b) {
9
+ extendStatics(d, b);
10
+ function __() { this.constructor = d; }
11
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
12
+ };
13
+ })();
14
+ var __assign = (this && this.__assign) || function () {
15
+ __assign = Object.assign || function(t) {
16
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
17
+ s = arguments[i];
18
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
19
+ t[p] = s[p];
20
+ }
21
+ return t;
22
+ };
23
+ return __assign.apply(this, arguments);
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __generator = (this && this.__generator) || function (thisArg, body) {
35
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
+ function verb(n) { return function (v) { return step([n, v]); }; }
38
+ function step(op) {
39
+ if (f) throw new TypeError("Generator is already executing.");
40
+ while (_) try {
41
+ 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;
42
+ if (y = 0, t) op = [op[0] & 2, t.value];
43
+ switch (op[0]) {
44
+ case 0: case 1: t = op; break;
45
+ case 4: _.label++; return { value: op[1], done: false };
46
+ case 5: _.label++; y = op[1]; op = [0]; continue;
47
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
+ default:
49
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
+ if (t[2]) _.ops.pop();
54
+ _.trys.pop(); continue;
55
+ }
56
+ op = body.call(thisArg, _);
57
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
+ }
60
+ };
61
+ /*
62
+ * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
63
+ *
64
+ * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
65
+ * the License. A copy of the License is located at
66
+ *
67
+ * http://aws.amazon.com/apache2.0/
68
+ *
69
+ * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
70
+ * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
71
+ * and limitations under the License.
72
+ */
73
+ import { AbstractInteractionsProvider } from './InteractionsProvider';
74
+ import { LexRuntimeV2Client, RecognizeTextCommand, RecognizeUtteranceCommand, } from '@aws-sdk/client-lex-runtime-v2';
75
+ import { ConsoleLogger as Logger, Credentials, getAmplifyUserAgent, } from '@aws-amplify/core';
76
+ import { convert } from './AWSLexProviderHelper/utils';
77
+ import { unGzipBase64AsJson } from './AWSLexProviderHelper/commonUtils';
78
+ var logger = new Logger('AWSLexV2Provider');
79
+ var AWSLexV2Provider = /** @class */ (function (_super) {
80
+ __extends(AWSLexV2Provider, _super);
81
+ /**
82
+ * Initialize Interactions with AWS configurations
83
+ * @param {InteractionsOptions} options - Configuration object for Interactions
84
+ */
85
+ function AWSLexV2Provider(options) {
86
+ if (options === void 0) { options = {}; }
87
+ var _this = _super.call(this, options) || this;
88
+ _this._botsCompleteCallback = {};
89
+ return _this;
90
+ }
91
+ /**
92
+ * get provider name of the plugin
93
+ * @returns {string} name of the provider
94
+ */
95
+ AWSLexV2Provider.prototype.getProviderName = function () {
96
+ return 'AWSLexV2Provider';
97
+ };
98
+ /**
99
+ * Configure Interactions part with aws configuration
100
+ * @param {AWSLexV2ProviderOptions} config - Configuration of the Interactions
101
+ * @return {AWSLexV2ProviderOptions} - Current configuration
102
+ */
103
+ AWSLexV2Provider.prototype.configure = function (config) {
104
+ if (config === void 0) { config = {}; }
105
+ var propertiesToTest = [
106
+ 'name',
107
+ 'botId',
108
+ 'aliasId',
109
+ 'localeId',
110
+ 'providerName',
111
+ 'region',
112
+ ];
113
+ Object.keys(config).forEach(function (botKey) {
114
+ var botConfig = config[botKey];
115
+ // is bot config correct
116
+ if (!propertiesToTest.every(function (x) { return x in botConfig; })) {
117
+ throw new Error('invalid bot configuration');
118
+ }
119
+ });
120
+ return _super.prototype.configure.call(this, config);
121
+ };
122
+ /**
123
+ * Send a message to a bot
124
+ * @async
125
+ * @param {string} botname - Bot name to send the message
126
+ * @param {string | InteractionsMessage} message - message to send to the bot
127
+ * @return {Promise<InteractionsResponse>} A promise resolves to the response from the bot
128
+ */
129
+ AWSLexV2Provider.prototype.sendMessage = function (botname, message) {
130
+ return __awaiter(this, void 0, void 0, function () {
131
+ var credentials, error_1, response, reqBaseParams;
132
+ return __generator(this, function (_a) {
133
+ switch (_a.label) {
134
+ case 0:
135
+ // check if bot exists
136
+ if (!this._config[botname]) {
137
+ return [2 /*return*/, Promise.reject('Bot ' + botname + ' does not exist')];
138
+ }
139
+ _a.label = 1;
140
+ case 1:
141
+ _a.trys.push([1, 3, , 4]);
142
+ return [4 /*yield*/, Credentials.get()];
143
+ case 2:
144
+ credentials = _a.sent();
145
+ return [3 /*break*/, 4];
146
+ case 3:
147
+ error_1 = _a.sent();
148
+ return [2 /*return*/, Promise.reject('No credentials')];
149
+ case 4:
150
+ this._lexRuntimeServiceV2Client = new LexRuntimeV2Client({
151
+ region: this._config[botname].region,
152
+ credentials: credentials,
153
+ customUserAgent: getAmplifyUserAgent(),
154
+ });
155
+ reqBaseParams = {
156
+ botAliasId: this._config[botname].aliasId,
157
+ botId: this._config[botname].botId,
158
+ localeId: this._config[botname].localeId,
159
+ sessionId: credentials.identityId,
160
+ };
161
+ if (!(typeof message === 'string')) return [3 /*break*/, 6];
162
+ return [4 /*yield*/, this._handleRecognizeTextCommand(botname, message, reqBaseParams)];
163
+ case 5:
164
+ response = _a.sent();
165
+ return [3 /*break*/, 8];
166
+ case 6: return [4 /*yield*/, this._handleRecognizeUtteranceCommand(botname, message, reqBaseParams)];
167
+ case 7:
168
+ response = _a.sent();
169
+ _a.label = 8;
170
+ case 8: return [2 /*return*/, response];
171
+ }
172
+ });
173
+ });
174
+ };
175
+ /**
176
+ * Attach a onComplete callback function to a bot.
177
+ * The callback is called once the bot's intent is fulfilled
178
+ * @param {string} botname - Bot name to attach the onComplete callback
179
+ * @param {(err: Error | null, confirmation: InteractionsResponse) => void} callback - called when Intent Fulfilled
180
+ */
181
+ AWSLexV2Provider.prototype.onComplete = function (botname, callback) {
182
+ // does bot exist
183
+ if (!this._config[botname]) {
184
+ throw new Error('Bot ' + botname + ' does not exist');
185
+ }
186
+ this._botsCompleteCallback[botname] = callback;
187
+ };
188
+ /**
189
+ * @private
190
+ * call onComplete callback for a bot if configured
191
+ */
192
+ AWSLexV2Provider.prototype._reportBotStatus = function (data, botname) {
193
+ var _this = this;
194
+ var _a, _b, _c, _d, _e, _f;
195
+ var sessionState = data === null || data === void 0 ? void 0 : data.sessionState;
196
+ // Check if state is fulfilled to resolve onFullfilment promise
197
+ logger.debug('postContent state', (_a = sessionState === null || sessionState === void 0 ? void 0 : sessionState.intent) === null || _a === void 0 ? void 0 : _a.state);
198
+ var isConfigOnCompleteAttached = typeof ((_b = this._config) === null || _b === void 0 ? void 0 : _b[botname].onComplete) === 'function';
199
+ var isApiOnCompleteAttached = typeof ((_c = this._botsCompleteCallback) === null || _c === void 0 ? void 0 : _c[botname]) === 'function';
200
+ // no onComplete callbacks added
201
+ if (!isConfigOnCompleteAttached && !isApiOnCompleteAttached)
202
+ return;
203
+ if (((_d = sessionState === null || sessionState === void 0 ? void 0 : sessionState.intent) === null || _d === void 0 ? void 0 : _d.state) === 'ReadyForFulfillment' ||
204
+ ((_e = sessionState === null || sessionState === void 0 ? void 0 : sessionState.intent) === null || _e === void 0 ? void 0 : _e.state) === 'Fulfilled') {
205
+ if (isApiOnCompleteAttached) {
206
+ setTimeout(function () { var _a; return (_a = _this._botsCompleteCallback) === null || _a === void 0 ? void 0 : _a[botname](null, data); }, 0);
207
+ }
208
+ if (isConfigOnCompleteAttached) {
209
+ setTimeout(function () { return _this._config[botname].onComplete(null, data); }, 0);
210
+ }
211
+ }
212
+ if (((_f = sessionState === null || sessionState === void 0 ? void 0 : sessionState.intent) === null || _f === void 0 ? void 0 : _f.state) === 'Failed') {
213
+ var error_2 = new Error('Bot conversation failed');
214
+ if (isApiOnCompleteAttached) {
215
+ setTimeout(function () { return _this._botsCompleteCallback[botname](error_2); }, 0);
216
+ }
217
+ if (isConfigOnCompleteAttached) {
218
+ setTimeout(function () { return _this._config[botname].onComplete(error_2); }, 0);
219
+ }
220
+ }
221
+ };
222
+ /**
223
+ * Format UtteranceCommandOutput's response
224
+ * decompress attributes
225
+ * update audioStream format
226
+ */
227
+ AWSLexV2Provider.prototype._formatUtteranceCommandOutput = function (data) {
228
+ return __awaiter(this, void 0, void 0, function () {
229
+ var response, _a, _b, _c;
230
+ return __generator(this, function (_d) {
231
+ switch (_d.label) {
232
+ case 0:
233
+ _a = [__assign({}, data)];
234
+ _b = {};
235
+ return [4 /*yield*/, unGzipBase64AsJson(data.messages)];
236
+ case 1:
237
+ _b.messages = _d.sent();
238
+ return [4 /*yield*/, unGzipBase64AsJson(data.sessionState)];
239
+ case 2:
240
+ _b.sessionState = _d.sent();
241
+ return [4 /*yield*/, unGzipBase64AsJson(data.interpretations)];
242
+ case 3:
243
+ _b.interpretations = _d.sent();
244
+ return [4 /*yield*/, unGzipBase64AsJson(data.requestAttributes)];
245
+ case 4:
246
+ _b.requestAttributes = _d.sent();
247
+ return [4 /*yield*/, unGzipBase64AsJson(data.inputTranscript)];
248
+ case 5:
249
+ _b.inputTranscript = _d.sent();
250
+ if (!data.audioStream) return [3 /*break*/, 7];
251
+ return [4 /*yield*/, convert(data.audioStream)];
252
+ case 6:
253
+ _c = _d.sent();
254
+ return [3 /*break*/, 8];
255
+ case 7:
256
+ _c = undefined;
257
+ _d.label = 8;
258
+ case 8:
259
+ response = __assign.apply(void 0, _a.concat([(_b.audioStream = _c, _b)]));
260
+ return [2 /*return*/, response];
261
+ }
262
+ });
263
+ });
264
+ };
265
+ /**
266
+ * handle client's `RecognizeTextCommand`
267
+ * used for sending simple text message
268
+ */
269
+ AWSLexV2Provider.prototype._handleRecognizeTextCommand = function (botname, data, baseParams) {
270
+ return __awaiter(this, void 0, void 0, function () {
271
+ var params, recognizeTextCommand, data_1, err_1;
272
+ return __generator(this, function (_a) {
273
+ switch (_a.label) {
274
+ case 0:
275
+ logger.debug('postText to lex2', data);
276
+ params = __assign(__assign({}, baseParams), { text: data });
277
+ _a.label = 1;
278
+ case 1:
279
+ _a.trys.push([1, 3, , 4]);
280
+ recognizeTextCommand = new RecognizeTextCommand(params);
281
+ return [4 /*yield*/, this._lexRuntimeServiceV2Client.send(recognizeTextCommand)];
282
+ case 2:
283
+ data_1 = _a.sent();
284
+ this._reportBotStatus(data_1, botname);
285
+ return [2 /*return*/, data_1];
286
+ case 3:
287
+ err_1 = _a.sent();
288
+ return [2 /*return*/, Promise.reject(err_1)];
289
+ case 4: return [2 /*return*/];
290
+ }
291
+ });
292
+ });
293
+ };
294
+ /**
295
+ * handle client's `RecognizeUtteranceCommand`
296
+ * used for obj text or obj voice message
297
+ */
298
+ AWSLexV2Provider.prototype._handleRecognizeUtteranceCommand = function (botname, data, baseParams) {
299
+ return __awaiter(this, void 0, void 0, function () {
300
+ var content, messageType, params, inputStream, _a, recognizeUtteranceCommand, data_2, response, err_2;
301
+ return __generator(this, function (_b) {
302
+ switch (_b.label) {
303
+ case 0:
304
+ content = data.content, messageType = data.options.messageType;
305
+ logger.debug('postContent to lex2', data);
306
+ if (!(messageType === 'voice')) return [3 /*break*/, 4];
307
+ if (typeof content !== 'object') {
308
+ return [2 /*return*/, Promise.reject('invalid content type')];
309
+ }
310
+ if (!(content instanceof Uint8Array)) return [3 /*break*/, 1];
311
+ _a = content;
312
+ return [3 /*break*/, 3];
313
+ case 1: return [4 /*yield*/, convert(content)];
314
+ case 2:
315
+ _a = _b.sent();
316
+ _b.label = 3;
317
+ case 3:
318
+ inputStream = _a;
319
+ params = __assign(__assign({}, baseParams), { requestContentType: 'audio/x-l16; sample-rate=16000; channel-count=1', inputStream: inputStream });
320
+ return [3 /*break*/, 5];
321
+ case 4:
322
+ // text input
323
+ if (typeof content !== 'string')
324
+ return [2 /*return*/, Promise.reject('invalid content type')];
325
+ params = __assign(__assign({}, baseParams), { requestContentType: 'text/plain; charset=utf-8', inputStream: content });
326
+ _b.label = 5;
327
+ case 5:
328
+ _b.trys.push([5, 8, , 9]);
329
+ recognizeUtteranceCommand = new RecognizeUtteranceCommand(params);
330
+ return [4 /*yield*/, this._lexRuntimeServiceV2Client.send(recognizeUtteranceCommand)];
331
+ case 6:
332
+ data_2 = _b.sent();
333
+ return [4 /*yield*/, this._formatUtteranceCommandOutput(data_2)];
334
+ case 7:
335
+ response = _b.sent();
336
+ this._reportBotStatus(response, botname);
337
+ return [2 /*return*/, response];
338
+ case 8:
339
+ err_2 = _b.sent();
340
+ return [2 /*return*/, Promise.reject(err_2)];
341
+ case 9: return [2 /*return*/];
342
+ }
343
+ });
344
+ });
345
+ };
346
+ return AWSLexV2Provider;
347
+ }(AbstractInteractionsProvider));
348
+ export { AWSLexV2Provider };
349
+ //# sourceMappingURL=AWSLexV2Provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AWSLexV2Provider.js","sourceRoot":"","sources":["../../src/Providers/AWSLexV2Provider.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,4BAA4B,EAAE,MAAM,wBAAwB,CAAC;AAOtE,OAAO,EACN,kBAAkB,E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AsB,CAAC,EAAC;wBAE/C,MAAM,yBACF,UAAU,KACb,kBAAkB,EAAE,2BAA2B,EAC/C,WAAW,EAAE,OAAO,GACpB,CAAC;;;;wBAKI,yBAAyB,GAAG,IAAI,yBAAyB,CAAC,MAAM,CAAC,CAAC;wBAC3D,qBAAM,IAAI,CAAC,0BAA0B,CAAC,IAAI,CACtD,yBAAyB,CACzB,EAAA;;wBAFK,SAAO,SAEZ;wBAEgB,qBAAM,IAAI,CAAC,6BAA6B,CAAC,MAAI,CAAC,EAAA;;wBAAzD,QAAQ,GAAG,SAA8C;wBAC/D,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;wBACzC,sBAAO,QAAQ,EAAC;;;wBAEhB,sBAAO,OAAO,CAAC,MAAM,CAAC,KAAG,CAAC,EAAC;;;;;KAE5B;IACF,uBAAC;AAAD,CAAC,AArRD,CAAsC,4BAA4B,GAqRjE"}
@@ -1,2 +1,3 @@
1
1
  export * from './AWSLexProvider';
2
+ export * from './AWSLexV2Provider';
2
3
  export * from './InteractionsProvider';
@@ -11,5 +11,6 @@
11
11
  * and limitations under the License.
12
12
  */
13
13
  export * from './AWSLexProvider';
14
+ export * from './AWSLexV2Provider';
14
15
  export * from './InteractionsProvider';
15
16
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/Providers/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,cAAc,kBAAkB,CAAC;AACjC,cAAc,wBAAwB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/Providers/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,wBAAwB,CAAC"}
@@ -6,4 +6,5 @@ export default Interactions;
6
6
  export * from './types';
7
7
  export * from './Providers/InteractionsProvider';
8
8
  export * from './Providers/AWSLexProvider';
9
+ export * from './Providers/AWSLexV2Provider';
9
10
  export { Interactions };
package/lib-esm/index.js CHANGED
@@ -17,5 +17,6 @@ import { Interactions } from './Interactions';
17
17
  export default Interactions;
18
18
  export * from './Providers/InteractionsProvider';
19
19
  export * from './Providers/AWSLexProvider';
20
+ export * from './Providers/AWSLexV2Provider';
20
21
  export { Interactions };
21
22
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;GAEG;AACH,eAAe,YAAY,CAAC;AAG5B,cAAc,kCAAkC,CAAC;AACjD,cAAc,4BAA4B,CAAC;AAE3C,OAAO,EAAE,YAAY,EAAE,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE9C;;GAEG;AACH,eAAe,YAAY,CAAC;AAG5B,cAAc,kCAAkC,CAAC;AACjD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,8BAA8B,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1,12 @@
1
+ export interface AWSLexV2ProviderOption {
2
+ name: string;
3
+ botId: string;
4
+ aliasId: string;
5
+ localeId: string;
6
+ region: string;
7
+ providerName: string;
8
+ onComplete?(botname: string, callback: (err: any, confirmation: any) => void): void;
9
+ }
10
+ export interface AWSLexV2ProviderOptions {
11
+ [key: string]: AWSLexV2ProviderOption;
12
+ }
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=AWSLexV2Provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AWSLexV2Provider.js","sourceRoot":"","sources":["../../../src/types/Providers/AWSLexV2Provider.ts"],"names":[],"mappings":""}
@@ -1,4 +1,5 @@
1
1
  export * from './Interactions';
2
2
  export * from './Provider';
3
3
  export * from './Providers/AWSLexProvider';
4
+ export * from './Providers/AWSLexV2Provider';
4
5
  export * from './Response';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aws-amplify/interactions",
3
- "version": "4.0.51",
3
+ "version": "4.1.0",
4
4
  "description": "Interactions category of aws-amplify",
5
5
  "main": "./lib/index.js",
6
6
  "module": "./lib-esm/index.js",
@@ -41,8 +41,12 @@
41
41
  },
42
42
  "homepage": "https://aws-amplify.github.io/",
43
43
  "dependencies": {
44
- "@aws-amplify/core": "4.7.2",
45
- "@aws-sdk/client-lex-runtime-service": "3.6.1"
44
+ "@aws-amplify/core": "4.7.3",
45
+ "@aws-sdk/client-lex-runtime-service": "3.6.1",
46
+ "@aws-sdk/client-lex-runtime-v2": "3.31.0",
47
+ "base-64": "1.0.0",
48
+ "fflate": "0.7.3",
49
+ "pako": "2.0.4"
46
50
  },
47
51
  "jest": {
48
52
  "globals": {
@@ -88,5 +92,5 @@
88
92
  "lib-esm"
89
93
  ]
90
94
  },
91
- "gitHead": "da29d79af1d5bfa585588eac6ac20982891be9af"
95
+ "gitHead": "29e6603f3c943ca8ff0c88c4c6e8c4d7b92d491c"
92
96
  }
@@ -31,10 +31,19 @@ import {
31
31
  Credentials,
32
32
  getAmplifyUserAgent,
33
33
  } from '@aws-amplify/core';
34
- import { convert } from './AWSLexProviderHelper/convert';
34
+ import { convert } from './AWSLexProviderHelper/utils';
35
35
 
36
36
  const logger = new Logger('AWSLexProvider');
37
37
 
38
+ interface PostContentCommandOutputFormatted
39
+ extends Omit<PostContentCommandOutput, 'audioStream'> {
40
+ audioStream?: Uint8Array;
41
+ }
42
+
43
+ type AWSLexProviderSendResponse =
44
+ | PostTextCommandOutput
45
+ | PostContentCommandOutputFormatted;
46
+
38
47
  export class AWSLexProvider extends AbstractInteractionsProvider {
39
48
  private lexRuntimeServiceClient: LexRuntimeServiceClient;
40
49
  private _botsCompleteCallback: object;
@@ -62,10 +71,13 @@ export class AWSLexProvider extends AbstractInteractionsProvider {
62
71
  return super.configure(config);
63
72
  }
64
73
 
65
- reportBotStatus(
66
- data: PostTextCommandOutput | PostContentCommandOutput,
67
- botname: string
68
- ) {
74
+ /**
75
+ * @private
76
+ * @deprecated
77
+ * This is used internally by 'sendMessage' to call onComplete callback
78
+ * for a bot if configured
79
+ */
80
+ reportBotStatus(data: AWSLexProviderSendResponse, botname: string) {
69
81
  // Check if state is fulfilled to resolve onFullfilment promise
70
82
  logger.debug('postContent state', data.dialogState);
71
83
  if (
@@ -73,21 +85,14 @@ export class AWSLexProvider extends AbstractInteractionsProvider {
73
85
  data.dialogState === 'Fulfilled'
74
86
  ) {
75
87
  if (typeof this._botsCompleteCallback[botname] === 'function') {
76
- setTimeout(
77
- () =>
78
- this._botsCompleteCallback[botname](null, { slots: data.slots }),
79
- 0
80
- );
88
+ setTimeout(() => this._botsCompleteCallback[botname](null, data), 0);
81
89
  }
82
90
 
83
91
  if (
84
92
  this._config &&
85
93
  typeof this._config[botname].onComplete === 'function'
86
94
  ) {
87
- setTimeout(
88
- () => this._config[botname].onComplete(null, { slots: data.slots }),
89
- 0
90
- );
95
+ setTimeout(() => this._config[botname].onComplete(null, data), 0);
91
96
  }
92
97
  }
93
98
 
@@ -159,16 +164,19 @@ export class AWSLexProvider extends AbstractInteractionsProvider {
159
164
  options: { messageType },
160
165
  } = message;
161
166
  if (messageType === 'voice') {
162
- if (!(content instanceof Blob || content instanceof ReadableStream))
167
+ if (typeof content !== 'object') {
163
168
  return Promise.reject('invalid content type');
169
+ }
170
+ const inputStream =
171
+ content instanceof Uint8Array ? content : await convert(content);
164
172
 
165
173
  params = {
166
174
  botAlias: this._config[botname].alias,
167
175
  botName: botname,
168
176
  contentType: 'audio/x-l16; sample-rate=16000; channel-count=1',
169
- inputStream: await convert(content),
170
177
  userId: credentials.identityId,
171
178
  accept: 'audio/mpeg',
179
+ inputStream,
172
180
  };
173
181
  } else {
174
182
  if (typeof content !== 'string')
@@ -194,8 +202,10 @@ export class AWSLexProvider extends AbstractInteractionsProvider {
194
202
  ? await convert(data.audioStream)
195
203
  : undefined;
196
204
 
197
- this.reportBotStatus(data, botname);
198
- return { ...data, ...{ audioStream: audioArray } };
205
+ const response = { ...data, ...{ audioStream: audioArray } };
206
+
207
+ this.reportBotStatus(response, botname);
208
+ return response;
199
209
  } catch (err) {
200
210
  return Promise.reject(err);
201
211
  }
@@ -0,0 +1,27 @@
1
+ /*
2
+ * Copyright 2017-2022 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
+ */
13
+ import { base64ToArrayBuffer, gzipDecompressToString } from './utils';
14
+
15
+ export const unGzipBase64AsJson = async (gzipBase64: string | undefined) => {
16
+ if (typeof gzipBase64 === 'undefined') return undefined;
17
+
18
+ try {
19
+ const decodedArrayBuffer = base64ToArrayBuffer(gzipBase64);
20
+
21
+ const objString: string = await gzipDecompressToString(decodedArrayBuffer);
22
+
23
+ return JSON.parse(objString);
24
+ } catch (error) {
25
+ return Promise.reject('unable to decode and decompress ' + error);
26
+ }
27
+ };
@@ -0,0 +1,56 @@
1
+ /*
2
+ * Copyright 2017-2022 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
+ */
13
+
14
+ import { decode } from 'base-64';
15
+ import { ungzip } from 'pako';
16
+
17
+ export const convert = async (stream: object): Promise<Uint8Array> => {
18
+ if (!(stream instanceof Blob)) {
19
+ return Promise.reject('Invalid content type');
20
+ }
21
+
22
+ return new Promise(async (resolve, reject) => {
23
+ try {
24
+ const fileReaderInstance = new FileReader();
25
+ fileReaderInstance.readAsDataURL(stream);
26
+ fileReaderInstance.onload = async () => {
27
+ const blobURL = fileReaderInstance.result as string;
28
+
29
+ const base64Blob = blobURL.split(/,(.*)/s)[1];
30
+
31
+ const decodedArrayBuffer = base64ToArrayBuffer(base64Blob);
32
+ resolve(decodedArrayBuffer);
33
+ };
34
+ } catch (error) {
35
+ reject('unable to convert blob to arrayBuffer: ' + error);
36
+ }
37
+ });
38
+ };
39
+
40
+ export const base64ToArrayBuffer = (base64: string): Uint8Array => {
41
+ const binaryString: string = decode(base64);
42
+ return Uint8Array.from(binaryString, c => c.charCodeAt(0));
43
+ };
44
+
45
+ export const gzipDecompressToString = async (
46
+ data: Uint8Array
47
+ ): Promise<string> => {
48
+ return new Promise((resolve, reject) => {
49
+ try {
50
+ const result: string = ungzip(data, { to: 'string' });
51
+ resolve(result);
52
+ } catch (error) {
53
+ reject('unable to decompress' + error);
54
+ }
55
+ });
56
+ };