@nlxai/core 1.2.7-alpha.1 → 1.2.7-alpha.2

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/lib/index.cjs CHANGED
@@ -5,7 +5,7 @@ var ReconnectingWebSocket = require('reconnecting-websocket');
5
5
  var uuid = require('uuid');
6
6
 
7
7
  var name = "@nlxai/core";
8
- var version$1 = "1.2.7-alpha.1";
8
+ var version$1 = "1.2.7-alpha.2";
9
9
  var description = "Low-level SDK for building NLX experiences";
10
10
  var type = "module";
11
11
  var main = "lib/index.cjs";
@@ -57,7 +57,7 @@ var dependencies = {
57
57
  var publishConfig = {
58
58
  access: "public"
59
59
  };
60
- var gitHead = "548c2c6c876cf86572aeb63a6810ed87c9b0382a";
60
+ var gitHead = "28deac5208ff64f99a3d038050172c1ac9a78630";
61
61
  var packageJson = {
62
62
  name: name,
63
63
  version: version$1,
@@ -92,6 +92,10 @@ exports.Protocol = void 0;
92
92
  * Supported for development purposes only
93
93
  */
94
94
  Protocol["Http"] = "http";
95
+ /**
96
+ * Supported for development purposes only
97
+ */
98
+ Protocol["HttpWithStreaming"] = "httpWithStreaming";
95
99
  /**
96
100
  * Regular encrypted HTTPS, without support for post-escalation message handling, interim messages and other streaming features.
97
101
  */
@@ -202,7 +206,13 @@ const parseConnection = (config) => {
202
206
  if (parseResult?.pathname.groups.channelKey != null &&
203
207
  parseResult?.pathname.groups.deploymentKey != null) {
204
208
  return {
205
- protocol: urlObject.protocol === "http:" ? exports.Protocol.Http : protocol,
209
+ protocol:
210
+ // Correction for the dev case
211
+ urlObject.protocol === "http:"
212
+ ? config.experimental?.streamHttp === false
213
+ ? exports.Protocol.Http
214
+ : exports.Protocol.HttpWithStreaming
215
+ : protocol,
206
216
  channelKey: parseResult.pathname.groups.channelKey,
207
217
  deploymentKey: parseResult.pathname.groups.deploymentKey,
208
218
  host,
@@ -402,6 +412,9 @@ function createConversation(configuration) {
402
412
  });
403
413
  };
404
414
  const failureHandler = () => {
415
+ eventListeners.interimMessage.forEach((listener) => {
416
+ listener(undefined);
417
+ });
405
418
  const newResponse = {
406
419
  type: exports.ResponseType.Failure,
407
420
  receivedAt: new Date().getTime(),
@@ -500,7 +513,8 @@ function createConversation(configuration) {
500
513
  fullApplicationUrl: fullApplicationHttpUrl(),
501
514
  apiKey: connection?.apiKey ?? "",
502
515
  headers: configuration.headers ?? {},
503
- stream: protocol === exports.Protocol.HttpsWithStreaming,
516
+ stream: protocol === exports.Protocol.HttpsWithStreaming ||
517
+ protocol === exports.Protocol.HttpWithStreaming,
504
518
  eventListeners,
505
519
  body: bodyWithContext,
506
520
  });
package/lib/index.d.ts CHANGED
@@ -269,6 +269,10 @@ export declare enum Protocol {
269
269
  * Supported for development purposes only
270
270
  */
271
271
  Http = "http",
272
+ /**
273
+ * Supported for development purposes only
274
+ */
275
+ HttpWithStreaming = "httpWithStreaming",
272
276
  /**
273
277
  * Regular encrypted HTTPS, without support for post-escalation message handling, interim messages and other streaming features.
274
278
  */
package/lib/index.esm.js CHANGED
@@ -3,7 +3,7 @@ import ReconnectingWebSocket from 'reconnecting-websocket';
3
3
  import { v4 } from 'uuid';
4
4
 
5
5
  var name = "@nlxai/core";
6
- var version$1 = "1.2.7-alpha.1";
6
+ var version$1 = "1.2.7-alpha.2";
7
7
  var description = "Low-level SDK for building NLX experiences";
8
8
  var type = "module";
9
9
  var main = "lib/index.cjs";
@@ -55,7 +55,7 @@ var dependencies = {
55
55
  var publishConfig = {
56
56
  access: "public"
57
57
  };
58
- var gitHead = "548c2c6c876cf86572aeb63a6810ed87c9b0382a";
58
+ var gitHead = "28deac5208ff64f99a3d038050172c1ac9a78630";
59
59
  var packageJson = {
60
60
  name: name,
61
61
  version: version$1,
@@ -90,6 +90,10 @@ var Protocol;
90
90
  * Supported for development purposes only
91
91
  */
92
92
  Protocol["Http"] = "http";
93
+ /**
94
+ * Supported for development purposes only
95
+ */
96
+ Protocol["HttpWithStreaming"] = "httpWithStreaming";
93
97
  /**
94
98
  * Regular encrypted HTTPS, without support for post-escalation message handling, interim messages and other streaming features.
95
99
  */
@@ -200,7 +204,13 @@ const parseConnection = (config) => {
200
204
  if (parseResult?.pathname.groups.channelKey != null &&
201
205
  parseResult?.pathname.groups.deploymentKey != null) {
202
206
  return {
203
- protocol: urlObject.protocol === "http:" ? Protocol.Http : protocol,
207
+ protocol:
208
+ // Correction for the dev case
209
+ urlObject.protocol === "http:"
210
+ ? config.experimental?.streamHttp === false
211
+ ? Protocol.Http
212
+ : Protocol.HttpWithStreaming
213
+ : protocol,
204
214
  channelKey: parseResult.pathname.groups.channelKey,
205
215
  deploymentKey: parseResult.pathname.groups.deploymentKey,
206
216
  host,
@@ -400,6 +410,9 @@ function createConversation(configuration) {
400
410
  });
401
411
  };
402
412
  const failureHandler = () => {
413
+ eventListeners.interimMessage.forEach((listener) => {
414
+ listener(undefined);
415
+ });
403
416
  const newResponse = {
404
417
  type: ResponseType.Failure,
405
418
  receivedAt: new Date().getTime(),
@@ -498,7 +511,8 @@ function createConversation(configuration) {
498
511
  fullApplicationUrl: fullApplicationHttpUrl(),
499
512
  apiKey: connection?.apiKey ?? "",
500
513
  headers: configuration.headers ?? {},
501
- stream: protocol === Protocol.HttpsWithStreaming,
514
+ stream: protocol === Protocol.HttpsWithStreaming ||
515
+ protocol === Protocol.HttpWithStreaming,
502
516
  eventListeners,
503
517
  body: bodyWithContext,
504
518
  });
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 x(e,t){function n(){this.constructor=e}w(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function T(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var o,r,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(o=s.next()).done;)i.push(o.value)}catch(e){r={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}var I=function(e,t){this.target=t,this.type=e},C=function(e){function t(t,n){var o=e.call(this,"error",n)||this;return o.message=t.message,o.error=t,o}return x(t,e),t}(I),O=function(e){function t(t,n,o){void 0===t&&(t=1e3),void 0===n&&(n="");var r=e.call(this,"close",o)||this;return r.wasClean=!0,r.code=t,r.reason=n,r}return x(t,e),t}(I),E=function(){if("undefined"!=typeof WebSocket)return WebSocket},P={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0},S=function(){function e(e,t,n){var o=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){o._debug("open event");var t=o._options.minUptime,n=void 0===t?P.minUptime:t;clearTimeout(o._connectTimeout),o._uptimeTimeout=setTimeout(function(){return o._acceptOpen()},n),o._ws.binaryType=o._binaryType,o._messageQueue.forEach(function(e){return o._ws.send(e)}),o._messageQueue=[],o.onopen&&o.onopen(e),o._listeners.open.forEach(function(t){return o._callEventListener(e,t)})},this._handleMessage=function(e){o._debug("message event"),o.onmessage&&o.onmessage(e),o._listeners.message.forEach(function(t){return o._callEventListener(e,t)})},this._handleError=function(e){o._debug("error event",e.message),o._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),o.onerror&&o.onerror(e),o._debug("exec error listeners"),o._listeners.error.forEach(function(t){return o._callEventListener(e,t)}),o._connect()},this._handleClose=function(e){o._debug("close event"),o._clearTimeouts(),o._shouldReconnect&&o._connect(),o.onclose&&o.onclose(e),o._listeners.close.forEach(function(t){return o._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?P.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,o=this._listeners[e.type];if(o)try{for(var r=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}}}}(o),s=r.next();!s.done;s=r.next()){var i=s.value;this._callEventListener(e,i)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}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(T(arguments[t]));return e}(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?P.reconnectionDelayGrowFactor:t,o=e.minReconnectionDelay,r=void 0===o?P.minReconnectionDelay:o,s=e.maxReconnectionDelay,i=void 0===s?P.maxReconnectionDelay:s,a=0;return this._retryCount>0&&(a=r*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,o=void 0===n?P.maxRetries:n,r=t.connectionTimeout,s=void 0===r?P.connectionTimeout:r,i=t.WebSocket,a=void 0===i?E():i;if(this._retryCount>=o)this._debug("max retries reached",this._retryCount,">=",o);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 C(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 O(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}();const L=[];for(let e=0;e<256;++e)L.push((e+256).toString(16).slice(1));const A=new Uint8Array(16);function R(e,t,n){return crypto.randomUUID?crypto.randomUUID():function(e){e=e||{};const t=e.random??e.rng?.()??crypto.getRandomValues(A);if(t.length<16)throw new Error("Random bytes length must be >= 16");return t[6]=15&t[6]|64,t[8]=63&t[8]|128,function(e,t=0){return(L[e[t+0]]+L[e[t+1]]+L[e[t+2]]+L[e[t+3]]+"-"+L[e[t+4]]+L[e[t+5]]+"-"+L[e[t+6]]+L[e[t+7]]+"-"+L[e[t+8]]+L[e[t+9]]+"-"+L[e[t+10]]+L[e[t+11]]+L[e[t+12]]+L[e[t+13]]+L[e[t+14]]+L[e[t+15]]).toLowerCase()}(t)}(e)}var U="1.2.7-alpha.1";const k=U,j=console;var K,N;e.Protocol=void 0,(K=e.Protocol||(e.Protocol={})).Http="http",K.Https="https",K.HttpsWithStreaming="httpsWithStreaming",K.Websocket="websocket",e.ResponseType=void 0,(N=e.ResponseType||(e.ResponseType={})).Application="bot",N.User="user",N.Failure="failure";const D="NLX.Welcome",q=e=>Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({slotId:e,value:t})),$=e=>({...e,intentId:e.flowId??e.intentId,slots:null!=e.slots?q(e.slots):e.slots}),W=e=>e.responses,M=e=>{try{return JSON.parse(e)}catch(e){return null}},F=t=>{const n=t.applicationUrl??"",o=t.apiKey??t.headers?.["nlx-api-key"]??"",r=t.protocol??(H(n)?e.Protocol.Websocket:!1===t.experimental?.streamHttp?e.Protocol.Https:e.Protocol.HttpsWithStreaming);if(null!=t.host&&null!=t.channelKey&&null!=t.deploymentKey)return{protocol:r,apiKey:o,host:t.host,channelKey:t.channelKey,deploymentKey:t.deploymentKey};if(H(n)){const e=(e=>e.match(/(bots\.dev\.studio\.nlx\.ai|bots\.studio\.nlx\.ai|apps\.nlx\.ai|dev\.apps\.nlx\.ai)/g)?.[0]??"apps.nlx.ai")(n),t=new URL(n),s=new URLSearchParams(t.search),i=s.get("channelKey"),a=s.get("deploymentKey");return null!=i&&null!=a?{protocol:r,channelKey:i,deploymentKey:a,host:e,apiKey:o}:null}const s=new URL(n),i=s.host,a=new URLPattern({pathname:"/c/:deploymentKey/:channelKey"}).exec(n);return null!=a?.pathname.groups.channelKey&&null!=a?.pathname.groups.deploymentKey?{protocol:"http:"===s.protocol?e.Protocol.Http:r,channelKey:a.pathname.groups.channelKey,deploymentKey:a.pathname.groups.deploymentKey,host:i,apiKey:o}:null},H=e=>0===e.indexOf("wss://"),G=async({fullApplicationUrl:e,apiKey:t,headers:n,body:o,stream:r,eventListeners:s})=>{if(r)return await(async o=>{s.interimMessage.forEach(e=>{e("Thinking...")});const r=await fetch(e,{method:"POST",headers:{...n,"nlx-api-key":t,"Content-Type":"application/json","nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({...o,stream:!0})});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);const i=r.body.getReader(),a=new TextDecoder;let c="";const l=[];let u={};for(;;){const{done:e,value:t}=await i.read();if(e)break;for(c+=a.decode(t,{stream:!0});;){const e=c.indexOf("{");if(-1===e)break;let t=!1;for(let n=0;n<c.length;n++)if("}"===c[n]){const o=c.substring(e,n+1);try{const e=JSON.parse(o);if("interim"===e.type){const t=e.text;"string"==typeof t&&s.interimMessage.forEach(e=>{e(t)})}else"message"===e.type?l.push({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}):"final_response"===e.type&&(u=e.data);c=c.substring(n+1),t=!0;break}catch(e){}}if(!t)break}}return s.interimMessage.forEach(e=>{e(void 0)}),{...u,messages:[...l,...(u.messages??[]).map(e=>({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}))]}})(o);{const r=await fetch(e,{method:"POST",headers:{...n??{},"nlx-api-key":t,Accept:"application/json","Content-Type":"application/json","nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify(o)});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);return await r.json()}};const J=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;e.createConversation=function(t){let n,o,r=[],i=null,a=[],c=null;const l=F(t),u=!0===t.experimental?.completeApplicationUrl,p=u&&H(t.applicationUrl??"")?t.applicationUrl??"":null!=l?(e=>`wss://us-east-1-ws.${e.host}?deploymentKey=${e.deploymentKey}&channelKey=${e.channelKey}&apiKey=${e.apiKey}`)(l):t.applicationUrl??"",d=u&&!H(t.applicationUrl??"")?t.applicationUrl??"":null!=l?(t=>`${t.protocol===e.Protocol.Http?"http":"https"}://${t.host}/c/${t.deploymentKey}/${t.channelKey}`)(l):t.applicationUrl??"";/[-|_][a-z]{2,}[-|_][A-Z]{2,}$/.test(d)&&j.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 h=null!=l?l.protocol:H(t.applicationUrl??"")?e.Protocol.Websocket:!1===t.experimental?.streamHttp?e.Protocol.Https:e.Protocol.HttpsWithStreaming,f={voicePlusCommand:[],interimMessage:[]},y=t.conversationId??R();let g={responses:t.responses??[],languageCode:t.languageCode,userId:t.userId,conversationId:y};const m=()=>`${d}${u?"":`-${g.languageCode}`}`,v=(e,t)=>{g={...g,...e},I.forEach(e=>{e(W(g),t)})},_=()=>{const n={type:e.ResponseType.Failure,receivedAt:(new Date).getTime(),payload:{text:t.failureMessage??"We encountered an issue. Please try again soon."}};v({responses:[...g.responses,n]},n)},b=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??[]}))}};v({responses:[...g.responses,n]},n),t.metadata.hasPendingDataRequest&&(L({poll:!0}),setTimeout(()=>{T({request:{structured:{poll:!0}}})},1500))}else j.warn("Invalid message structure, expected object with field 'messages'."),_()};let w;const x=e=>{1===o?.readyState?o.send(JSON.stringify(e)):a=[...a,e]},T=async o=>{if(null!=w)return void w(o,t=>{j.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};v({responses:[...g.responses,n]},n)});const s={userId:g.userId,conversationId:g.conversationId,...o,languageCode:g.languageCode,channelType:t.experimental?.channelType,environment:t.environment};if(h===e.Protocol.Websocket)1===n?.readyState?n.send(JSON.stringify(s)):r=[...r,s];else try{const n=await G({fullApplicationUrl:m(),apiKey:l?.apiKey??"",headers:t.headers??{},stream:h===e.Protocol.HttpsWithStreaming,eventListeners:f,body:s});b(n)}catch(e){j.warn(e),_()}};let I=[];const C=()=>{E();const e=new URL(p);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",g.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${g.languageCode}`)),e.searchParams.set("conversationId",g.conversationId),n=new S(e.href),i=setInterval(()=>{(async()=>{1===n?.readyState&&null!=r[0]&&(await T(r[0]),r=r.slice(1))})()},500),n.onmessage=function(e){"string"==typeof e?.data&&b(M(e.data))}},O=()=>{if(P(),!0!==t.bidirectional)return;const e=new URL(p);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",g.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${g.languageCode}`)),e.searchParams.set("conversationId",g.conversationId),e.searchParams.set("type","voice-plus"),null!=l?.apiKey&&e.searchParams.set("apiKey",l.apiKey),o=new S(e.href),c=setInterval(()=>{1===o?.readyState&&null!=a[0]&&(x(a[0]),a=a.slice(1))},500),o.onmessage=e=>{if("string"==typeof e?.data){const t=M(e.data);null!=t&&f.voicePlusCommand.forEach(e=>{e(t)})}}},E=()=>{null!=i&&clearInterval(i),null!=n&&(n.onmessage=null,n.close(),n=void 0)},P=()=>{null!=c&&clearInterval(c),null!=o&&(o.onmessage=null,o.close(),o=void 0)};h===e.Protocol.Websocket&&C(),O();const L=(t,n)=>{const o={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"structured",...$(t),context:n}};v({responses:[...g.responses,o]},o)},A=(e,t)=>{L({intentId:e},t),T({context:t,request:{structured:{intentId:e}}})},k=e=>{I=I.filter(t=>t!==e)};return{sendText:(t,n)=>{const o={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"text",text:t,context:n}};v({responses:[...g.responses,o]},o),T({context:n,request:{unstructured:{text:t}}})},sendContext:async e=>{const n=await fetch(`${m()}/context`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":l?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":g.conversationId,"nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.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()};v({responses:[...g.responses,t]},t)},setInterimMessage:e=>{f.interimMessage.forEach(t=>{t(e)})},sendStructured:(e,t)=>{L(e,t),T({context:t,request:{structured:$(e)}})},sendSlots:(e,t)=>{L({slots:e},t),T({context:t,request:{structured:{slots:q(e)}}})},sendFlow:A,sendIntent:(e,t)=>{j.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(D,e)},sendWelcomeIntent:e=>{j.warn("Calling `sendWelcomeIntent` is deprecated and will be removed in a future version of the SDK. Use `sendWelcomeFlow` instead."),A(D,e)},sendChoice:(t,n,o)=>{let r=[...g.responses];const i={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"choice",choiceId:t}},a=o?.responseIndex??-1,c=o?.messageIndex??-1;a>-1&&c>-1&&(r=s(a,n=>n.type===e.ResponseType.Application?{...n,payload:{...n.payload,messages:s(c,e=>({...e,selectedChoiceId:t}),n.payload.messages)}}:n,r)),r=[...r,i],v({responses:r},i),T({context:n,request:{structured:{nodeId:o?.nodeId,intentId:o?.flowId??o?.intentId,choiceId:t}}})},submitFeedback:async(e,t)=>{const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.userId,...t})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},currentConversationId:()=>g.conversationId,setLanguageCode:t=>{t!==g.languageCode?(l?.protocol===e.Protocol.Websocket&&C(),O(),v({languageCode:t})):j.warn("Attempted to set language code to the one already active.")},currentLanguageCode:()=>g.languageCode,getVoiceCredentials:async(e,n)=>{const o=await fetch(`${d}-${g.languageCode}/requestToken`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":l?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":g.conversationId,"nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.userId,requestToken:!0,context:e,autoTriggerWelcomeFlow:n?.autoTriggerWelcomeFlow??!0})});if(o.status>=400)throw new Error(`Responded with ${o.status}`);const r=await o.json();if(null==r?.url)throw new Error("Invalid response");return r},subscribe:e=>(I=[...I,e],e(W(g)),()=>{k(e)}),unsubscribe:k,unsubscribeAll:()=>{I=[]},reset:t=>{v({conversationId:R(),responses:!0===t?.clearResponses?[]:g.responses}),l?.protocol===e.Protocol.Websocket&&C(),O()},destroy:()=>{I=[],l?.protocol===e.Protocol.Websocket&&E(),P()},setRequestOverride:e=>{w=e},addEventListener:(e,t)=>{f[e]=[...f[e],t]},removeEventListener:(e,t)=>{f[e]=f[e].filter(e=>e!==t)},sendVoicePlusContext:e=>{x({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=>null!=F(e),e.promisify=function(t,n,o=1e4){return async r=>await new Promise((s,i)=>{const a=setTimeout(()=>{i(new Error("The request timed out.")),n.unsubscribe(c)},o),c=(t,o)=>{o?.type!==e.ResponseType.Application&&o?.type!==e.ResponseType.Failure||(clearTimeout(a),n.unsubscribe(c),s(o))};n.subscribe(c),t(r)})},e.sendVoicePlusStep=async({apiKey:e,workspaceId:t,conversationId:n,scriptId:o,languageCode:r,step:s,context:i,debug:a=!1,dev:c=!1})=>{if(null==o)throw new Error("Voice+ scriptId is not defined.");if("string"!=typeof n||0===n.length)throw new Error("Voice+ conversationId is not defined.");const[l,u]="string"==typeof s?[s,void 0]:[s.stepId,s.stepTriggerDescription];if(!J.test(l))throw new Error("Invalid stepId. It should be formatted as a UUID.");const p={stepId:l,context:i,conversationId:n,journeyId:o,languageCode:r,stepTriggerDescription:u};try{await fetch(`https://${c?"dev.":""}mm.nlx.ai/v1/track`,{method:"POST",headers:{"x-api-key":e,"x-nlx-id":t,"Content-Type":"application/json","nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify(p)}),a&&j.info(`✓ step: ${l}`,p)}catch(e){throw a&&j.error(`× step: ${l}`,e,p),e}},e.shouldReinitialize=(e,t)=>!b(e,t),e.version=k});
15
+ ***************************************************************************** */function x(e,t){function n(){this.constructor=e}w(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function T(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var o,r,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(o=s.next()).done;)i.push(o.value)}catch(e){r={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}finally{if(r)throw r.error}}return i}var I=function(e,t){this.target=t,this.type=e},C=function(e){function t(t,n){var o=e.call(this,"error",n)||this;return o.message=t.message,o.error=t,o}return x(t,e),t}(I),O=function(e){function t(t,n,o){void 0===t&&(t=1e3),void 0===n&&(n="");var r=e.call(this,"close",o)||this;return r.wasClean=!0,r.code=t,r.reason=n,r}return x(t,e),t}(I),E=function(){if("undefined"!=typeof WebSocket)return WebSocket},P={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+4e3*Math.random(),minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0},S=function(){function e(e,t,n){var o=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){o._debug("open event");var t=o._options.minUptime,n=void 0===t?P.minUptime:t;clearTimeout(o._connectTimeout),o._uptimeTimeout=setTimeout(function(){return o._acceptOpen()},n),o._ws.binaryType=o._binaryType,o._messageQueue.forEach(function(e){return o._ws.send(e)}),o._messageQueue=[],o.onopen&&o.onopen(e),o._listeners.open.forEach(function(t){return o._callEventListener(e,t)})},this._handleMessage=function(e){o._debug("message event"),o.onmessage&&o.onmessage(e),o._listeners.message.forEach(function(t){return o._callEventListener(e,t)})},this._handleError=function(e){o._debug("error event",e.message),o._disconnect(void 0,"TIMEOUT"===e.message?"timeout":void 0),o.onerror&&o.onerror(e),o._debug("exec error listeners"),o._listeners.error.forEach(function(t){return o._callEventListener(e,t)}),o._connect()},this._handleClose=function(e){o._debug("close event"),o._clearTimeouts(),o._shouldReconnect&&o._connect(),o.onclose&&o.onclose(e),o._listeners.close.forEach(function(t){return o._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?P.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,o=this._listeners[e.type];if(o)try{for(var r=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}}}}(o),s=r.next();!s.done;s=r.next()){var i=s.value;this._callEventListener(e,i)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}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(T(arguments[t]));return e}(["RWS>"],e))},e.prototype._getNextDelay=function(){var e=this._options,t=e.reconnectionDelayGrowFactor,n=void 0===t?P.reconnectionDelayGrowFactor:t,o=e.minReconnectionDelay,r=void 0===o?P.minReconnectionDelay:o,s=e.maxReconnectionDelay,i=void 0===s?P.maxReconnectionDelay:s,a=0;return this._retryCount>0&&(a=r*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,o=void 0===n?P.maxRetries:n,r=t.connectionTimeout,s=void 0===r?P.connectionTimeout:r,i=t.WebSocket,a=void 0===i?E():i;if(this._retryCount>=o)this._debug("max retries reached",this._retryCount,">=",o);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 C(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 O(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}();const L=[];for(let e=0;e<256;++e)L.push((e+256).toString(16).slice(1));const A=new Uint8Array(16);function R(e,t,n){return crypto.randomUUID?crypto.randomUUID():function(e){e=e||{};const t=e.random??e.rng?.()??crypto.getRandomValues(A);if(t.length<16)throw new Error("Random bytes length must be >= 16");return t[6]=15&t[6]|64,t[8]=63&t[8]|128,function(e,t=0){return(L[e[t+0]]+L[e[t+1]]+L[e[t+2]]+L[e[t+3]]+"-"+L[e[t+4]]+L[e[t+5]]+"-"+L[e[t+6]]+L[e[t+7]]+"-"+L[e[t+8]]+L[e[t+9]]+"-"+L[e[t+10]]+L[e[t+11]]+L[e[t+12]]+L[e[t+13]]+L[e[t+14]]+L[e[t+15]]).toLowerCase()}(t)}(e)}var U="1.2.7-alpha.2";const k=U,j=console;var K,N;e.Protocol=void 0,(K=e.Protocol||(e.Protocol={})).Http="http",K.HttpWithStreaming="httpWithStreaming",K.Https="https",K.HttpsWithStreaming="httpsWithStreaming",K.Websocket="websocket",e.ResponseType=void 0,(N=e.ResponseType||(e.ResponseType={})).Application="bot",N.User="user",N.Failure="failure";const D="NLX.Welcome",W=e=>Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({slotId:e,value:t})),q=e=>({...e,intentId:e.flowId??e.intentId,slots:null!=e.slots?W(e.slots):e.slots}),$=e=>e.responses,M=e=>{try{return JSON.parse(e)}catch(e){return null}},F=t=>{const n=t.applicationUrl??"",o=t.apiKey??t.headers?.["nlx-api-key"]??"",r=t.protocol??(H(n)?e.Protocol.Websocket:!1===t.experimental?.streamHttp?e.Protocol.Https:e.Protocol.HttpsWithStreaming);if(null!=t.host&&null!=t.channelKey&&null!=t.deploymentKey)return{protocol:r,apiKey:o,host:t.host,channelKey:t.channelKey,deploymentKey:t.deploymentKey};if(H(n)){const e=(e=>e.match(/(bots\.dev\.studio\.nlx\.ai|bots\.studio\.nlx\.ai|apps\.nlx\.ai|dev\.apps\.nlx\.ai)/g)?.[0]??"apps.nlx.ai")(n),t=new URL(n),s=new URLSearchParams(t.search),i=s.get("channelKey"),a=s.get("deploymentKey");return null!=i&&null!=a?{protocol:r,channelKey:i,deploymentKey:a,host:e,apiKey:o}:null}const s=new URL(n),i=s.host,a=new URLPattern({pathname:"/c/:deploymentKey/:channelKey"}).exec(n);return null!=a?.pathname.groups.channelKey&&null!=a?.pathname.groups.deploymentKey?{protocol:"http:"===s.protocol?!1===t.experimental?.streamHttp?e.Protocol.Http:e.Protocol.HttpWithStreaming:r,channelKey:a.pathname.groups.channelKey,deploymentKey:a.pathname.groups.deploymentKey,host:i,apiKey:o}:null},H=e=>0===e.indexOf("wss://"),G=async({fullApplicationUrl:e,apiKey:t,headers:n,body:o,stream:r,eventListeners:s})=>{if(r)return await(async o=>{s.interimMessage.forEach(e=>{e("Thinking...")});const r=await fetch(e,{method:"POST",headers:{...n,"nlx-api-key":t,"Content-Type":"application/json","nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({...o,stream:!0})});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);const i=r.body.getReader(),a=new TextDecoder;let c="";const l=[];let u={};for(;;){const{done:e,value:t}=await i.read();if(e)break;for(c+=a.decode(t,{stream:!0});;){const e=c.indexOf("{");if(-1===e)break;let t=!1;for(let n=0;n<c.length;n++)if("}"===c[n]){const o=c.substring(e,n+1);try{const e=JSON.parse(o);if("interim"===e.type){const t=e.text;"string"==typeof t&&s.interimMessage.forEach(e=>{e(t)})}else"message"===e.type?l.push({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}):"final_response"===e.type&&(u=e.data);c=c.substring(n+1),t=!0;break}catch(e){}}if(!t)break}}return s.interimMessage.forEach(e=>{e(void 0)}),{...u,messages:[...l,...(u.messages??[]).map(e=>({text:e.text,choices:e.choices??[],messageId:e.messageId,metadata:e.metadata}))]}})(o);{const r=await fetch(e,{method:"POST",headers:{...n??{},"nlx-api-key":t,Accept:"application/json","Content-Type":"application/json","nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify(o)});if(!r.ok||null==r.body)throw new Error(`HTTP Error: ${r.status}`);return await r.json()}};const J=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;e.createConversation=function(t){let n,o,r=[],i=null,a=[],c=null;const l=F(t),u=!0===t.experimental?.completeApplicationUrl,p=u&&H(t.applicationUrl??"")?t.applicationUrl??"":null!=l?(e=>`wss://us-east-1-ws.${e.host}?deploymentKey=${e.deploymentKey}&channelKey=${e.channelKey}&apiKey=${e.apiKey}`)(l):t.applicationUrl??"",d=u&&!H(t.applicationUrl??"")?t.applicationUrl??"":null!=l?(t=>`${t.protocol===e.Protocol.Http?"http":"https"}://${t.host}/c/${t.deploymentKey}/${t.channelKey}`)(l):t.applicationUrl??"";/[-|_][a-z]{2,}[-|_][A-Z]{2,}$/.test(d)&&j.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 h=null!=l?l.protocol:H(t.applicationUrl??"")?e.Protocol.Websocket:!1===t.experimental?.streamHttp?e.Protocol.Https:e.Protocol.HttpsWithStreaming,f={voicePlusCommand:[],interimMessage:[]},y=t.conversationId??R();let g={responses:t.responses??[],languageCode:t.languageCode,userId:t.userId,conversationId:y};const m=()=>`${d}${u?"":`-${g.languageCode}`}`,v=(e,t)=>{g={...g,...e},I.forEach(e=>{e($(g),t)})},_=()=>{f.interimMessage.forEach(e=>{e(void 0)});const n={type:e.ResponseType.Failure,receivedAt:(new Date).getTime(),payload:{text:t.failureMessage??"We encountered an issue. Please try again soon."}};v({responses:[...g.responses,n]},n)},b=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??[]}))}};v({responses:[...g.responses,n]},n),t.metadata.hasPendingDataRequest&&(L({poll:!0}),setTimeout(()=>{T({request:{structured:{poll:!0}}})},1500))}else j.warn("Invalid message structure, expected object with field 'messages'."),_()};let w;const x=e=>{1===o?.readyState?o.send(JSON.stringify(e)):a=[...a,e]},T=async o=>{if(null!=w)return void w(o,t=>{j.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};v({responses:[...g.responses,n]},n)});const s={userId:g.userId,conversationId:g.conversationId,...o,languageCode:g.languageCode,channelType:t.experimental?.channelType,environment:t.environment};if(h===e.Protocol.Websocket)1===n?.readyState?n.send(JSON.stringify(s)):r=[...r,s];else try{const n=await G({fullApplicationUrl:m(),apiKey:l?.apiKey??"",headers:t.headers??{},stream:h===e.Protocol.HttpsWithStreaming||h===e.Protocol.HttpWithStreaming,eventListeners:f,body:s});b(n)}catch(e){j.warn(e),_()}};let I=[];const C=()=>{E();const e=new URL(p);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",g.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${g.languageCode}`)),e.searchParams.set("conversationId",g.conversationId),n=new S(e.href),i=setInterval(()=>{(async()=>{1===n?.readyState&&null!=r[0]&&(await T(r[0]),r=r.slice(1))})()},500),n.onmessage=function(e){"string"==typeof e?.data&&b(M(e.data))}},O=()=>{if(P(),!0!==t.bidirectional)return;const e=new URL(p);!0!==t.experimental?.completeApplicationUrl&&(e.searchParams.set("languageCode",g.languageCode),e.searchParams.set("channelKey",`${e.searchParams.get("channelKey")??""}-${g.languageCode}`)),e.searchParams.set("conversationId",g.conversationId),e.searchParams.set("type","voice-plus"),null!=l?.apiKey&&e.searchParams.set("apiKey",l.apiKey),o=new S(e.href),c=setInterval(()=>{1===o?.readyState&&null!=a[0]&&(x(a[0]),a=a.slice(1))},500),o.onmessage=e=>{if("string"==typeof e?.data){const t=M(e.data);null!=t&&f.voicePlusCommand.forEach(e=>{e(t)})}}},E=()=>{null!=i&&clearInterval(i),null!=n&&(n.onmessage=null,n.close(),n=void 0)},P=()=>{null!=c&&clearInterval(c),null!=o&&(o.onmessage=null,o.close(),o=void 0)};h===e.Protocol.Websocket&&C(),O();const L=(t,n)=>{const o={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"structured",...q(t),context:n}};v({responses:[...g.responses,o]},o)},A=(e,t)=>{L({intentId:e},t),T({context:t,request:{structured:{intentId:e}}})},k=e=>{I=I.filter(t=>t!==e)};return{sendText:(t,n)=>{const o={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"text",text:t,context:n}};v({responses:[...g.responses,o]},o),T({context:n,request:{unstructured:{text:t}}})},sendContext:async e=>{const n=await fetch(`${m()}/context`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":l?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":g.conversationId,"nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.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()};v({responses:[...g.responses,t]},t)},setInterimMessage:e=>{f.interimMessage.forEach(t=>{t(e)})},sendStructured:(e,t)=>{L(e,t),T({context:t,request:{structured:q(e)}})},sendSlots:(e,t)=>{L({slots:e},t),T({context:t,request:{structured:{slots:W(e)}}})},sendFlow:A,sendIntent:(e,t)=>{j.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(D,e)},sendWelcomeIntent:e=>{j.warn("Calling `sendWelcomeIntent` is deprecated and will be removed in a future version of the SDK. Use `sendWelcomeFlow` instead."),A(D,e)},sendChoice:(t,n,o)=>{let r=[...g.responses];const i={type:e.ResponseType.User,receivedAt:(new Date).getTime(),payload:{type:"choice",choiceId:t}},a=o?.responseIndex??-1,c=o?.messageIndex??-1;a>-1&&c>-1&&(r=s(a,n=>n.type===e.ResponseType.Application?{...n,payload:{...n.payload,messages:s(c,e=>({...e,selectedChoiceId:t}),n.payload.messages)}}:n,r)),r=[...r,i],v({responses:r},i),T({context:n,request:{structured:{nodeId:o?.nodeId,intentId:o?.flowId??o?.intentId,choiceId:t}}})},submitFeedback:async(e,t)=>{const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.userId,...t})});if(n.status>=400)throw new Error(`Responded with ${n.status}`)},currentConversationId:()=>g.conversationId,setLanguageCode:t=>{t!==g.languageCode?(l?.protocol===e.Protocol.Websocket&&C(),O(),v({languageCode:t})):j.warn("Attempted to set language code to the one already active.")},currentLanguageCode:()=>g.languageCode,getVoiceCredentials:async(e,n)=>{const o=await fetch(`${d}-${g.languageCode}/requestToken`,{method:"POST",headers:{...t.headers??{},"nlx-api-key":l?.apiKey??"",Accept:"application/json","Content-Type":"application/json","nlx-conversation-id":g.conversationId,"nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify({languageCode:g.languageCode,conversationId:g.conversationId,userId:g.userId,requestToken:!0,context:e,autoTriggerWelcomeFlow:n?.autoTriggerWelcomeFlow??!0})});if(o.status>=400)throw new Error(`Responded with ${o.status}`);const r=await o.json();if(null==r?.url)throw new Error("Invalid response");return r},subscribe:e=>(I=[...I,e],e($(g)),()=>{k(e)}),unsubscribe:k,unsubscribeAll:()=>{I=[]},reset:t=>{v({conversationId:R(),responses:!0===t?.clearResponses?[]:g.responses}),l?.protocol===e.Protocol.Websocket&&C(),O()},destroy:()=>{I=[],l?.protocol===e.Protocol.Websocket&&E(),P()},setRequestOverride:e=>{w=e},addEventListener:(e,t)=>{f[e]=[...f[e],t]},removeEventListener:(e,t)=>{f[e]=f[e].filter(e=>e!==t)},sendVoicePlusContext:e=>{x({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=>null!=F(e),e.promisify=function(t,n,o=1e4){return async r=>await new Promise((s,i)=>{const a=setTimeout(()=>{i(new Error("The request timed out.")),n.unsubscribe(c)},o),c=(t,o)=>{o?.type!==e.ResponseType.Application&&o?.type!==e.ResponseType.Failure||(clearTimeout(a),n.unsubscribe(c),s(o))};n.subscribe(c),t(r)})},e.sendVoicePlusStep=async({apiKey:e,workspaceId:t,conversationId:n,scriptId:o,languageCode:r,step:s,context:i,debug:a=!1,dev:c=!1})=>{if(null==o)throw new Error("Voice+ scriptId is not defined.");if("string"!=typeof n||0===n.length)throw new Error("Voice+ conversationId is not defined.");const[l,u]="string"==typeof s?[s,void 0]:[s.stepId,s.stepTriggerDescription];if(!J.test(l))throw new Error("Invalid stepId. It should be formatted as a UUID.");const p={stepId:l,context:i,conversationId:n,journeyId:o,languageCode:r,stepTriggerDescription:u};try{await fetch(`https://${c?"dev.":""}mm.nlx.ai/v1/track`,{method:"POST",headers:{"x-api-key":e,"x-nlx-id":t,"Content-Type":"application/json","nlx-sdk-version":U,"nlx-core-version":U},body:JSON.stringify(p)}),a&&j.info(`✓ step: ${l}`,p)}catch(e){throw a&&j.error(`× step: ${l}`,e,p),e}},e.shouldReinitialize=(e,t)=>!b(e,t),e.version=k});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nlxai/core",
3
- "version": "1.2.7-alpha.1",
3
+ "version": "1.2.7-alpha.2",
4
4
  "description": "Low-level SDK for building NLX experiences",
5
5
  "type": "module",
6
6
  "main": "lib/index.cjs",
@@ -52,5 +52,5 @@
52
52
  "publishConfig": {
53
53
  "access": "public"
54
54
  },
55
- "gitHead": "548c2c6c876cf86572aeb63a6810ed87c9b0382a"
55
+ "gitHead": "28deac5208ff64f99a3d038050172c1ac9a78630"
56
56
  }