@nlxai/core 1.2.4-alpha.3 → 1.2.4-alpha.5
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.
- package/README.md +67 -19
- package/docs/README.md +8 -0
- package/lib/index.cjs +2 -2
- package/lib/index.d.ts +1 -1
- package/lib/index.esm.js +2 -2
- package/lib/index.umd.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -757,11 +757,13 @@ The URL comming from the Application response `metadata.feedbackURL` field.
|
|
|
757
757
|
|
|
758
758
|
Either a numerical rating or a textual comment.
|
|
759
759
|
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
760
|
+
###### rating?
|
|
761
|
+
|
|
762
|
+
`number`
|
|
763
|
+
|
|
764
|
+
###### comment?
|
|
765
|
+
|
|
766
|
+
`string`
|
|
765
767
|
|
|
766
768
|
###### Returns
|
|
767
769
|
|
|
@@ -934,11 +936,11 @@ Add a listener to one of the handler's custom events
|
|
|
934
936
|
|
|
935
937
|
###### event
|
|
936
938
|
|
|
937
|
-
`
|
|
939
|
+
[`ConversationHandlerEvent`](#conversationhandlerevent)
|
|
938
940
|
|
|
939
941
|
###### handler
|
|
940
942
|
|
|
941
|
-
|
|
943
|
+
[`VoicePlusCommandListener`](#voicepluscommandlistener) | [`InterimMessageListener`](#interimmessagelistener)
|
|
942
944
|
|
|
943
945
|
###### Returns
|
|
944
946
|
|
|
@@ -956,11 +958,11 @@ Remove a listener to one of the handler's custom events
|
|
|
956
958
|
|
|
957
959
|
###### event
|
|
958
960
|
|
|
959
|
-
`
|
|
961
|
+
[`ConversationHandlerEvent`](#conversationhandlerevent)
|
|
960
962
|
|
|
961
963
|
###### handler
|
|
962
964
|
|
|
963
|
-
|
|
965
|
+
[`VoicePlusCommandListener`](#voicepluscommandlistener) | [`InterimMessageListener`](#interimmessagelistener)
|
|
964
966
|
|
|
965
967
|
###### Returns
|
|
966
968
|
|
|
@@ -1542,6 +1544,14 @@ optional negative: string;
|
|
|
1542
1544
|
|
|
1543
1545
|
Label for negative feedback
|
|
1544
1546
|
|
|
1547
|
+
###### comment?
|
|
1548
|
+
|
|
1549
|
+
```ts
|
|
1550
|
+
optional comment: string;
|
|
1551
|
+
```
|
|
1552
|
+
|
|
1553
|
+
Label for comment
|
|
1554
|
+
|
|
1545
1555
|
---
|
|
1546
1556
|
|
|
1547
1557
|
### StructuredRequest
|
|
@@ -1795,23 +1805,21 @@ Dictionary of handler methods per event
|
|
|
1795
1805
|
|
|
1796
1806
|
#### Properties
|
|
1797
1807
|
|
|
1798
|
-
##### voicePlusCommand
|
|
1808
|
+
##### voicePlusCommand
|
|
1799
1809
|
|
|
1800
1810
|
```ts
|
|
1801
|
-
voicePlusCommand:
|
|
1811
|
+
voicePlusCommand: VoicePlusCommandListener;
|
|
1802
1812
|
```
|
|
1803
1813
|
|
|
1804
1814
|
Voice+ command event handler
|
|
1805
1815
|
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
###### payload
|
|
1816
|
+
##### interimMessage
|
|
1809
1817
|
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1818
|
+
```ts
|
|
1819
|
+
interimMessage: InterimMessageListener;
|
|
1820
|
+
```
|
|
1813
1821
|
|
|
1814
|
-
|
|
1822
|
+
Interim message event handler
|
|
1815
1823
|
|
|
1816
1824
|
## Enumerations
|
|
1817
1825
|
|
|
@@ -1850,7 +1858,7 @@ Generic failure (cannot be attributed to the application)
|
|
|
1850
1858
|
### ConversationHandlerEvent
|
|
1851
1859
|
|
|
1852
1860
|
```ts
|
|
1853
|
-
type ConversationHandlerEvent = "voicePlusCommand";
|
|
1861
|
+
type ConversationHandlerEvent = "voicePlusCommand" | "interimMessage";
|
|
1854
1862
|
```
|
|
1855
1863
|
|
|
1856
1864
|
Handler events
|
|
@@ -2085,6 +2093,46 @@ Voice+ context, type to be defined
|
|
|
2085
2093
|
|
|
2086
2094
|
---
|
|
2087
2095
|
|
|
2096
|
+
### VoicePlusCommandListener()
|
|
2097
|
+
|
|
2098
|
+
```ts
|
|
2099
|
+
type VoicePlusCommandListener = (payload) => void;
|
|
2100
|
+
```
|
|
2101
|
+
|
|
2102
|
+
Voice+ command listener
|
|
2103
|
+
|
|
2104
|
+
#### Parameters
|
|
2105
|
+
|
|
2106
|
+
##### payload
|
|
2107
|
+
|
|
2108
|
+
`any`
|
|
2109
|
+
|
|
2110
|
+
#### Returns
|
|
2111
|
+
|
|
2112
|
+
`void`
|
|
2113
|
+
|
|
2114
|
+
---
|
|
2115
|
+
|
|
2116
|
+
### InterimMessageListener()
|
|
2117
|
+
|
|
2118
|
+
```ts
|
|
2119
|
+
type InterimMessageListener = (message?) => void;
|
|
2120
|
+
```
|
|
2121
|
+
|
|
2122
|
+
Interim message listener
|
|
2123
|
+
|
|
2124
|
+
#### Parameters
|
|
2125
|
+
|
|
2126
|
+
##### message?
|
|
2127
|
+
|
|
2128
|
+
`string`
|
|
2129
|
+
|
|
2130
|
+
#### Returns
|
|
2131
|
+
|
|
2132
|
+
`void`
|
|
2133
|
+
|
|
2134
|
+
---
|
|
2135
|
+
|
|
2088
2136
|
### Subscriber()
|
|
2089
2137
|
|
|
2090
2138
|
```ts
|
package/docs/README.md
CHANGED
package/lib/index.cjs
CHANGED
|
@@ -5,7 +5,7 @@ var ramda = require('ramda');
|
|
|
5
5
|
var ReconnectingWebSocket = require('reconnecting-websocket');
|
|
6
6
|
var uuid = require('uuid');
|
|
7
7
|
|
|
8
|
-
var version$1 = "1.2.4-alpha.
|
|
8
|
+
var version$1 = "1.2.4-alpha.5";
|
|
9
9
|
var packageJson = {
|
|
10
10
|
version: version$1};
|
|
11
11
|
|
|
@@ -335,7 +335,7 @@ function createConversation(configuration) {
|
|
|
335
335
|
const json = await fetchUserMessage({
|
|
336
336
|
fullApplicationUrl: fullApplicationHttpUrl(),
|
|
337
337
|
headers: configuration.headers ?? {},
|
|
338
|
-
stream: configuration.experimental?.streamHttp ??
|
|
338
|
+
stream: configuration.experimental?.streamHttp ?? true,
|
|
339
339
|
eventListeners,
|
|
340
340
|
body: bodyWithContext,
|
|
341
341
|
});
|
package/lib/index.d.ts
CHANGED
package/lib/index.esm.js
CHANGED
|
@@ -3,7 +3,7 @@ import { equals, adjust } from 'ramda';
|
|
|
3
3
|
import ReconnectingWebSocket from 'reconnecting-websocket';
|
|
4
4
|
import { v4 } from 'uuid';
|
|
5
5
|
|
|
6
|
-
var version$1 = "1.2.4-alpha.
|
|
6
|
+
var version$1 = "1.2.4-alpha.5";
|
|
7
7
|
var packageJson = {
|
|
8
8
|
version: version$1};
|
|
9
9
|
|
|
@@ -333,7 +333,7 @@ function createConversation(configuration) {
|
|
|
333
333
|
const json = await fetchUserMessage({
|
|
334
334
|
fullApplicationUrl: fullApplicationHttpUrl(),
|
|
335
335
|
headers: configuration.headers ?? {},
|
|
336
|
-
stream: configuration.experimental?.streamHttp ??
|
|
336
|
+
stream: configuration.experimental?.streamHttp ?? true,
|
|
337
337
|
eventListeners,
|
|
338
338
|
body: bodyWithContext,
|
|
339
339
|
});
|
package/lib/index.umd.js
CHANGED
|
@@ -12,4 +12,4 @@
|
|
|
12
12
|
|
|
13
13
|
See the Apache Version 2.0 License for specific language governing permissions
|
|
14
14
|
and limitations under the License.
|
|
15
|
-
***************************************************************************** */function z(e,t){function n(){this.constructor=e}J(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function V(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)i.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(o)throw o.error}}return i}var Q=function(e,t){this.target=t,this.type=e},X=function(e){function t(t,n){var r=e.call(this,"error",n)||this;return r.message=t.message,r.error=t,r}return z(t,e),t}(Q),Z=function(e){function t(t,n,r){void 0===t&&(t=1e3),void 0===n&&(n="");var o=e.call(this,"close",r)||this;return o.wasClean=!0,o.code=t,o.reason=n,o}return z(t,e),t}(Q),Y=function(){if("undefined"!=typeof WebSocket)return WebSocket},ee={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0},te=function(){function e(e,t,n){var r=this;void 0===n&&(n={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(e){r._debug("open event");var t=r._options.minUptime,n=void 0===t?ee.minUptime:t;clearTimeout(r._connectTimeout),r._uptimeTimeout=setTimeout((function(){return r._acceptOpen()}),n),r._ws.binaryType=r._binaryType,r._messageQueue.forEach((function(e){return r._ws.send(e)})),r._messageQueue=[],r.onopen&&r.onopen(e),r._listeners.open.forEach((function(t){return r._callEventListener(e,t)}))},this._handleMessage=function(e){r._debug("message event"),r.onmessage&&r.onmessage(e),r._listeners.message.forEach((function(t){return r._callEventListener(e,t)}))},this._handleError=function(e){r._debug("error event",e.message),r._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),r.onerror&&r.onerror(e),r._debug("exec error listeners"),r._listeners.error.forEach((function(t){return r._callEventListener(e,t)})),r._connect()},this._handleClose=function(e){r._debug("close event"),r._clearTimeouts(),r._shouldReconnect&&r._connect(),r.onclose&&r.onclose(e),r._listeners.close.forEach((function(t){return r._callEventListener(e,t)}))},this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(e,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CONNECTING",{get:function(){return e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"OPEN",{get:function(){return e.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSING",{get:function(){return e.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSED",{get:function(){return e.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bufferedAmount",{get:function(){return this._messageQueue.reduce((function(e,t){return"string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e}),0)+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),e.prototype.close=function(e,t){void 0===e&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")},e.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()},e.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,n=void 0===t?ee.maxEnqueuedMessages:t;this._messageQueue.length<n&&(this._debug("enqueue",e),this._messageQueue.push(e))}},e.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},e.prototype.dispatchEvent=function(e){var t,n,r=this._listeners[e.type];if(r)try{for(var o=function(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}(r),s=o.next();!s.done;s=o.next()){var i=s.value;this._callEventListener(e,i)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((function(e){return e!==t})))},e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(V(arguments[t]));return e}(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?ee.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,o=void 0===r?ee.minReconnectionDelay:r,s=e.maxReconnectionDelay,i=void 0===s?ee.maxReconnectionDelay:s,a=0;return this._retryCount>0&&(a=o*Math.pow(n,this._retryCount-1))>i&&(a=i),this._debug("next delay",a),a},e.prototype._wait=function(){var e=this;return new Promise((function(t){setTimeout(t,e._getNextDelay())}))},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,n=t.maxRetries,r=void 0===n?ee.maxRetries:n,o=t.connectionTimeout,s=void 0===o?ee.connectionTimeout:o,i=t.WebSocket,a=void 0===i?Y():i;if(this._retryCount>=r)this._debug("max retries reached",this._retryCount,">=",r);else{if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),void 0===(c=a)||!c||2!==c.CLOSING)throw Error("No valid WebSocket class provided");var c;this._wait().then((function(){return e._getNextUrl(e._url)})).then((function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new a(t,e._protocols):new a(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout((function(){return e._handleTimeout()}),s))}))}}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new X(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new Z(e,t,this))}catch(e){}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();let ne;const re=new Uint8Array(16);function oe(){if(!ne&&(ne="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ne))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ne(re)}const se=[];for(let e=0;e<256;++e)se.push((e+256).toString(16).slice(1));var ie={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ae(e,t,n){if(ie.randomUUID&&!e)return ie.randomUUID();const r=(e=e||{}).random||(e.rng||oe)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return se[e[t+0]]+se[e[t+1]]+se[e[t+2]]+se[e[t+3]]+"-"+se[e[t+4]]+se[e[t+5]]+"-"+se[e[t+6]]+se[e[t+7]]+"-"+se[e[t+8]]+se[e[t+9]]+"-"+se[e[t+10]]+se[e[t+11]]+se[e[t+12]]+se[e[t+13]]+se[e[t+14]]+se[e[t+15]]}(r)}var ce="1.2.4-alpha.3";const ue=ce,le=console;var de;e.ResponseType=void 0,(de=e.ResponseType||(e.ResponseType={})).Application="bot",de.User="user",de.Failure="failure";const fe="NLX.Welcome",pe=e=>Array.isArray(e)?e:Object.entries(e).map((([e,t])=>({slotId:e,value:t}))),he=e=>({...e,intentId:e.flowId??e.intentId,slots:null!=e.slots?pe(e.slots):e.slots}),ye=e=>e.responses,me=e=>{try{return JSON.parse(e)}catch(e){return null}},ge=e=>e.match(/(bots\.dev\.studio\.nlx\.ai|bots\.studio\.nlx\.ai|apps\.nlx\.ai|dev\.apps\.nlx\.ai)/g)?.[0]??"apps.nlx.ai",be=e=>{if(!ve(e))return e;const t=ge(e),n=new URL(e),r=new URLSearchParams(n.search),o=r.get("channelKey");return`https://${t}/c/${r.get("deploymentKey")}/${o}`},ve=e=>0===e.indexOf("wss://"),_e=async({fullApplicationUrl:e,headers:t,body:n,stream:r,eventListeners:o})=>{if(r)return await(async n=>{const r=await C(e,{method:"POST",headers:{...t,"Content-Type":"application/json","nlx-sdk-version":ce},body:JSON.stringify({...n,stream:!0})});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);const s=r.body.getReader(),i=new TextDecoder;let a="";const c=[];let u={};for(;;){const{done:e,value:t}=await s.read();if(e)break;for(a+=i.decode(t,{stream:!0});;){const e=a.indexOf("{");if(-1===e)break;let t=!1;for(let n=0;n<a.length;n++)if("}"===a[n]){const r=a.substring(e,n+1);try{const e=JSON.parse(r);if("interim"===e.type){const t=e.text;"string"==typeof t&&o.interimMessage.forEach((e=>{e(t)}))}else"message"===e.type?c.push({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}):"final_response"===e.type&&(u=e.data);a=a.substring(n+1),t=!0;break}catch(e){}}if(!t)break}}return o.interimMessage.forEach((e=>{e(void 0)})),{...u,messages:c}})(n);{const r=await C(e,{method:"POST",headers:{...t??{},Accept:"application/json","Content-Type":"application/json","nlx-sdk-version":ce},body:JSON.stringify(n)});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);return await r.json()}};e.createConversation=function(t){let n,r,o=[],s=null,i=[],a=null;const c=t.applicationUrl??"";/[-|_][a-z]{2,}[-|_][A-Z]{2,}$/.test(c)&&le.warn("Since v1.0.0, the language code is no longer added at the end of the application URL. Please remove the modifier (e.g. '-en-US') from the URL, and specify it in the `languageCode` parameter instead.");const u={voicePlusCommand:[],interimMessage:[]},l=t.conversationId??ae();let d={responses:t.responses??[],languageCode:t.languageCode,userId:t.userId,conversationId:l};const f=()=>`${be(c)}${!0===t.experimental?.completeApplicationUrl?"":`-${d.languageCode}`}`,p=(e,t)=>{d={...d,...e},v.forEach((e=>{e(ye(d),t)}))},h=()=>{const n={type:e.ResponseType.Failure,receivedAt:(new Date).getTime(),payload:{text:t.failureMessage??"We encountered an issue. Please try again soon."}};p({responses:[...d.responses,n]},n)},y=t=>{if(t?.messages.length>0){const n={type:e.ResponseType.Application,receivedAt:(new Date).getTime(),payload:{...t,messages:t.messages.map((e=>({nodeId:e.nodeId,messageId:e.messageId,text:e.text,choices:e.choices??[]})))}};p({responses:[...d.responses,n]},n),t.metadata.hasPendingDataRequest&&(x({poll:!0}),setTimeout((()=>{b({request:{structured:{poll:!0}}})}),1500))}else le.warn("Invalid message structure, expected object with field 'messages'."),h()};let m;const g=e=>{1===r?.readyState?r.send(JSON.stringify(e)):i=[...i,e]},b=async r=>{if(null!=m)return void m(r,(t=>{le.warn("Using the second argument in `setRequestOverride` is deprecated. Use `conversationHandler.appendMessageToTranscript` instead.");const n={type:e.ResponseType.Application,receivedAt:(new Date).getTime(),payload:t};p({responses:[...d.responses,n]},n)}));const s={userId:d.userId,conversationId:d.conversationId,...r,languageCode:d.languageCode,channelType:t.experimental?.channelType,environment:t.environment};if(ve(c))1===n?.readyState?n.send(JSON.stringify(s)):o=[...o,s];else try{const e=await _e({fullApplicationUrl:f(),headers:t.headers??{},stream:t.experimental?.streamHttp??!1,eventListeners:u,body:s});y(e)}catch(e){le.warn(e),h()}};let v=[];const _=()=>{1===r?.readyState&&null!=i[0]&&(g(i[0]),i=i.slice(1))},w=()=>{E();const e=new URL(c);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",d.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${d.languageCode}`)),e.searchParams.set("conversationId",d.conversationId),n=new te(e.href),s=setInterval((()=>{(async()=>{1===n?.readyState&&null!=o[0]&&(await b(o[0]),o=o.slice(1))})()}),500),n.onmessage=function(e){"string"==typeof e?.data&&y(me(e.data))},e.searchParams.set("voice-plus","true"),r=new te(e.href),a=setInterval((()=>{_()}),500),r.onmessage=e=>{if("string"==typeof e?.data){const t=me(e.data);null!=t&&u.voicePlusCommand.forEach((e=>{e(t)}))}}},T=()=>{if(O(),!0!==t.bidirectional)return;const e=new URL((e=>{if(ve(e))return e;const t=ge(e),n=new URL(e).pathname.split("/");return`wss://us-east-1-ws.${t}?deploymentKey=${n[2]}&channelKey=${n[3]}`})(c));!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",d.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${d.languageCode}`)),e.searchParams.set("conversationId",d.conversationId),e.searchParams.set("type","voice-plus");const n=t.headers["nlx-api-key"];ve(c)||null==n||e.searchParams.set("apiKey",n),r=new te(e.href),a=setInterval((()=>{_()}),500),r.onmessage=e=>{if("string"==typeof e?.data){const t=me(e.data);null!=t&&u.voicePlusCommand.forEach((e=>{e(t)}))}}},E=()=>{null!=s&&clearInterval(s),null!=n&&(n.onmessage=null,n.close(),n=void 0)},O=()=>{null!=a&&clearInterval(a),null!=r&&(r.onmessage=null,r.close(),r=void 0)};ve(c)&&w(),T();const x=(t,n)=>{const r={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"structured",...he(t),context:n}};p({responses:[...d.responses,r]},r)},A=(e,t)=>{x({intentId:e},t),b({context:t,request:{structured:{intentId:e}}})},I=e=>{v=v.filter((t=>t!==e))};return{sendText:(t,n)=>{const r={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"text",text:t,context:n}};p({responses:[...d.responses,r]},r),b({context:n,request:{unstructured:{text:t}}})},sendContext:async e=>{const n=await C(`${f()}/context`,{method:"POST",headers:{...t.headers??{},Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":d.conversationId,"nlx-sdk-version":ce},body:JSON.stringify({languageCode:d.languageCode,conversationId:d.conversationId,userId:d.userId,context:e})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},appendMessageToTranscript:e=>{const t={...e,receivedAt:e.receivedAt??(new Date).getTime()};p({responses:[...d.responses,t]},t)},sendStructured:(e,t)=>{x(e,t),b({context:t,request:{structured:he(e)}})},sendSlots:(e,t)=>{x({slots:e},t),b({context:t,request:{structured:{slots:pe(e)}}})},sendFlow:A,sendIntent:(e,t)=>{le.warn("Calling `sendIntent` is deprecated and will be removed in a future version of the SDK. Use `sendFlow` instead."),A(e,t)},sendWelcomeFlow:e=>{A(fe,e)},sendWelcomeIntent:e=>{le.warn("Calling `sendWelcomeIntent` is deprecated and will be removed in a future version of the SDK. Use `sendWelcomeFlow` instead."),A(fe,e)},sendChoice:(t,n,r)=>{let o=[...d.responses];const s={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"choice",choiceId:t}},i=r?.responseIndex??-1,a=r?.messageIndex??-1;i>-1&&a>-1&&(o=R(i,(n=>n.type===e.ResponseType.Application?{...n,payload:{...n.payload,messages:R(a,(e=>({...e,selectedChoiceId:t})),n.payload.messages)}}:n),o)),o=[...o,s],p({responses:o},s),b({context:n,request:{structured:{nodeId:r?.nodeId,intentId:r?.intentId,choiceId:t}}})},submitFeedback:async(e,t)=>{const n=await C(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({languageCode:d.languageCode,conversationId:d.conversationId,userId:d.userId,...t})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},currentConversationId:()=>d.conversationId,setLanguageCode:e=>{e!==d.languageCode?(ve(c)&&w(),T(),p({languageCode:e})):le.warn("Attempted to set language code to the one already active.")},currentLanguageCode:()=>d.languageCode,getVoiceCredentials:async(e,n)=>{const r=be(c),o=await C(`${r}-${d.languageCode}/requestToken`,{method:"POST",headers:{...t.headers??{},Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":d.conversationId,"nlx-sdk-version":ce},body:JSON.stringify({languageCode:d.languageCode,conversationId:d.conversationId,userId:d.userId,requestToken:!0,context:e,autoTriggerWelcomeFlow:n?.autoTriggerWelcomeFlow??!0})});if(o.status>=400)throw new Error(`Responded with ${o.status}`);const s=await o.json();if(null==s?.url)throw new Error("Invalid response");return s},subscribe:e=>(v=[...v,e],e(ye(d)),()=>{I(e)}),unsubscribe:I,unsubscribeAll:()=>{v=[]},reset:e=>{p({conversationId:ae(),responses:!0===e?.clearResponses?[]:d.responses}),ve(c)&&w(),T()},destroy:()=>{v=[],ve(c)&&E(),O()},setRequestOverride:e=>{m=e},addEventListener:(e,t)=>{u[e]=[...u[e],t]},removeEventListener:(e,t)=>{u[e]=u[e].filter((e=>e!==t))},sendVoicePlusContext:e=>{g({context:e})}}},e.getCurrentExpirationTimestamp=t=>{let n=null;return t.forEach((t=>{t.type===e.ResponseType.Application&&null!=t.payload.expirationTimestamp&&(n=t.payload.expirationTimestamp)})),n},e.isConfigValid=e=>(e.applicationUrl??"").length>0,e.promisify=function(t,n,r=1e4){return async o=>await new Promise(((s,i)=>{const a=setTimeout((()=>{i(new Error("The request timed out.")),n.unsubscribe(c)}),r),c=(t,r)=>{r?.type!==e.ResponseType.Application&&r?.type!==e.ResponseType.Failure||(clearTimeout(a),n.unsubscribe(c),s(r))};n.subscribe(c),t(o)}))},e.shouldReinitialize=(e,t)=>!K(e,t),e.version=ue}));
|
|
15
|
+
***************************************************************************** */function z(e,t){function n(){this.constructor=e}J(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function V(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)i.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(o)throw o.error}}return i}var Q=function(e,t){this.target=t,this.type=e},X=function(e){function t(t,n){var r=e.call(this,"error",n)||this;return r.message=t.message,r.error=t,r}return z(t,e),t}(Q),Z=function(e){function t(t,n,r){void 0===t&&(t=1e3),void 0===n&&(n="");var o=e.call(this,"close",r)||this;return o.wasClean=!0,o.code=t,o.reason=n,o}return z(t,e),t}(Q),Y=function(){if("undefined"!=typeof WebSocket)return WebSocket},ee={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0},te=function(){function e(e,t,n){var r=this;void 0===n&&(n={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(e){r._debug("open event");var t=r._options.minUptime,n=void 0===t?ee.minUptime:t;clearTimeout(r._connectTimeout),r._uptimeTimeout=setTimeout((function(){return r._acceptOpen()}),n),r._ws.binaryType=r._binaryType,r._messageQueue.forEach((function(e){return r._ws.send(e)})),r._messageQueue=[],r.onopen&&r.onopen(e),r._listeners.open.forEach((function(t){return r._callEventListener(e,t)}))},this._handleMessage=function(e){r._debug("message event"),r.onmessage&&r.onmessage(e),r._listeners.message.forEach((function(t){return r._callEventListener(e,t)}))},this._handleError=function(e){r._debug("error event",e.message),r._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),r.onerror&&r.onerror(e),r._debug("exec error listeners"),r._listeners.error.forEach((function(t){return r._callEventListener(e,t)})),r._connect()},this._handleClose=function(e){r._debug("close event"),r._clearTimeouts(),r._shouldReconnect&&r._connect(),r.onclose&&r.onclose(e),r._listeners.close.forEach((function(t){return r._callEventListener(e,t)}))},this._url=e,this._protocols=t,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(e,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(e,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(e,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CONNECTING",{get:function(){return e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"OPEN",{get:function(){return e.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSING",{get:function(){return e.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"CLOSED",{get:function(){return e.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"bufferedAmount",{get:function(){return this._messageQueue.reduce((function(e,t){return"string"==typeof t?e+=t.length:t instanceof Blob?e+=t.size:e+=t.byteLength,e}),0)+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?e.CLOSED:e.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),e.prototype.close=function(e,t){void 0===e&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),this._ws?this._ws.readyState!==this.CLOSED?this._ws.close(e,t):this._debug("close: already closed"):this._debug("close enqueued: no ws instance")},e.prototype.reconnect=function(e,t){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,this._ws&&this._ws.readyState!==this.CLOSED?(this._disconnect(e,t),this._connect()):this._connect()},e.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var t=this._options.maxEnqueuedMessages,n=void 0===t?ee.maxEnqueuedMessages:t;this._messageQueue.length<n&&(this._debug("enqueue",e),this._messageQueue.push(e))}},e.prototype.addEventListener=function(e,t){this._listeners[e]&&this._listeners[e].push(t)},e.prototype.dispatchEvent=function(e){var t,n,r=this._listeners[e.type];if(r)try{for(var o=function(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}}(r),s=o.next();!s.done;s=o.next()){var i=s.value;this._callEventListener(e,i)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return!0},e.prototype.removeEventListener=function(e,t){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter((function(e){return e!==t})))},e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._options.debug&&console.log.apply(console,function(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(V(arguments[t]));return e}(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?ee.reconnectionDelayGrowFactor:t,r=e.minReconnectionDelay,o=void 0===r?ee.minReconnectionDelay:r,s=e.maxReconnectionDelay,i=void 0===s?ee.maxReconnectionDelay:s,a=0;return this._retryCount>0&&(a=o*Math.pow(n,this._retryCount-1))>i&&(a=i),this._debug("next delay",a),a},e.prototype._wait=function(){var e=this;return new Promise((function(t){setTimeout(t,e._getNextDelay())}))},e.prototype._getNextUrl=function(e){if("string"==typeof e)return Promise.resolve(e);if("function"==typeof e){var t=e();if("string"==typeof t)return Promise.resolve(t);if(t.then)return t}throw Error("Invalid URL")},e.prototype._connect=function(){var e=this;if(!this._connectLock&&this._shouldReconnect){this._connectLock=!0;var t=this._options,n=t.maxRetries,r=void 0===n?ee.maxRetries:n,o=t.connectionTimeout,s=void 0===o?ee.connectionTimeout:o,i=t.WebSocket,a=void 0===i?Y():i;if(this._retryCount>=r)this._debug("max retries reached",this._retryCount,">=",r);else{if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),void 0===(c=a)||!c||2!==c.CLOSING)throw Error("No valid WebSocket class provided");var c;this._wait().then((function(){return e._getNextUrl(e._url)})).then((function(t){e._closeCalled||(e._debug("connect",{url:t,protocols:e._protocols}),e._ws=e._protocols?new a(t,e._protocols):new a(t),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout((function(){return e._handleTimeout()}),s))}))}}},e.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new X(Error("TIMEOUT"),this))},e.prototype._disconnect=function(e,t){if(void 0===e&&(e=1e3),this._clearTimeouts(),this._ws){this._removeListeners();try{this._ws.close(e,t),this._handleClose(new Z(e,t,this))}catch(e){}}},e.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},e.prototype._callEventListener=function(e,t){"handleEvent"in t?t.handleEvent(e):t(e)},e.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},e.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},e.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},e}();let ne;const re=new Uint8Array(16);function oe(){if(!ne&&(ne="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ne))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ne(re)}const se=[];for(let e=0;e<256;++e)se.push((e+256).toString(16).slice(1));var ie={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ae(e,t,n){if(ie.randomUUID&&!e)return ie.randomUUID();const r=(e=e||{}).random||(e.rng||oe)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return se[e[t+0]]+se[e[t+1]]+se[e[t+2]]+se[e[t+3]]+"-"+se[e[t+4]]+se[e[t+5]]+"-"+se[e[t+6]]+se[e[t+7]]+"-"+se[e[t+8]]+se[e[t+9]]+"-"+se[e[t+10]]+se[e[t+11]]+se[e[t+12]]+se[e[t+13]]+se[e[t+14]]+se[e[t+15]]}(r)}var ce="1.2.4-alpha.5";const ue=ce,le=console;var de;e.ResponseType=void 0,(de=e.ResponseType||(e.ResponseType={})).Application="bot",de.User="user",de.Failure="failure";const fe="NLX.Welcome",pe=e=>Array.isArray(e)?e:Object.entries(e).map((([e,t])=>({slotId:e,value:t}))),he=e=>({...e,intentId:e.flowId??e.intentId,slots:null!=e.slots?pe(e.slots):e.slots}),ye=e=>e.responses,me=e=>{try{return JSON.parse(e)}catch(e){return null}},ge=e=>e.match(/(bots\.dev\.studio\.nlx\.ai|bots\.studio\.nlx\.ai|apps\.nlx\.ai|dev\.apps\.nlx\.ai)/g)?.[0]??"apps.nlx.ai",be=e=>{if(!ve(e))return e;const t=ge(e),n=new URL(e),r=new URLSearchParams(n.search),o=r.get("channelKey");return`https://${t}/c/${r.get("deploymentKey")}/${o}`},ve=e=>0===e.indexOf("wss://"),_e=async({fullApplicationUrl:e,headers:t,body:n,stream:r,eventListeners:o})=>{if(r)return await(async n=>{const r=await C(e,{method:"POST",headers:{...t,"Content-Type":"application/json","nlx-sdk-version":ce},body:JSON.stringify({...n,stream:!0})});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);const s=r.body.getReader(),i=new TextDecoder;let a="";const c=[];let u={};for(;;){const{done:e,value:t}=await s.read();if(e)break;for(a+=i.decode(t,{stream:!0});;){const e=a.indexOf("{");if(-1===e)break;let t=!1;for(let n=0;n<a.length;n++)if("}"===a[n]){const r=a.substring(e,n+1);try{const e=JSON.parse(r);if("interim"===e.type){const t=e.text;"string"==typeof t&&o.interimMessage.forEach((e=>{e(t)}))}else"message"===e.type?c.push({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}):"final_response"===e.type&&(u=e.data);a=a.substring(n+1),t=!0;break}catch(e){}}if(!t)break}}return o.interimMessage.forEach((e=>{e(void 0)})),{...u,messages:c}})(n);{const r=await C(e,{method:"POST",headers:{...t??{},Accept:"application/json","Content-Type":"application/json","nlx-sdk-version":ce},body:JSON.stringify(n)});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);return await r.json()}};e.createConversation=function(t){let n,r,o=[],s=null,i=[],a=null;const c=t.applicationUrl??"";/[-|_][a-z]{2,}[-|_][A-Z]{2,}$/.test(c)&&le.warn("Since v1.0.0, the language code is no longer added at the end of the application URL. Please remove the modifier (e.g. '-en-US') from the URL, and specify it in the `languageCode` parameter instead.");const u={voicePlusCommand:[],interimMessage:[]},l=t.conversationId??ae();let d={responses:t.responses??[],languageCode:t.languageCode,userId:t.userId,conversationId:l};const f=()=>`${be(c)}${!0===t.experimental?.completeApplicationUrl?"":`-${d.languageCode}`}`,p=(e,t)=>{d={...d,...e},v.forEach((e=>{e(ye(d),t)}))},h=()=>{const n={type:e.ResponseType.Failure,receivedAt:(new Date).getTime(),payload:{text:t.failureMessage??"We encountered an issue. Please try again soon."}};p({responses:[...d.responses,n]},n)},y=t=>{if(t?.messages.length>0){const n={type:e.ResponseType.Application,receivedAt:(new Date).getTime(),payload:{...t,messages:t.messages.map((e=>({nodeId:e.nodeId,messageId:e.messageId,text:e.text,choices:e.choices??[]})))}};p({responses:[...d.responses,n]},n),t.metadata.hasPendingDataRequest&&(x({poll:!0}),setTimeout((()=>{b({request:{structured:{poll:!0}}})}),1500))}else le.warn("Invalid message structure, expected object with field 'messages'."),h()};let m;const g=e=>{1===r?.readyState?r.send(JSON.stringify(e)):i=[...i,e]},b=async r=>{if(null!=m)return void m(r,(t=>{le.warn("Using the second argument in `setRequestOverride` is deprecated. Use `conversationHandler.appendMessageToTranscript` instead.");const n={type:e.ResponseType.Application,receivedAt:(new Date).getTime(),payload:t};p({responses:[...d.responses,n]},n)}));const s={userId:d.userId,conversationId:d.conversationId,...r,languageCode:d.languageCode,channelType:t.experimental?.channelType,environment:t.environment};if(ve(c))1===n?.readyState?n.send(JSON.stringify(s)):o=[...o,s];else try{const e=await _e({fullApplicationUrl:f(),headers:t.headers??{},stream:t.experimental?.streamHttp??!0,eventListeners:u,body:s});y(e)}catch(e){le.warn(e),h()}};let v=[];const _=()=>{1===r?.readyState&&null!=i[0]&&(g(i[0]),i=i.slice(1))},w=()=>{E();const e=new URL(c);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",d.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${d.languageCode}`)),e.searchParams.set("conversationId",d.conversationId),n=new te(e.href),s=setInterval((()=>{(async()=>{1===n?.readyState&&null!=o[0]&&(await b(o[0]),o=o.slice(1))})()}),500),n.onmessage=function(e){"string"==typeof e?.data&&y(me(e.data))},e.searchParams.set("voice-plus","true"),r=new te(e.href),a=setInterval((()=>{_()}),500),r.onmessage=e=>{if("string"==typeof e?.data){const t=me(e.data);null!=t&&u.voicePlusCommand.forEach((e=>{e(t)}))}}},T=()=>{if(O(),!0!==t.bidirectional)return;const e=new URL((e=>{if(ve(e))return e;const t=ge(e),n=new URL(e).pathname.split("/");return`wss://us-east-1-ws.${t}?deploymentKey=${n[2]}&channelKey=${n[3]}`})(c));!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",d.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${d.languageCode}`)),e.searchParams.set("conversationId",d.conversationId),e.searchParams.set("type","voice-plus");const n=t.headers["nlx-api-key"];ve(c)||null==n||e.searchParams.set("apiKey",n),r=new te(e.href),a=setInterval((()=>{_()}),500),r.onmessage=e=>{if("string"==typeof e?.data){const t=me(e.data);null!=t&&u.voicePlusCommand.forEach((e=>{e(t)}))}}},E=()=>{null!=s&&clearInterval(s),null!=n&&(n.onmessage=null,n.close(),n=void 0)},O=()=>{null!=a&&clearInterval(a),null!=r&&(r.onmessage=null,r.close(),r=void 0)};ve(c)&&w(),T();const x=(t,n)=>{const r={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"structured",...he(t),context:n}};p({responses:[...d.responses,r]},r)},A=(e,t)=>{x({intentId:e},t),b({context:t,request:{structured:{intentId:e}}})},I=e=>{v=v.filter((t=>t!==e))};return{sendText:(t,n)=>{const r={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"text",text:t,context:n}};p({responses:[...d.responses,r]},r),b({context:n,request:{unstructured:{text:t}}})},sendContext:async e=>{const n=await C(`${f()}/context`,{method:"POST",headers:{...t.headers??{},Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":d.conversationId,"nlx-sdk-version":ce},body:JSON.stringify({languageCode:d.languageCode,conversationId:d.conversationId,userId:d.userId,context:e})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},appendMessageToTranscript:e=>{const t={...e,receivedAt:e.receivedAt??(new Date).getTime()};p({responses:[...d.responses,t]},t)},sendStructured:(e,t)=>{x(e,t),b({context:t,request:{structured:he(e)}})},sendSlots:(e,t)=>{x({slots:e},t),b({context:t,request:{structured:{slots:pe(e)}}})},sendFlow:A,sendIntent:(e,t)=>{le.warn("Calling `sendIntent` is deprecated and will be removed in a future version of the SDK. Use `sendFlow` instead."),A(e,t)},sendWelcomeFlow:e=>{A(fe,e)},sendWelcomeIntent:e=>{le.warn("Calling `sendWelcomeIntent` is deprecated and will be removed in a future version of the SDK. Use `sendWelcomeFlow` instead."),A(fe,e)},sendChoice:(t,n,r)=>{let o=[...d.responses];const s={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"choice",choiceId:t}},i=r?.responseIndex??-1,a=r?.messageIndex??-1;i>-1&&a>-1&&(o=R(i,(n=>n.type===e.ResponseType.Application?{...n,payload:{...n.payload,messages:R(a,(e=>({...e,selectedChoiceId:t})),n.payload.messages)}}:n),o)),o=[...o,s],p({responses:o},s),b({context:n,request:{structured:{nodeId:r?.nodeId,intentId:r?.intentId,choiceId:t}}})},submitFeedback:async(e,t)=>{const n=await C(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({languageCode:d.languageCode,conversationId:d.conversationId,userId:d.userId,...t})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},currentConversationId:()=>d.conversationId,setLanguageCode:e=>{e!==d.languageCode?(ve(c)&&w(),T(),p({languageCode:e})):le.warn("Attempted to set language code to the one already active.")},currentLanguageCode:()=>d.languageCode,getVoiceCredentials:async(e,n)=>{const r=be(c),o=await C(`${r}-${d.languageCode}/requestToken`,{method:"POST",headers:{...t.headers??{},Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":d.conversationId,"nlx-sdk-version":ce},body:JSON.stringify({languageCode:d.languageCode,conversationId:d.conversationId,userId:d.userId,requestToken:!0,context:e,autoTriggerWelcomeFlow:n?.autoTriggerWelcomeFlow??!0})});if(o.status>=400)throw new Error(`Responded with ${o.status}`);const s=await o.json();if(null==s?.url)throw new Error("Invalid response");return s},subscribe:e=>(v=[...v,e],e(ye(d)),()=>{I(e)}),unsubscribe:I,unsubscribeAll:()=>{v=[]},reset:e=>{p({conversationId:ae(),responses:!0===e?.clearResponses?[]:d.responses}),ve(c)&&w(),T()},destroy:()=>{v=[],ve(c)&&E(),O()},setRequestOverride:e=>{m=e},addEventListener:(e,t)=>{u[e]=[...u[e],t]},removeEventListener:(e,t)=>{u[e]=u[e].filter((e=>e!==t))},sendVoicePlusContext:e=>{g({context:e})}}},e.getCurrentExpirationTimestamp=t=>{let n=null;return t.forEach((t=>{t.type===e.ResponseType.Application&&null!=t.payload.expirationTimestamp&&(n=t.payload.expirationTimestamp)})),n},e.isConfigValid=e=>(e.applicationUrl??"").length>0,e.promisify=function(t,n,r=1e4){return async o=>await new Promise(((s,i)=>{const a=setTimeout((()=>{i(new Error("The request timed out.")),n.unsubscribe(c)}),r),c=(t,r)=>{r?.type!==e.ResponseType.Application&&r?.type!==e.ResponseType.Failure||(clearTimeout(a),n.unsubscribe(c),s(r))};n.subscribe(c),t(o)}))},e.shouldReinitialize=(e,t)=>!K(e,t),e.version=ue}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nlxai/core",
|
|
3
|
-
"version": "1.2.4-alpha.
|
|
3
|
+
"version": "1.2.4-alpha.5",
|
|
4
4
|
"description": "Low-level SDK for building NLX experiences",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.cjs",
|
|
@@ -49,5 +49,5 @@
|
|
|
49
49
|
"publishConfig": {
|
|
50
50
|
"access": "public"
|
|
51
51
|
},
|
|
52
|
-
"gitHead": "
|
|
52
|
+
"gitHead": "41f7924241752b6f335c9a3ee1c3e6531e407ae4"
|
|
53
53
|
}
|