@aikaara/chat-sdk 0.8.8 → 0.8.9
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/dist/{MountTenant-YYFWHzOg.cjs → MountTenant-BCdh7baG.cjs} +1 -1
- package/dist/{MountTenant-DvFjmSTt.mjs → MountTenant-Df3fIQU6.mjs} +5 -13
- package/dist/cdn/aikaara-chat.iife.js +1 -1
- package/dist/headless.cjs +1 -1
- package/dist/headless.mjs +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +2 -2
- package/dist/ui.cjs +1 -1
- package/dist/ui.mjs +1 -1
- package/package.json +1 -1
|
@@ -5,7 +5,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
5
5
|
`+ie.prev+ie.base;return xe+I.call(z,","+xe)+`
|
|
6
6
|
`+ie.prev}function ke(z,ie){var xe=be(z),Ae=[];if(xe){Ae.length=z.length;for(var Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],z):""}var Ce=typeof T=="function"?T(z):[],Ge;if(D){Ge={};for(var Ye=0;Ye<Ce.length;Ye++)Ge["$"+Ce[Ye]]=Ce[Ye]}for(var Ue in z)oe(z,Ue)&&(xe&&String(Number(Ue))===Ue&&Ue<z.length||D&&Ge["$"+Ue]instanceof Symbol||(x.call(/[^\w$]/,Ue)?Ae.push(ie(Ue,z)+": "+ie(z[Ue],z)):Ae.push(Ue+": "+ie(z[Ue],z))));if(typeof T=="function")for(var Qe=0;Qe<Ce.length;Qe++)ae.call(z,Ce[Qe])&&Ae.push("["+ie(Ce[Qe])+"]: "+ie(z[Ce[Qe]],z));return Ae}return _r}function Xu(){if(Di)return Sr;Di=!0;var c=Bt(),e=Uu(),t=Ju(),r=Jt(),a=c("%WeakMap%",!0),n=c("%Map%",!0),i=e("WeakMap.prototype.get",!0),s=e("WeakMap.prototype.set",!0),o=e("WeakMap.prototype.has",!0),l=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(b,k){for(var m=b,w;(w=m.next)!==null;m=w)if(w.key===k)return m.next=w.next,w.next=b.next,b.next=w,w},y=function(b,k){var m=p(b,k);return m&&m.value},f=function(b,k,m){var w=p(b,k);w?w.value=m:b.next={key:k,next:b.next,value:m}},g=function(b,k){return!!p(b,k)};return Sr=function(){var b,k,m,w={assert:function(E){if(!w.has(E))throw new r("Side channel does not contain "+t(E))},get:function(E){if(a&&E&&(typeof E=="object"||typeof E=="function")){if(b)return i(b,E)}else if(n){if(k)return l(k,E)}else if(m)return y(m,E)},has:function(E){if(a&&E&&(typeof E=="object"||typeof E=="function")){if(b)return o(b,E)}else if(n){if(k)return d(k,E)}else if(m)return g(m,E);return!1},set:function(E,v){a&&E&&(typeof E=="object"||typeof E=="function")?(b||(b=new a),s(b,E,v)):n?(k||(k=new n),u(k,E,v)):(m||(m={key:{},next:null}),f(m,E,v))}};return w},Sr}function oo(){if(Fi)return Er;Fi=!0;var c=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Er={default:t.RFC3986,formatters:{RFC1738:function(r){return c.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Er}function Da(){if($i)return xr;$i=!0;var c=oo(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var b=[],k=0;k<256;++k)b.push("%"+((k<16?"0":"")+k.toString(16)).toUpperCase());return b})(),a=function(b){for(;b.length>1;){var k=b.pop(),m=k.obj[k.prop];if(t(m)){for(var w=[],E=0;E<m.length;++E)typeof m[E]<"u"&&w.push(m[E]);k.obj[k.prop]=w}}},n=function(b,k){for(var m=k&&k.plainObjects?Object.create(null):{},w=0;w<b.length;++w)typeof b[w]<"u"&&(m[w]=b[w]);return m},i=function b(k,m,w){if(!m)return k;if(typeof m!="object"){if(t(k))k.push(m);else if(k&&typeof k=="object")(w&&(w.plainObjects||w.allowPrototypes)||!e.call(Object.prototype,m))&&(k[m]=!0);else return[k,m];return k}if(!k||typeof k!="object")return[k].concat(m);var E=k;return t(k)&&!t(m)&&(E=n(k,w)),t(k)&&t(m)?(m.forEach(function(v,x){if(e.call(k,x)){var S=k[x];S&&typeof S=="object"&&v&&typeof v=="object"?k[x]=b(S,v,w):k.push(v)}else k[x]=v}),k):Object.keys(m).reduce(function(v,x){var S=m[x];return e.call(v,x)?v[x]=b(v[x],S,w):v[x]=S,v},E)},s=function(b,k){return Object.keys(k).reduce(function(m,w){return m[w]=k[w],m},b)},o=function(b,k,m){var w=b.replace(/\+/g," ");if(m==="iso-8859-1")return w.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(w)}catch{return w}},l=1024,u=function(b,k,m,w,E){if(b.length===0)return b;var v=b;if(typeof b=="symbol"?v=Symbol.prototype.toString.call(b):typeof b!="string"&&(v=String(b)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var x="",S=0;S<v.length;S+=l){for(var I=v.length>=l?v.slice(S,S+l):v,M=[],O=0;O<I.length;++O){var B=I.charCodeAt(O);if(B===45||B===46||B===95||B===126||B>=48&&B<=57||B>=65&&B<=90||B>=97&&B<=122||E===c.RFC1738&&(B===40||B===41)){M[M.length]=I.charAt(O);continue}if(B<128){M[M.length]=r[B];continue}if(B<2048){M[M.length]=r[192|B>>6]+r[128|B&63];continue}if(B<55296||B>=57344){M[M.length]=r[224|B>>12]+r[128|B>>6&63]+r[128|B&63];continue}O+=1,B=65536+((B&1023)<<10|I.charCodeAt(O)&1023),M[M.length]=r[240|B>>18]+r[128|B>>12&63]+r[128|B>>6&63]+r[128|B&63]}x+=M.join("")}return x},d=function(b){for(var k=[{obj:{o:b},prop:"o"}],m=[],w=0;w<k.length;++w)for(var E=k[w],v=E.obj[E.prop],x=Object.keys(v),S=0;S<x.length;++S){var I=x[S],M=v[I];typeof M=="object"&&M!==null&&m.indexOf(M)===-1&&(k.push({obj:v,prop:I}),m.push(M))}return a(k),b},p=function(b){return Object.prototype.toString.call(b)==="[object RegExp]"},y=function(b){return!b||typeof b!="object"?!1:!!(b.constructor&&b.constructor.isBuffer&&b.constructor.isBuffer(b))},f=function(b,k){return[].concat(b,k)},g=function(b,k){if(t(b)){for(var m=[],w=0;w<b.length;w+=1)m.push(k(b[w]));return m}return k(b)};return xr={arrayToObject:n,assign:s,combine:f,compact:d,decode:o,encode:u,isBuffer:y,isRegExp:p,maybeMap:g,merge:i},xr}function Zu(){if(Wi)return Ar;Wi=!0;var c=Xu(),e=Da(),t=oo(),r=Object.prototype.hasOwnProperty,a={brackets:function(g){return g+"[]"},comma:"comma",indices:function(g,b){return g+"["+b+"]"},repeat:function(g){return g}},n=Array.isArray,i=Array.prototype.push,s=function(g,b){i.apply(g,n(b)?b:[b])},o=Date.prototype.toISOString,l=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:l,formatter:t.formatters[l],indices:!1,serializeDate:function(g){return o.call(g)},skipNulls:!1,strictNullHandling:!1},d=function(g){return typeof g=="string"||typeof g=="number"||typeof g=="boolean"||typeof g=="symbol"||typeof g=="bigint"},p={},y=function g(b,k,m,w,E,v,x,S,I,M,O,B,T,W,D,N,ae,Y){for(var K=b,re=Y,F=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var P=re.get(b);if(F+=1,typeof P<"u"){if(P===F)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(F=0)}if(typeof M=="function"?K=M(k,K):K instanceof Date?K=T(K):m==="comma"&&n(K)&&(K=e.maybeMap(K,function(R){return R instanceof Date?T(R):R})),K===null){if(v)return I&&!N?I(k,u.encoder,ae,"key",W):k;K=""}if(d(K)||e.isBuffer(K)){if(I){var J=N?k:I(k,u.encoder,ae,"key",W);return[D(J)+"="+D(I(K,u.encoder,ae,"value",W))]}return[D(k)+"="+D(String(K))]}var be=[];if(typeof K>"u")return be;var te;if(m==="comma"&&n(K))N&&I&&(K=e.maybeMap(K,I)),te=[{value:K.length>0?K.join(",")||null:void 0}];else if(n(M))te=M;else{var we=Object.keys(K);te=O?we.sort(O):we}var V=S?k.replace(/\./g,"%2E"):k,L=w&&n(K)&&K.length===1?V+"[]":V;if(E&&n(K)&&K.length===0)return L+"[]";for(var ne=0;ne<te.length;++ne){var H=te[ne],G=typeof H=="object"&&typeof H.value<"u"?H.value:K[H];if(!(x&&G===null)){var Q=B&&S?H.replace(/\./g,"%2E"):H,me=n(K)?typeof m=="function"?m(L,Q):L:L+(B?"."+Q:"["+Q+"]");Y.set(b,F);var oe=c();oe.set(p,Y),s(be,g(G,me,m,w,E,v,x,S,m==="comma"&&N&&n(K)?null:I,M,O,B,T,W,D,N,ae,oe))}}return be},f=function(g){if(!g)return u;if(typeof g.allowEmptyArrays<"u"&&typeof g.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof g.encodeDotInKeys<"u"&&typeof g.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(g.encoder!==null&&typeof g.encoder<"u"&&typeof g.encoder!="function")throw new TypeError("Encoder has to be a function.");var b=g.charset||u.charset;if(typeof g.charset<"u"&&g.charset!=="utf-8"&&g.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var k=t.default;if(typeof g.format<"u"){if(!r.call(t.formatters,g.format))throw new TypeError("Unknown format option provided.");k=g.format}var m=t.formatters[k],w=u.filter;(typeof g.filter=="function"||n(g.filter))&&(w=g.filter);var E;if(g.arrayFormat in a?E=g.arrayFormat:"indices"in g?E=g.indices?"indices":"repeat":E=u.arrayFormat,"commaRoundTrip"in g&&typeof g.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof g.allowDots>"u"?g.encodeDotInKeys===!0?!0:u.allowDots:!!g.allowDots;return{addQueryPrefix:typeof g.addQueryPrefix=="boolean"?g.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof g.allowEmptyArrays=="boolean"?!!g.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:E,charset:b,charsetSentinel:typeof g.charsetSentinel=="boolean"?g.charsetSentinel:u.charsetSentinel,commaRoundTrip:g.commaRoundTrip,delimiter:typeof g.delimiter>"u"?u.delimiter:g.delimiter,encode:typeof g.encode=="boolean"?g.encode:u.encode,encodeDotInKeys:typeof g.encodeDotInKeys=="boolean"?g.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof g.encoder=="function"?g.encoder:u.encoder,encodeValuesOnly:typeof g.encodeValuesOnly=="boolean"?g.encodeValuesOnly:u.encodeValuesOnly,filter:w,format:k,formatter:m,serializeDate:typeof g.serializeDate=="function"?g.serializeDate:u.serializeDate,skipNulls:typeof g.skipNulls=="boolean"?g.skipNulls:u.skipNulls,sort:typeof g.sort=="function"?g.sort:null,strictNullHandling:typeof g.strictNullHandling=="boolean"?g.strictNullHandling:u.strictNullHandling}};return Ar=function(g,b){var k=g,m=f(b),w,E;typeof m.filter=="function"?(E=m.filter,k=E("",k)):n(m.filter)&&(E=m.filter,w=E);var v=[];if(typeof k!="object"||k===null)return"";var x=a[m.arrayFormat],S=x==="comma"&&m.commaRoundTrip;w||(w=Object.keys(k)),m.sort&&w.sort(m.sort);for(var I=c(),M=0;M<w.length;++M){var O=w[M];m.skipNulls&&k[O]===null||s(v,y(k[O],O,x,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var B=v.join(m.delimiter),T=m.addQueryPrefix===!0?"?":"";return m.charsetSentinel&&(m.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),B.length>0?T+B:""},Ar}function eh(){if(qi)return Ir;qi=!0;var c=Da(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:c.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},a=function(p){return p.replace(/&#(\d+);/g,function(y,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,y){return p&&typeof p=="string"&&y.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",s="utf8=%E2%9C%93",o=function(p,y){var f={__proto__:null},g=y.ignoreQueryPrefix?p.replace(/^\?/,""):p;g=g.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var b=y.parameterLimit===1/0?void 0:y.parameterLimit,k=g.split(y.delimiter,b),m=-1,w,E=y.charset;if(y.charsetSentinel)for(w=0;w<k.length;++w)k[w].indexOf("utf8=")===0&&(k[w]===s?E="utf-8":k[w]===i&&(E="iso-8859-1"),m=w,w=k.length);for(w=0;w<k.length;++w)if(w!==m){var v=k[w],x=v.indexOf("]="),S=x===-1?v.indexOf("="):x+1,I,M;S===-1?(I=y.decoder(v,r.decoder,E,"key"),M=y.strictNullHandling?null:""):(I=y.decoder(v.slice(0,S),r.decoder,E,"key"),M=c.maybeMap(n(v.slice(S+1),y),function(B){return y.decoder(B,r.decoder,E,"value")})),M&&y.interpretNumericEntities&&E==="iso-8859-1"&&(M=a(M)),v.indexOf("[]=")>-1&&(M=t(M)?[M]:M);var O=e.call(f,I);O&&y.duplicates==="combine"?f[I]=c.combine(f[I],M):(!O||y.duplicates==="last")&&(f[I]=M)}return f},l=function(p,y,f,g){for(var b=g?y:n(y,f),k=p.length-1;k>=0;--k){var m,w=p[k];if(w==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(b===""||f.strictNullHandling&&b===null)?[]:[].concat(b);else{m=f.plainObjects?Object.create(null):{};var E=w.charAt(0)==="["&&w.charAt(w.length-1)==="]"?w.slice(1,-1):w,v=f.decodeDotInKeys?E.replace(/%2E/g,"."):E,x=parseInt(v,10);!f.parseArrays&&v===""?m={0:b}:!isNaN(x)&&w!==v&&String(x)===v&&x>=0&&f.parseArrays&&x<=f.arrayLimit?(m=[],m[x]=b):v!=="__proto__"&&(m[v]=b)}b=m}return b},u=function(p,y,f,g){if(p){var b=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,k=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,w=f.depth>0&&k.exec(b),E=w?b.slice(0,w.index):b,v=[];if(E){if(!f.plainObjects&&e.call(Object.prototype,E)&&!f.allowPrototypes)return;v.push(E)}for(var x=0;f.depth>0&&(w=m.exec(b))!==null&&x<f.depth;){if(x+=1,!f.plainObjects&&e.call(Object.prototype,w[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(w[1])}if(w){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+b.slice(w.index)+"]")}return l(v,y,f,g)}},d=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var y=typeof p.charset>"u"?r.charset:p.charset,f=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var g=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:g,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:y,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||c.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:f,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:r.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:r.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:r.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:r.strictNullHandling}};return Ir=function(p,y){var f=d(y);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?o(p,f):p,b=f.plainObjects?Object.create(null):{},k=Object.keys(g),m=0;m<k.length;++m){var w=k[m],E=u(w,g[w],f,typeof p=="string");b=c.merge(b,E,f)}return f.allowSparse===!0?b:c.compact(b)},Ir}function th(){if(Hi)return Tr;Hi=!0;var c=Zu(),e=eh(),t=oo();return Tr={formats:t,parse:e,stringify:c},Tr}function rh(){if(zi)return mt;zi=!0;var c=gt;function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var t=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,a=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
7
|
`," "],i=["{","}","|","\\","^","`"].concat(n),s=["'"].concat(i),o=["%","/","?",";","#"].concat(s),l=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=th();function k(v,x,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,x,S),I}e.prototype.parse=function(v,x,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),M=I!==-1&&I<v.indexOf("#")?"?":"#",O=v.split(M),B=/\\/g;O[0]=O[0].replace(B,"/"),v=O.join(M);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var W=a.exec(T);if(W)return this.path=T,this.href=T,this.pathname=W[1],W[2]?(this.search=W[2],x?this.query=b.parse(this.search.substr(1)):this.query=this.search.substr(1)):x&&(this.search="",this.query={}),this}var D=t.exec(T);if(D){D=D[0];var N=D.toLowerCase();this.protocol=N,T=T.substr(D.length)}if(S||D||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(D&&f[D])&&(T=T.substr(2),this.slashes=!0)}if(!f[D]&&(ae||D&&!g[D])){for(var Y=-1,K=0;K<l.length;K++){var re=T.indexOf(l[K]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var F,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(F=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(F)),Y=-1;for(var K=0;K<o.length;K++){var re=T.indexOf(o[K]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var P=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!P)for(var J=this.hostname.split(/\./),K=0,be=J.length;K<be;K++){var te=J[K];if(te&&!te.match(d)){for(var we="",V=0,L=te.length;V<L;V++)te.charCodeAt(V)>127?we+="x":we+=te[V];if(!we.match(d)){var ne=J.slice(0,K),H=J.slice(K+1),G=te.match(p);G&&(ne.push(G[1]),H.unshift(G[2])),H.length&&(T="/"+H.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=c.toASCII(this.hostname));var Q=this.port?":"+this.port:"",me=this.hostname||"";this.host=me+Q,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!y[N])for(var K=0,be=s.length;K<be;K++){var oe=s[K];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var $=T.indexOf("#");$!==-1&&(this.hash=T.substr($),T=T.slice(0,$));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),x&&(this.query=b.parse(this.query)),T=T.slice(0,ee)):x&&(this.search="",this.query={}),T&&(this.pathname=T),g[N]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Q=this.pathname||"",fe=this.search||"";this.path=Q+fe}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=k(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var x=this.protocol||"",S=this.pathname||"",I=this.hash||"",M=!1,O="";this.host?M=v+this.host:this.hostname&&(M=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(M+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(O=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var B=this.search||O&&"?"+O||"";return x&&x.substr(-1)!==":"&&(x+=":"),this.slashes||(!x||g[x])&&M!==!1?(M="//"+(M||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):M||(M=""),I&&I.charAt(0)!=="#"&&(I="#"+I),B&&B.charAt(0)!=="?"&&(B="?"+B),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),B=B.replace("#","%23"),x+M+S+B+I};function w(v,x){return k(v,!1,!0).resolve(x)}e.prototype.resolve=function(v){return this.resolveObject(k(v,!1,!0)).format()};function E(v,x){return v?k(v,!1,!0).resolveObject(x):x}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var x=new e;x.parse(v,!1,!0),v=x}for(var S=new e,I=Object.keys(this),M=0;M<I.length;M++){var O=I[M];S[O]=this[O]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var B=Object.keys(v),T=0;T<B.length;T++){var W=B[T];W!=="protocol"&&(S[W]=v[W])}return g[S.protocol]&&S.hostname&&!S.pathname&&(S.pathname="/",S.path=S.pathname),S.href=S.format(),S}if(v.protocol&&v.protocol!==S.protocol){if(!g[v.protocol]){for(var D=Object.keys(v),N=0;N<D.length;N++){var ae=D[N];S[ae]=v[ae]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!f[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),S.pathname=be.join("/")}else S.pathname=v.pathname;if(S.search=v.search,S.query=v.query,S.host=v.host||"",S.auth=v.auth,S.hostname=v.hostname||v.host,S.port=v.port,S.pathname||S.search){var Y=S.pathname||"",K=S.search||"";S.path=Y+K}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",F=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=F||re||S.host&&v.pathname,P=Z,J=S.pathname&&S.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!g[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(J[0]===""?J[0]=S.host:J.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||J[0]==="")),F)S.host=v.host||v.host===""?v.host:S.host,S.hostname=v.hostname||v.hostname===""?v.hostname:S.hostname,S.search=v.search,S.query=v.query,J=be;else if(be.length)J||(J=[]),J.pop(),J=J.concat(be),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=J.shift(),S.hostname=S.host;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return S.search=v.search,S.query=v.query,(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S}if(!J.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var V=J.slice(-1)[0],L=(S.host||v.host||J.length>1)&&(V==="."||V==="..")||V==="",ne=0,H=J.length;H>=0;H--)V=J[H],V==="."?J.splice(H,1):V===".."?(J.splice(H,1),ne++):ne&&(J.splice(H,1),ne--);if(!Z&&!P)for(;ne--;ne)J.unshift("..");Z&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),L&&J.join("/").substr(-1)!=="/"&&J.push("");var G=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(te){S.hostname=G?"":J.length?J.shift():"",S.host=S.hostname;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return Z=Z||S.host&&J.length,Z&&!G&&J.unshift(""),J.length>0?S.pathname=J.join("/"):(S.pathname=null,S.path=null),(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=v.auth||S.auth,S.slashes=S.slashes||v.slashes,S.href=S.format(),S},e.prototype.parseHost=function(){var v=this.host,x=r.exec(v);x&&(x=x[0],x!==":"&&(this.port=x.substr(1)),v=v.substr(0,v.length-x.length)),v&&(this.hostname=v)},mt.parse=k,mt.resolve=w,mt.resolveObject=E,mt.format=m,mt.Url=e,mt}function Fa(c){if(typeof c=="string")c=new URL(c);else if(!(c instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(c.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Or?nh(c):ih(c)}function nh(c){let e=c.hostname,t=c.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let a=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&a===102||t[r+1]==="5"&&a===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(Za,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,a=t[2];if(r<Ja||r>Xa||a!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function ih(c){if(c.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=c.pathname;for(let t=0;t<e.length;t++)if(e[t]==="%"){let r=e.codePointAt(t+2)||32;if(e[t+1]==="2"&&r===102)throw new Deno.errors.InvalidData("must not include encoded / characters")}return decodeURIComponent(e)}function $a(c){let e=Ui.resolve(c),t=c.charCodeAt(c.length-1);(t===Qa||Or&&t===Ya)&&e[e.length-1]!==Ui.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(el,"%25")),!Or&&e.includes("\\")&&(e=e.replace(tl,"%5C")),e.includes(`
|
|
8
|
-
`)&&(e=e.replace(rl,"%0A")),e.includes("\r")&&(e=e.replace(nl,"%0D")),e.includes(" ")&&(e=e.replace(il,"%09")),r.pathname=e,r}var Wa,_r,Bi,kr,Sr,Di,Er,Fi,xr,$i,Ar,Wi,Ir,qi,Tr,Hi,mt,zi,Fe,bs,qa,Ha,za,Ka,Va,Ga,Ya,Qa,Ja,Xa,Or,Za,el,tl,rl,nl,il,oh=He(()=>{le(),ue(),ce(),ku(),Bu(),Qu(),Ua(),Wa=Object.freeze(Object.create(null)),_r={},Bi=!1,kr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Sr={},Di=!1,Er={},Fi=!1,xr={},$i=!1,Ar={},Wi=!1,Ir={},qi=!1,Tr={},Hi=!1,mt={},zi=!1,Fe=rh(),Fe.parse,Fe.resolve,Fe.resolveObject,Fe.format,Fe.Url,bs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Fe.URL=typeof URL<"u"?URL:null,Fe.pathToFileURL=$a,Fe.fileURLToPath=Fa,qa=Fe.Url,Ha=Fe.format,za=Fe.resolve,Ka=Fe.resolveObject,Va=Fe.parse,Ga=Fe.URL,Ya=92,Qa=47,Ja=97,Xa=122,Or=bs==="win32",Za=/\//g,el=/%/g,tl=/\\/g,rl=/\n/g,nl=/\r/g,il=/\t/g}),sh=pe((c,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),so=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.BufferedDuplex=void 0,c.writev=r;var e=It(),t=(Ne(),Oe(Le));function r(n,i){let s=new Array(n.length);for(let o=0;o<n.length;o++)typeof n[o].chunk=="string"?s[o]=t.Buffer.from(n[o].chunk,"utf8"):s[o]=n[o].chunk;this._write(t.Buffer.concat(s),"binary",i)}var a=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,s){super({objectMode:!0}),this.proxy=i,this.socket=s,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",o=>{!this.destroyed&&this.readable&&this.push(o)})}_read(n){this.proxy.read(n)}_write(n,i,s){this.isSocketOpen?this.writeToProxy(n,i,s):this.writeQueue.push({chunk:n,encoding:i,cb:s})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,s){this.proxy.write(n,i)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:s}=this.writeQueue.shift();this.writeToProxy(n,i,s)}}};c.BufferedDuplex=a}),tr=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(k){return k&&k.__esModule?k:{default:k}};Object.defineProperty(c,"__esModule",{value:!0}),c.streamBuilder=c.browserStreamBuilder=void 0;var t=(Ne(),Oe(Le)),r=e(sh()),a=e(lt()),n=It(),i=e(Ur()),s=so(),o=(0,a.default)("mqttjs:ws"),l=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(k,m){let w=`${k.protocol}://${k.hostname}:${k.port}${k.path}`;return typeof k.transformWsUrl=="function"&&(w=k.transformWsUrl(w,k,m)),w}function d(k){let m=k;return k.port||(k.protocol==="wss"?m.port=443:m.port=80),k.path||(m.path="/"),k.wsOptions||(m.wsOptions={}),!i.default&&!k.forceNativeWebSocket&&k.protocol==="wss"&&l.forEach(w=>{Object.prototype.hasOwnProperty.call(k,w)&&!Object.prototype.hasOwnProperty.call(k.wsOptions,w)&&(m.wsOptions[w]=k[w])}),m}function p(k){let m=d(k);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let w=new URL(document.URL);m.hostname=w.hostname,m.port||(m.port=Number(w.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function y(k,m,w){o("createWebSocket"),o(`protocol: ${w.protocolId} ${w.protocolVersion}`);let E=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";o(`creating new Websocket for url: ${m} and protocol: ${E}`);let v;return w.createWebsocket?v=w.createWebsocket(m,[E],w):v=new r.default(m,[E],w.wsOptions),v}function f(k,m){let w=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",E=u(m,k),v;return m.createWebsocket?v=m.createWebsocket(E,[w],m):v=new WebSocket(E,[w]),v.binaryType="arraybuffer",v}var g=(k,m)=>{o("streamBuilder");let w=d(m);w.hostname=w.hostname||w.host||"localhost";let E=u(w,k),v=y(k,E,w),x=r.default.createWebSocketStream(v,w.wsOptions);return x.url=E,v.on("close",()=>{x.destroy()}),x};c.streamBuilder=g;var b=(k,m)=>{o("browserStreamBuilder");let w,E=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,x=!m.objectMode,S=f(k,m),I=O(m,N,ae);m.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{S.close()});let M=typeof S.addEventListener<"u";S.readyState===S.OPEN?(w=I,w.socket=S):(w=new s.BufferedDuplex(m,I,S),M?S.addEventListener("open",B):S.onopen=B),M?(S.addEventListener("close",T),S.addEventListener("error",W),S.addEventListener("message",D)):(S.onclose=T,S.onerror=W,S.onmessage=D);function O(Y,K,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=K,F._flush=re,F}function B(){o("WebSocket onOpen"),w instanceof s.BufferedDuplex&&w.socketReady()}function T(Y){o("WebSocket onClose",Y),w.end(),w.destroy()}function W(Y){o("WebSocket onError",Y);let K=new Error("WebSocket error");K.event=Y,w.destroy(K)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:K}=Y;K instanceof ArrayBuffer?K=t.Buffer.from(K):K instanceof Blob?K=t.Buffer.from(await new Response(K).arrayBuffer()):K=t.Buffer.from(K,"utf8"),I.push(K)}function N(Y,K,re){if(S.bufferedAmount>E){setTimeout(N,v,Y,K,re);return}x&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch(F){return re(F)}re()}function ae(Y){S.close(),Y()}return w};c.browserStreamBuilder=b}),ao={};Lt(ao,{Server:()=>Me,Socket:()=>Me,Stream:()=>Me,_createServerHandle:()=>Me,_normalizeArgs:()=>Me,_setSimultaneousAccepts:()=>Me,connect:()=>Me,createConnection:()=>Me,createServer:()=>Me,default:()=>ol,isIP:()=>Me,isIPv4:()=>Me,isIPv6:()=>Me});function Me(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var ol,sl=He(()=>{le(),ue(),ce(),ol={_createServerHandle:Me,_normalizeArgs:Me,_setSimultaneousAccepts:Me,connect:Me,createConnection:Me,createServer:Me,isIP:Me,isIPv4:Me,isIPv6:Me,Server:Me,Socket:Me,Stream:Me}}),al=pe((c,e)=>{le(),ue(),ce(),e.exports={}}),ys=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(c,"__esModule",{value:!0});var t=e((sl(),Oe(ao))),r=e(lt()),a=e(al()),n=(0,r.default)("mqttjs:tcp"),i=(s,o)=>{if(o.port=o.port||1883,o.hostname=o.hostname||o.host||"localhost",o.socksProxy)return(0,a.default)(o.hostname,o.port,o.socksProxy,{timeout:o.socksTimeout});let{port:l,path:u}=o,d=o.hostname;return n("port %d and host %s",l,d),t.default.createConnection({port:l,host:d,path:u})};c.default=i}),ll={};Lt(ll,{default:()=>cl});var cl,ah=He(()=>{le(),ue(),ce(),cl={}}),vs=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(c,"__esModule",{value:!0});var t=(ah(),Oe(ll)),r=e((sl(),Oe(ao))),a=e(lt()),n=e(al()),i=(0,a.default)("mqttjs:tls");function s(l){let{host:u,port:d,socksProxy:p,...y}=l;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:l.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(l)}var o=(l,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=s(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(y){u.rejectUnauthorized&&l.emit("error",y),d.end()}return d.on("error",p),d};c.default=o}),ws=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ne(),Oe(Le)),t=It(),r=so(),a,n,i;function s(){let p=new t.Transform;return p._write=(y,f,g)=>{a.send({data:y.buffer,success(){g()},fail(b){g(new Error(b))}})},p._flush=y=>{a.close({success(){y()}})},p}function o(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function l(p,y){let f=p.protocol==="wxs"?"wss":"ws",g=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,y)),g}function u(){a.onOpen(()=>{i.socketReady()}),a.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),n.push(y)}),a.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),a.onError(p=>{let y=new Error(p.errMsg);i.destroy(y)})}var d=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";o(y);let g=l(y,p);a=wx.connectSocket({url:g,protocols:[f]}),n=s(),i=new r.BufferedDuplex(y,n,a),i._destroy=(k,m)=>{a.close({success(){m&&m(k)}})};let b=i.destroy;return i.destroy=(k,m)=>(i.destroy=b,setTimeout(()=>{a.close({fail(){i._destroy(k,m)}})},0),i),u(),i};c.default=d}),_s=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ne(),Oe(Le)),t=It(),r=so(),a,n,i,s=!1;function o(){let y=new t.Transform;return y._write=(f,g,b)=>{a.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{a.closeSocket({success(){f()}})},y}function l(y){y.hostname||(y.hostname="localhost"),y.path||(y.path="/"),y.wsOptions||(y.wsOptions={})}function u(y,f){let g=y.protocol==="alis"?"wss":"ws",b=`${g}://${y.hostname}${y.path}`;return y.port&&y.port!==80&&y.port!==443&&(b=`${g}://${y.hostname}:${y.port}${y.path}`),typeof y.transformWsUrl=="function"&&(b=y.transformWsUrl(b,y,f)),b}function d(){s||(s=!0,a.onSocketOpen(()=>{i.socketReady()}),a.onSocketMessage(y=>{if(typeof y.data=="string"){let f=e.Buffer.from(y.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(y.data)}}),a.onSocketClose(()=>{i.end(),i.destroy()}),a.onSocketError(y=>{i.destroy(y)}))}var p=(y,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let g=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";l(f);let b=u(f,y);return a=f.my,a.connectSocket({url:b,protocols:g}),n=o(),i=new r.BufferedDuplex(f,n,a),d(),i};c.default=p}),lh=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(c,"__esModule",{value:!0}),c.connectAsync=u;var t=e(lt()),r=e((oh(),Oe(Ba))),a=e(ii()),n=e(Ur());typeof Pe?.nextTick!="function"&&(Pe.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),s=null;function o(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;d.username=y,d.password=f}else d.username=d.auth}function l(d,p){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let g=r.default.parse(d,!0),b={};if(g.port!=null&&(b.port=Number(g.port)),b.host=g.hostname,b.query=g.query,b.auth=g.auth,b.protocol=g.protocol,b.path=g.path,p={...b,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,o(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Pe<"u"&&(p.socksProxy=Pe.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=tr().streamBuilder,s.wss=tr().streamBuilder,s.mqtt=ys().default,s.tcp=ys().default,s.ssl=vs().default,s.tls=s.ssl,s.mqtts=vs().default):(s.ws=tr().browserStreamBuilder,s.wss=tr().browserStreamBuilder,s.wx=ws().default,s.wxs=ws().default,s.ali=_s().default,s.alis=_s().default)),!s[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,k)=>g&&k%2===0?!1:typeof s[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function y(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),s[p.protocol](g,p)}let f=new a.default(y,p);return f.on("error",()=>{}),f}function u(d,p,y=!0){return new Promise((f,g)=>{let b=l(d,p),k={connect:w=>{m(),f(b)},end:()=>{m(),f(b)},error:w=>{m(),b.end(),g(w)}};y===!1&&(k.close=()=>{k.error(new Error("Couldn't connect to server"))});function m(){Object.keys(k).forEach(w=>{b.off(w,k[w])})}Object.keys(k).forEach(w=>{b.on(w,k[w])})})}c.default=l}),ks=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(y,f,g,b){b===void 0&&(b=g);var k=Object.getOwnPropertyDescriptor(f,g);(!k||("get"in k?!f.__esModule:k.writable||k.configurable))&&(k={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(y,b,k)}:function(y,f,g,b){b===void 0&&(b=g),y[b]=f[g]}),t=c&&c.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),r=c&&c.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(g){var b=[];for(var k in g)Object.prototype.hasOwnProperty.call(g,k)&&(b[b.length]=k);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var b=y(f),k=0;k<b.length;k++)b[k]!=="default"&&e(g,f,b[k]);return t(g,f),g}})(),a=c&&c.__exportStar||function(y,f){for(var g in y)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,y,g)},n=c&&c.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(c,"__esModule",{value:!0}),c.ReasonCodes=c.KeepaliveManager=c.UniqueMessageIdProvider=c.DefaultMessageIdProvider=c.Store=c.MqttClient=c.connectAsync=c.connect=c.Client=void 0;var i=n(ii());c.MqttClient=i.default;var s=n(xa());c.DefaultMessageIdProvider=s.default;var o=n(wu());c.UniqueMessageIdProvider=o.default;var l=n(la());c.Store=l.default;var u=r(lh());c.connect=u.default,Object.defineProperty(c,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Ma());c.KeepaliveManager=d.default,c.Client=i.default,a(ii(),c),a(Ut(),c),a(aa(),c);var p=Lr();Object.defineProperty(c,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),ch=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(i,s,o,l){l===void 0&&(l=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,l,u)}:function(i,s,o,l){l===void 0&&(l=o),i[l]=s[o]}),t=c&&c.__setModuleDefault||(Object.create?function(i,s){Object.defineProperty(i,"default",{enumerable:!0,value:s})}:function(i,s){i.default=s}),r=c&&c.__importStar||(function(){var i=function(s){return i=Object.getOwnPropertyNames||function(o){var l=[];for(var u in o)Object.prototype.hasOwnProperty.call(o,u)&&(l[l.length]=u);return l},i(s)};return function(s){if(s&&s.__esModule)return s;var o={};if(s!=null)for(var l=i(s),u=0;u<l.length;u++)l[u]!=="default"&&e(o,s,l[u]);return t(o,s),o}})(),a=c&&c.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(c,"__esModule",{value:!0});var n=r(ks());c.default=n,a(ks(),c)});const uh=ch();const hh={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},fh=300,dh={templateId:"7",type:"link",isDeepLink:!0},ph={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class ul{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;disposed=!1;reconnectTimer=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??`aikaara_${e.userId}_${Date.now()}`,this.topics={...hh,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??10,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0},r={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!0,reconnectPeriod:0,connectTimeout:this.config.connectTimeoutMs??1e4,keepalive:this.config.keepAliveSec??60,protocolVersion:this.config.protocolVersion??3,protocolId:this.config.protocolId??"MQIsdp"};return this.config.enablePresence!==!1&&(r.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),new Promise((a,n)=>{this.client=uh.connect(this.config.mqttEndpoint,r),this.client.on("connect",()=>{if(this.reconnectAttempt=0,this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const i=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(i),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:i})}a()}),this.client.on("message",(i,s)=>{this.dispatchInbound(i,s)}),this.client.on("close",()=>{this.debugLog("CLOSE",{}),this.notifyStateChange(!1),this.disposed||this.scheduleReconnect()}),this.client.on("error",i=>{this.debugLog("ERROR",{message:i.message}),this.reconnectAttempt===0&&n(i)}),this.client.on("packetsend",i=>{(i.cmd==="subscribe"||i.cmd==="unsubscribe"||i.cmd==="pingreq")&&this.debugLog(i.cmd.toUpperCase(),{topic:i.topic,packetId:i.messageId})})})}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[a,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[a]=`${n.slice(0,200)}…(${n.length})`:r[a]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const a=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,a)}publishFileMessage(e,t){if(!this.client)return;const r={...dh,...this.config.fileTemplate??{},...gh(t)},a={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(a),type:"html",attributes:n,metadata:a.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=fh){if(!this.client)return;const a=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(a,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed)return;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const t=[...this.subscribedTopics];this.subscribedTopics.clear(),t.forEach(r=>{this.client&&(this.client.subscribe(r,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(r))})}catch{}}},e)}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let a=null;try{a=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!a)return;this.debugLog("RECV",{topic:e,sender:a.sender,type:a.type,contentType:a.metadata?.contentType,templateId:a.metadata?.templateId,messageId:a.message_id,text:typeof a.text=="string"?a.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const l=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof a.status=="number"?a.status:Number(a.status??0),p={conversationId:l,messageId:u,status:d,raw:a};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(a,{topic:e,conversationId:l,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),s=i?.groups?.conversationId,o={topic:e,conversationId:s,messageId:typeof a.message_id=="string"?a.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(l=>l(a,o))}buildOutgoingEnvelope(e,t){const r={...ph,...this.config.messageDefaults??{}},a=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:a,senderFullname:a,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(a,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(a,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const s=i[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function gh(c){const e={};for(const[t,r]of Object.entries(c))r!==void 0&&(e[t]=r);return e}function hl(c,e){return(c.sender??"").toString()===e}function fl(c,e){const t=(c.sender??"").toString(),r=e.systemSenders??["metadata","system"],a=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(a)?"assistant":r.includes(t)?"system":"agent":"system"}function lo(c){const e={raw:c},t=c.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof c.text=="string"&&c.text.trim().startsWith("{"))try{const r=JSON.parse(c.text);typeof r.message=="string"&&(e.innerMessage=r.message);const a=r.metadata;a&&typeof a=="object"&&(!e.contentType&&typeof a.contentType=="string"&&(e.contentType=a.contentType),!e.templateId&&typeof a.templateId=="string"&&(e.templateId=a.templateId),e.payload===void 0&&a.payload!==void 0&&(e.payload=a.payload))}catch{}return e}function dl(c){const e=lo(c);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const a=r[0],n=a.action,i=n&&typeof n.url=="string"?n.url:void 0,s=typeof a.description=="string"?a.description:void 0,o=c.attributes,l=o&&typeof o.cloudFileId=="string"?o.cloudFileId:void 0;return!i&&!s?null:{fileName:s,fileUrl:i,cloudFileId:l,templateId:e.templateId}}function Ss(c,e,t){const r=fl(c,t),a=lo(c),n=dl(c);let i="";a.innerMessage?i=a.innerMessage:typeof c.text=="string"&&(c.text.trim().startsWith("{")?a.contentType!=="300"&&(i=c.text):i=c.text);const s=typeof c.message_id=="string"?c.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=typeof c.timestamp=="number"?new Date(c.timestamp).toISOString():new Date().toISOString(),l=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof c.status=="number"?mh(c.status):"delivered",d={id:s,externalId:s,conversationId:e,role:l,content:i,createdAt:o,status:u,metadata:{sender:c.sender,sender_fullname:c.sender_fullname??c.senderFullname,app_id:c.app_id,attributes:c.attributes}};return a.contentType&&(d.template={contentType:a.contentType,templateId:a.templateId,payload:a.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:a}}function mh(c){return c<0?"error":c>=250?"read":c>=150?"delivered":"sent"}class pl extends Vi{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new Os(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Ps,this.conversationManager=new Ms(e.conversationId),this.usesAikaara()&&(this.connection=new Cs(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new ul({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const a=r?"connected":"disconnected";this.emit("connection:state",a),this.config.onConnectionStateChange?.(a)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,a)=>this.handleTiledeskMessage(r,a))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),a=this.config.tiledesk?.autoInitiateOnEmpty??!0;r==="empty"&&a&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const a=r.map(s=>Ss(s,e,{userId:t}).message).sort((s,o)=>new Date(s.createdAt).getTime()-new Date(o.createdAt).getTime()),n=this.messageStore.messages,i=[...a,...n.filter(s=>!a.some(o=>o.externalId&&o.externalId===s.externalId))];if(this.messageStore.setMessages(i),this.config.onMessage)for(const s of a)try{this.config.onMessage(s)}catch(o){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",o)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",a),this.config.onMessage?.(a);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:a.fileName,fileUrl:a.url,cloudFileId:a.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const a=this.conversationManager.conversationId;if(!a)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(a,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=t.conversationId??this.conversationManager.conversationId;if(!r)return;const a=this.config.tiledeskIdentity?.userId??"",{message:n,template:i}=Ss(e,r,{userId:a,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(hl(e,a)){const l=this.messageStore.reconcileOptimistic(n);if(l){this.emit("message:updated",l);return}}const{message:s,deduped:o}=this.messageStore.upsertRemoteMessage(n);if(o?this.emit("message:updated",s):(this.emit("message:received",s),this.config.onMessage?.(s)),i.contentType){const l={messageId:s.id,conversationId:r,role:n.role==="tool"?"system":n.role,contentType:i.contentType,templateId:i.templateId,payload:i.payload,innerMessage:i.innerMessage,raw:e};this.config.onTemplateMessage?.(l)}}handleTiledeskStatusUpdate(e){e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered")}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",a=e.content||"";a?this.messageStore.updateStreaming(a):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,a=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),a&&(this.emit("stream:end",{messageId:a.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",a),this.config.onMessage?.(a));break}case"message_queued":{const r=this.messageStore.messages.findLast(a=>a.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}const Es={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",json:"application/json",zip:"application/zip"};function bh(c){const e=c.lastIndexOf(".");return e<0||e===c.length-1?"":c.slice(e+1).toLowerCase()}function yh(c,e,t){const r=c.type;if(r&&r.trim().length>0)return r;const a=bh(c.name||"");if(a){if(e&&e[a])return e[a];if(Es[a])return Es[a]}return t}function Wr(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function vh(c,e){const t=e.split(".");let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return"";return typeof r=="string"?r:""}function gl(c){const e=c.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const a=t.name||`upload-${Date.now()}`,n={fileName:a,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId},i=c.authHeader?await c.authHeader():void 0,s={accept:"application/json",...c.extraHeaders??{},...i?{authorization:i}:{}},o=Wr(c.signEndpoint.includes("{")?c.signEndpoint:`${c.signEndpoint}?fileName={fileName}`,n),l=await fetch(o,{method:c.signMethod??"GET",headers:s});if(!l.ok)throw new Error(`Sign request failed: ${l.status}`);const u=await l.json().catch(()=>({})),d=vh(u,e);if(!d)throw new Error(`Sign response missing path "${e}"`);const p=yh(t,c.contentTypeMap,c.contentTypeFallback??"application/octet-stream"),y=c.s3HostRewrite?d.replace(/^https:\/\/[^/]+/i,c.s3HostRewrite):d,f=await fetch(y,{method:"PUT",headers:{"content-type":p},body:t});if(!f.ok){const b=await f.text().catch(()=>"");throw new Error(`S3 PUT failed: ${f.status} ${b.slice(0,200)}`)}if(c.registerEndpoint){const b=JSON.parse(Wr(JSON.stringify(c.registerBody??{}),n)),k=await fetch(c.registerEndpoint,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify(b)});if(!k.ok){const m=await k.text().catch(()=>"");throw new Error(`Register failed: ${k.status} ${m.slice(0,200)}`)}}return{url:c.viewerTemplate?Wr(c.viewerTemplate,n):d.split("?")[0],fileName:a,contentType:p,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function co(c){return{async upload(e,t){const r=new FormData,a=c.fieldName??"file";r.append(a,e,e.name);const n=typeof c.extraFields=="function"?c.extraFields(t):c.extraFields;if(n)for(const[p,y]of Object.entries(n))r.append(p,y);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof c.headers=="function"?await c.headers():c.headers??{},s=await fetch(c.endpoint,{method:c.method??"POST",body:r,headers:i,credentials:c.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const o=await s.json().catch(()=>({}));if(c.parseResponse)return c.parseResponse(o,t);const l=o,u=l.url??l.fileUrl??l.publicUrl,d=l.fileName??l.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof l.cloudFileId=="string"?l.cloudFileId:void 0,relativePath:typeof l.path=="string"?l.path:void 0,contentType:typeof l.contentType=="string"?l.contentType:void 0,byteSize:typeof l.byteSize=="number"?l.byteSize:void 0,meta:l}}}}const wh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function ml(c){const e=c.apiBase.replace(/\/$/,""),t=c.pageSize??200,r=c.pathTemplate??wh;return{async fetchMessages(a,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(a)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),s=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,o={accept:"application/json","content-type":"application/json",...c.extraHeaders??{}};if(c.getToken){const p=await c.getToken();p&&(o.authorization=p)}const l=await fetch(s,{method:"GET",headers:o}),u=await l.json().catch(()=>null);if(c.parseResponse&&u)return c.parseResponse(u);const d=u;if(d&&Array.isArray(d.result))return d.result;if(!l.ok)throw new Error(`History fetch failed: ${l.status} ${l.statusText}`);return[]}}}class _h{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;constructor(e,t,r){this.client=new pl(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e)}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.client.config.templateActionAttributes??{},a=t.attributes?.action??{},n={...t.attributes,action:{...r,...a}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class bl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||tc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||ho,position:this.getAttribute("position")||this._config.position||ec,width:Number(this.getAttribute("width"))||this._config.width||Ql,height:Number(this.getAttribute("height"))||this._config.height||Jl,fontFamily:this._config.fontFamily||Zl,borderRadius:this._config.borderRadius??Xl,placeholder:this.getAttribute("placeholder")||this._config.placeholder||fo,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||rc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,a){if(typeof document>"u")return;const n=document.documentElement,i=(s,o)=>{o!==void 0&&o!==""&&n.style.setProperty(`--aikaara-${s}`,o)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??a),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=a=>typeof a=="number"?`${a}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,a])=>a!==void 0&&a!=="").map(([a,n])=>`--aikaara-${a}: ${n};`).join(`
|
|
8
|
+
`)&&(e=e.replace(rl,"%0A")),e.includes("\r")&&(e=e.replace(nl,"%0D")),e.includes(" ")&&(e=e.replace(il,"%09")),r.pathname=e,r}var Wa,_r,Bi,kr,Sr,Di,Er,Fi,xr,$i,Ar,Wi,Ir,qi,Tr,Hi,mt,zi,Fe,bs,qa,Ha,za,Ka,Va,Ga,Ya,Qa,Ja,Xa,Or,Za,el,tl,rl,nl,il,oh=He(()=>{le(),ue(),ce(),ku(),Bu(),Qu(),Ua(),Wa=Object.freeze(Object.create(null)),_r={},Bi=!1,kr=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Sr={},Di=!1,Er={},Fi=!1,xr={},$i=!1,Ar={},Wi=!1,Ir={},qi=!1,Tr={},Hi=!1,mt={},zi=!1,Fe=rh(),Fe.parse,Fe.resolve,Fe.resolveObject,Fe.format,Fe.Url,bs=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,Fe.URL=typeof URL<"u"?URL:null,Fe.pathToFileURL=$a,Fe.fileURLToPath=Fa,qa=Fe.Url,Ha=Fe.format,za=Fe.resolve,Ka=Fe.resolveObject,Va=Fe.parse,Ga=Fe.URL,Ya=92,Qa=47,Ja=97,Xa=122,Or=bs==="win32",Za=/\//g,el=/%/g,tl=/\\/g,rl=/\n/g,nl=/\r/g,il=/\t/g}),sh=pe((c,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),so=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.BufferedDuplex=void 0,c.writev=r;var e=It(),t=(Ne(),Oe(Le));function r(n,i){let s=new Array(n.length);for(let o=0;o<n.length;o++)typeof n[o].chunk=="string"?s[o]=t.Buffer.from(n[o].chunk,"utf8"):s[o]=n[o].chunk;this._write(t.Buffer.concat(s),"binary",i)}var a=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,s){super({objectMode:!0}),this.proxy=i,this.socket=s,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",o=>{!this.destroyed&&this.readable&&this.push(o)})}_read(n){this.proxy.read(n)}_write(n,i,s){this.isSocketOpen?this.writeToProxy(n,i,s):this.writeQueue.push({chunk:n,encoding:i,cb:s})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,s){this.proxy.write(n,i)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:s}=this.writeQueue.shift();this.writeToProxy(n,i,s)}}};c.BufferedDuplex=a}),tr=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(k){return k&&k.__esModule?k:{default:k}};Object.defineProperty(c,"__esModule",{value:!0}),c.streamBuilder=c.browserStreamBuilder=void 0;var t=(Ne(),Oe(Le)),r=e(sh()),a=e(lt()),n=It(),i=e(Ur()),s=so(),o=(0,a.default)("mqttjs:ws"),l=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(k,m){let w=`${k.protocol}://${k.hostname}:${k.port}${k.path}`;return typeof k.transformWsUrl=="function"&&(w=k.transformWsUrl(w,k,m)),w}function d(k){let m=k;return k.port||(k.protocol==="wss"?m.port=443:m.port=80),k.path||(m.path="/"),k.wsOptions||(m.wsOptions={}),!i.default&&!k.forceNativeWebSocket&&k.protocol==="wss"&&l.forEach(w=>{Object.prototype.hasOwnProperty.call(k,w)&&!Object.prototype.hasOwnProperty.call(k.wsOptions,w)&&(m.wsOptions[w]=k[w])}),m}function p(k){let m=d(k);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let w=new URL(document.URL);m.hostname=w.hostname,m.port||(m.port=Number(w.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function y(k,m,w){o("createWebSocket"),o(`protocol: ${w.protocolId} ${w.protocolVersion}`);let E=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";o(`creating new Websocket for url: ${m} and protocol: ${E}`);let v;return w.createWebsocket?v=w.createWebsocket(m,[E],w):v=new r.default(m,[E],w.wsOptions),v}function f(k,m){let w=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",E=u(m,k),v;return m.createWebsocket?v=m.createWebsocket(E,[w],m):v=new WebSocket(E,[w]),v.binaryType="arraybuffer",v}var g=(k,m)=>{o("streamBuilder");let w=d(m);w.hostname=w.hostname||w.host||"localhost";let E=u(w,k),v=y(k,E,w),x=r.default.createWebSocketStream(v,w.wsOptions);return x.url=E,v.on("close",()=>{x.destroy()}),x};c.streamBuilder=g;var b=(k,m)=>{o("browserStreamBuilder");let w,E=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,x=!m.objectMode,S=f(k,m),I=O(m,N,ae);m.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{S.close()});let M=typeof S.addEventListener<"u";S.readyState===S.OPEN?(w=I,w.socket=S):(w=new s.BufferedDuplex(m,I,S),M?S.addEventListener("open",B):S.onopen=B),M?(S.addEventListener("close",T),S.addEventListener("error",W),S.addEventListener("message",D)):(S.onclose=T,S.onerror=W,S.onmessage=D);function O(Y,K,re){let F=new n.Transform({objectMode:Y.objectMode});return F._write=K,F._flush=re,F}function B(){o("WebSocket onOpen"),w instanceof s.BufferedDuplex&&w.socketReady()}function T(Y){o("WebSocket onClose",Y),w.end(),w.destroy()}function W(Y){o("WebSocket onError",Y);let K=new Error("WebSocket error");K.event=Y,w.destroy(K)}async function D(Y){if(!I||!I.readable||!I.writable)return;let{data:K}=Y;K instanceof ArrayBuffer?K=t.Buffer.from(K):K instanceof Blob?K=t.Buffer.from(await new Response(K).arrayBuffer()):K=t.Buffer.from(K,"utf8"),I.push(K)}function N(Y,K,re){if(S.bufferedAmount>E){setTimeout(N,v,Y,K,re);return}x&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch(F){return re(F)}re()}function ae(Y){S.close(),Y()}return w};c.browserStreamBuilder=b}),ao={};Lt(ao,{Server:()=>Me,Socket:()=>Me,Stream:()=>Me,_createServerHandle:()=>Me,_normalizeArgs:()=>Me,_setSimultaneousAccepts:()=>Me,connect:()=>Me,createConnection:()=>Me,createServer:()=>Me,default:()=>ol,isIP:()=>Me,isIPv4:()=>Me,isIPv6:()=>Me});function Me(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var ol,sl=He(()=>{le(),ue(),ce(),ol={_createServerHandle:Me,_normalizeArgs:Me,_setSimultaneousAccepts:Me,connect:Me,createConnection:Me,createServer:Me,isIP:Me,isIPv4:Me,isIPv6:Me,Server:Me,Socket:Me,Stream:Me}}),al=pe((c,e)=>{le(),ue(),ce(),e.exports={}}),ys=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(c,"__esModule",{value:!0});var t=e((sl(),Oe(ao))),r=e(lt()),a=e(al()),n=(0,r.default)("mqttjs:tcp"),i=(s,o)=>{if(o.port=o.port||1883,o.hostname=o.hostname||o.host||"localhost",o.socksProxy)return(0,a.default)(o.hostname,o.port,o.socksProxy,{timeout:o.socksTimeout});let{port:l,path:u}=o,d=o.hostname;return n("port %d and host %s",l,d),t.default.createConnection({port:l,host:d,path:u})};c.default=i}),ll={};Lt(ll,{default:()=>cl});var cl,ah=He(()=>{le(),ue(),ce(),cl={}}),vs=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(c,"__esModule",{value:!0});var t=(ah(),Oe(ll)),r=e((sl(),Oe(ao))),a=e(lt()),n=e(al()),i=(0,a.default)("mqttjs:tls");function s(l){let{host:u,port:d,socksProxy:p,...y}=l;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:l.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(l)}var o=(l,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=s(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(y){u.rejectUnauthorized&&l.emit("error",y),d.end()}return d.on("error",p),d};c.default=o}),ws=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ne(),Oe(Le)),t=It(),r=so(),a,n,i;function s(){let p=new t.Transform;return p._write=(y,f,g)=>{a.send({data:y.buffer,success(){g()},fail(b){g(new Error(b))}})},p._flush=y=>{a.close({success(){y()}})},p}function o(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function l(p,y){let f=p.protocol==="wxs"?"wss":"ws",g=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,y)),g}function u(){a.onOpen(()=>{i.socketReady()}),a.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),n.push(y)}),a.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),a.onError(p=>{let y=new Error(p.errMsg);i.destroy(y)})}var d=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";o(y);let g=l(y,p);a=wx.connectSocket({url:g,protocols:[f]}),n=s(),i=new r.BufferedDuplex(y,n,a),i._destroy=(k,m)=>{a.close({success(){m&&m(k)}})};let b=i.destroy;return i.destroy=(k,m)=>(i.destroy=b,setTimeout(()=>{a.close({fail(){i._destroy(k,m)}})},0),i),u(),i};c.default=d}),_s=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ne(),Oe(Le)),t=It(),r=so(),a,n,i,s=!1;function o(){let y=new t.Transform;return y._write=(f,g,b)=>{a.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{a.closeSocket({success(){f()}})},y}function l(y){y.hostname||(y.hostname="localhost"),y.path||(y.path="/"),y.wsOptions||(y.wsOptions={})}function u(y,f){let g=y.protocol==="alis"?"wss":"ws",b=`${g}://${y.hostname}${y.path}`;return y.port&&y.port!==80&&y.port!==443&&(b=`${g}://${y.hostname}:${y.port}${y.path}`),typeof y.transformWsUrl=="function"&&(b=y.transformWsUrl(b,y,f)),b}function d(){s||(s=!0,a.onSocketOpen(()=>{i.socketReady()}),a.onSocketMessage(y=>{if(typeof y.data=="string"){let f=e.Buffer.from(y.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(y.data)}}),a.onSocketClose(()=>{i.end(),i.destroy()}),a.onSocketError(y=>{i.destroy(y)}))}var p=(y,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let g=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";l(f);let b=u(f,y);return a=f.my,a.connectSocket({url:b,protocols:g}),n=o(),i=new r.BufferedDuplex(f,n,a),d(),i};c.default=p}),lh=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(c,"__esModule",{value:!0}),c.connectAsync=u;var t=e(lt()),r=e((oh(),Oe(Ba))),a=e(ii()),n=e(Ur());typeof Pe?.nextTick!="function"&&(Pe.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),s=null;function o(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;d.username=y,d.password=f}else d.username=d.auth}function l(d,p){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let g=r.default.parse(d,!0),b={};if(g.port!=null&&(b.port=Number(g.port)),b.host=g.hostname,b.query=g.query,b.auth=g.auth,b.protocol=g.protocol,b.path=g.path,p={...b,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,o(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Pe<"u"&&(p.socksProxy=Pe.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=tr().streamBuilder,s.wss=tr().streamBuilder,s.mqtt=ys().default,s.tcp=ys().default,s.ssl=vs().default,s.tls=s.ssl,s.mqtts=vs().default):(s.ws=tr().browserStreamBuilder,s.wss=tr().browserStreamBuilder,s.wx=ws().default,s.wxs=ws().default,s.ali=_s().default,s.alis=_s().default)),!s[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,k)=>g&&k%2===0?!1:typeof s[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function y(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),s[p.protocol](g,p)}let f=new a.default(y,p);return f.on("error",()=>{}),f}function u(d,p,y=!0){return new Promise((f,g)=>{let b=l(d,p),k={connect:w=>{m(),f(b)},end:()=>{m(),f(b)},error:w=>{m(),b.end(),g(w)}};y===!1&&(k.close=()=>{k.error(new Error("Couldn't connect to server"))});function m(){Object.keys(k).forEach(w=>{b.off(w,k[w])})}Object.keys(k).forEach(w=>{b.on(w,k[w])})})}c.default=l}),ks=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(y,f,g,b){b===void 0&&(b=g);var k=Object.getOwnPropertyDescriptor(f,g);(!k||("get"in k?!f.__esModule:k.writable||k.configurable))&&(k={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(y,b,k)}:function(y,f,g,b){b===void 0&&(b=g),y[b]=f[g]}),t=c&&c.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),r=c&&c.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(g){var b=[];for(var k in g)Object.prototype.hasOwnProperty.call(g,k)&&(b[b.length]=k);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var b=y(f),k=0;k<b.length;k++)b[k]!=="default"&&e(g,f,b[k]);return t(g,f),g}})(),a=c&&c.__exportStar||function(y,f){for(var g in y)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,y,g)},n=c&&c.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(c,"__esModule",{value:!0}),c.ReasonCodes=c.KeepaliveManager=c.UniqueMessageIdProvider=c.DefaultMessageIdProvider=c.Store=c.MqttClient=c.connectAsync=c.connect=c.Client=void 0;var i=n(ii());c.MqttClient=i.default;var s=n(xa());c.DefaultMessageIdProvider=s.default;var o=n(wu());c.UniqueMessageIdProvider=o.default;var l=n(la());c.Store=l.default;var u=r(lh());c.connect=u.default,Object.defineProperty(c,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(Ma());c.KeepaliveManager=d.default,c.Client=i.default,a(ii(),c),a(Ut(),c),a(aa(),c);var p=Lr();Object.defineProperty(c,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),ch=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(i,s,o,l){l===void 0&&(l=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,l,u)}:function(i,s,o,l){l===void 0&&(l=o),i[l]=s[o]}),t=c&&c.__setModuleDefault||(Object.create?function(i,s){Object.defineProperty(i,"default",{enumerable:!0,value:s})}:function(i,s){i.default=s}),r=c&&c.__importStar||(function(){var i=function(s){return i=Object.getOwnPropertyNames||function(o){var l=[];for(var u in o)Object.prototype.hasOwnProperty.call(o,u)&&(l[l.length]=u);return l},i(s)};return function(s){if(s&&s.__esModule)return s;var o={};if(s!=null)for(var l=i(s),u=0;u<l.length;u++)l[u]!=="default"&&e(o,s,l[u]);return t(o,s),o}})(),a=c&&c.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(c,"__esModule",{value:!0});var n=r(ks());c.default=n,a(ks(),c)});const uh=ch();const hh={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},fh=300,dh={templateId:"7",type:"link",isDeepLink:!0},ph={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class ul{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;disposed=!1;reconnectTimer=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??`aikaara_${e.userId}_${Date.now()}`,this.topics={...hh,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??10,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0},r={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!0,reconnectPeriod:0,connectTimeout:this.config.connectTimeoutMs??1e4,keepalive:this.config.keepAliveSec??60,protocolVersion:this.config.protocolVersion??3,protocolId:this.config.protocolId??"MQIsdp"};return this.config.enablePresence!==!1&&(r.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),new Promise((a,n)=>{this.client=uh.connect(this.config.mqttEndpoint,r),this.client.on("connect",()=>{if(this.reconnectAttempt=0,this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const i=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(i),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:i})}a()}),this.client.on("message",(i,s)=>{this.dispatchInbound(i,s)}),this.client.on("close",()=>{this.debugLog("CLOSE",{}),this.notifyStateChange(!1),this.disposed||this.scheduleReconnect()}),this.client.on("error",i=>{this.debugLog("ERROR",{message:i.message}),this.reconnectAttempt===0&&n(i)}),this.client.on("packetsend",i=>{(i.cmd==="subscribe"||i.cmd==="unsubscribe"||i.cmd==="pingreq")&&this.debugLog(i.cmd.toUpperCase(),{topic:i.topic,packetId:i.messageId})})})}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[a,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[a]=`${n.slice(0,200)}…(${n.length})`:r[a]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const a=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,a)}publishFileMessage(e,t){if(!this.client)return;const r={...dh,...this.config.fileTemplate??{},...gh(t)},a={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(a),type:"html",attributes:n,metadata:a.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=fh){if(!this.client)return;const a=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(a,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed)return;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const t=[...this.subscribedTopics];this.subscribedTopics.clear(),t.forEach(r=>{this.client&&(this.client.subscribe(r,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(r))})}catch{}}},e)}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let a=null;try{a=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!a)return;this.debugLog("RECV",{topic:e,sender:a.sender,type:a.type,contentType:a.metadata?.contentType,templateId:a.metadata?.templateId,messageId:a.message_id,text:typeof a.text=="string"?a.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const l=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof a.status=="number"?a.status:Number(a.status??0),p={conversationId:l,messageId:u,status:d,raw:a};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(a,{topic:e,conversationId:l,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),s=i?.groups?.conversationId,o={topic:e,conversationId:s,messageId:typeof a.message_id=="string"?a.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(l=>l(a,o))}buildOutgoingEnvelope(e,t){const r={...ph,...this.config.messageDefaults??{}},a=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:a,senderFullname:a,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(a,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(a,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const s=i[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function gh(c){const e={};for(const[t,r]of Object.entries(c))r!==void 0&&(e[t]=r);return e}function hl(c,e){return(c.sender??"").toString()===e}function fl(c,e){const t=(c.sender??"").toString(),r=e.systemSenders??["metadata","system"],a=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(a)?"assistant":r.includes(t)?"system":"agent":"system"}function lo(c){const e={raw:c},t=c.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof c.text=="string"&&c.text.trim().startsWith("{"))try{const r=JSON.parse(c.text);typeof r.message=="string"&&(e.innerMessage=r.message);const a=r.metadata;a&&typeof a=="object"&&(!e.contentType&&typeof a.contentType=="string"&&(e.contentType=a.contentType),!e.templateId&&typeof a.templateId=="string"&&(e.templateId=a.templateId),e.payload===void 0&&a.payload!==void 0&&(e.payload=a.payload))}catch{}return e}function dl(c){const e=lo(c);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const a=r[0],n=a.action,i=n&&typeof n.url=="string"?n.url:void 0,s=typeof a.description=="string"?a.description:void 0,o=c.attributes,l=o&&typeof o.cloudFileId=="string"?o.cloudFileId:void 0;return!i&&!s?null:{fileName:s,fileUrl:i,cloudFileId:l,templateId:e.templateId}}function Ss(c,e,t){const r=fl(c,t),a=lo(c),n=dl(c);let i="";a.innerMessage?i=a.innerMessage:typeof c.text=="string"&&(c.text.trim().startsWith("{")?a.contentType!=="300"&&(i=c.text):i=c.text);const s=typeof c.message_id=="string"?c.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=typeof c.timestamp=="number"?new Date(c.timestamp).toISOString():new Date().toISOString(),l=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof c.status=="number"?mh(c.status):"delivered",d={id:s,externalId:s,conversationId:e,role:l,content:i,createdAt:o,status:u,metadata:{sender:c.sender,sender_fullname:c.sender_fullname??c.senderFullname,app_id:c.app_id,attributes:c.attributes}};return a.contentType&&(d.template={contentType:a.contentType,templateId:a.templateId,payload:a.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:a}}function mh(c){return c<0?"error":c>=250?"read":c>=150?"delivered":"sent"}class pl extends Vi{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new Os(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new Ps,this.conversationManager=new Ms(e.conversationId),this.usesAikaara()&&(this.connection=new Cs(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new ul({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const a=r?"connected":"disconnected";this.emit("connection:state",a),this.config.onConnectionStateChange?.(a)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,a)=>this.handleTiledeskMessage(r,a))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),a=this.config.tiledesk?.autoInitiateOnEmpty??!0;r==="empty"&&a&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const a=r.map(s=>Ss(s,e,{userId:t}).message).sort((s,o)=>new Date(s.createdAt).getTime()-new Date(o.createdAt).getTime()),n=this.messageStore.messages,i=[...a,...n.filter(s=>!a.some(o=>o.externalId&&o.externalId===s.externalId))];if(this.messageStore.setMessages(i),this.config.onMessage)for(const s of a)try{this.config.onMessage(s)}catch(o){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",o)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",a),this.config.onMessage?.(a);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:a.fileName,fileUrl:a.url,cloudFileId:a.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const a=this.conversationManager.conversationId;if(!a)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(a,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=t.conversationId??this.conversationManager.conversationId;if(!r)return;const a=this.config.tiledeskIdentity?.userId??"",{message:n,template:i}=Ss(e,r,{userId:a,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(hl(e,a)){const l=this.messageStore.reconcileOptimistic(n);if(l){this.emit("message:updated",l);return}}const{message:s,deduped:o}=this.messageStore.upsertRemoteMessage(n);if(o?this.emit("message:updated",s):(this.emit("message:received",s),this.config.onMessage?.(s)),i.contentType){const l={messageId:s.id,conversationId:r,role:n.role==="tool"?"system":n.role,contentType:i.contentType,templateId:i.templateId,payload:i.payload,innerMessage:i.innerMessage,raw:e};this.config.onTemplateMessage?.(l)}}handleTiledeskStatusUpdate(e){e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered")}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",a=e.content||"";a?this.messageStore.updateStreaming(a):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,a=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),a&&(this.emit("stream:end",{messageId:a.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",a),this.config.onMessage?.(a));break}case"message_queued":{const r=this.messageStore.messages.findLast(a=>a.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}const Es={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function bh(c){const e=c.lastIndexOf(".");return e<0||e===c.length-1?"":c.slice(e+1).toLowerCase()}function yh(c,e,t){const r=bh(c.name||"");if(r&&e&&e[r])return e[r];const a=c.type;return a&&a.trim().length>0?a:r&&Es[r]?Es[r]:t}function Wr(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function vh(c,e){const t=e.split(".");let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return"";return typeof r=="string"?r:""}function gl(c){const e=c.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const a=t.name||`upload-${Date.now()}`,n={fileName:a,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId},i=c.authHeader?await c.authHeader():void 0,s={accept:"application/json",...c.extraHeaders??{},...i?{authorization:i}:{}},o=Wr(c.signEndpoint.includes("{")?c.signEndpoint:`${c.signEndpoint}?fileName={fileName}`,n),l=await fetch(o,{method:c.signMethod??"GET",headers:s});if(!l.ok)throw new Error(`Sign request failed: ${l.status}`);const u=await l.json().catch(()=>({})),d=vh(u,e);if(!d)throw new Error(`Sign response missing path "${e}"`);const p=yh(t,c.contentTypeMap,c.contentTypeFallback??"application/octet-stream"),y=c.s3HostRewrite?d.replace(/^https:\/\/[^/]+/i,c.s3HostRewrite):d,f=await fetch(y,{method:"PUT",headers:{"content-type":p},body:t});if(!f.ok){const b=await f.text().catch(()=>"");throw new Error(`S3 PUT failed: ${f.status} ${b.slice(0,200)}`)}if(c.registerEndpoint){const b=JSON.parse(Wr(JSON.stringify(c.registerBody??{}),n)),k=await fetch(c.registerEndpoint,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify(b)});if(!k.ok){const m=await k.text().catch(()=>"");throw new Error(`Register failed: ${k.status} ${m.slice(0,200)}`)}}return{url:c.viewerTemplate?Wr(c.viewerTemplate,n):d.split("?")[0],fileName:a,contentType:p,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function co(c){return{async upload(e,t){const r=new FormData,a=c.fieldName??"file";r.append(a,e,e.name);const n=typeof c.extraFields=="function"?c.extraFields(t):c.extraFields;if(n)for(const[p,y]of Object.entries(n))r.append(p,y);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof c.headers=="function"?await c.headers():c.headers??{},s=await fetch(c.endpoint,{method:c.method??"POST",body:r,headers:i,credentials:c.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const o=await s.json().catch(()=>({}));if(c.parseResponse)return c.parseResponse(o,t);const l=o,u=l.url??l.fileUrl??l.publicUrl,d=l.fileName??l.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof l.cloudFileId=="string"?l.cloudFileId:void 0,relativePath:typeof l.path=="string"?l.path:void 0,contentType:typeof l.contentType=="string"?l.contentType:void 0,byteSize:typeof l.byteSize=="number"?l.byteSize:void 0,meta:l}}}}const wh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function ml(c){const e=c.apiBase.replace(/\/$/,""),t=c.pageSize??200,r=c.pathTemplate??wh;return{async fetchMessages(a,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(a)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),s=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,o={accept:"application/json","content-type":"application/json",...c.extraHeaders??{}};if(c.getToken){const p=await c.getToken();p&&(o.authorization=p)}const l=await fetch(s,{method:"GET",headers:o}),u=await l.json().catch(()=>null);if(c.parseResponse&&u)return c.parseResponse(u);const d=u;if(d&&Array.isArray(d.result))return d.result;if(!l.ok)throw new Error(`History fetch failed: ${l.status} ${l.statusText}`);return[]}}}class _h{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;constructor(e,t,r){this.client=new pl(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e)}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.client.config.templateActionAttributes??{},a=t.attributes?.action??{},n={...t.attributes,action:{...r,...a}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class bl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||tc,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||ho,position:this.getAttribute("position")||this._config.position||ec,width:Number(this.getAttribute("width"))||this._config.width||Ql,height:Number(this.getAttribute("height"))||this._config.height||Jl,fontFamily:this._config.fontFamily||Zl,borderRadius:this._config.borderRadius??Xl,placeholder:this.getAttribute("placeholder")||this._config.placeholder||fo,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||rc,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,a){if(typeof document>"u")return;const n=document.documentElement,i=(s,o)=>{o!==void 0&&o!==""&&n.style.setProperty(`--aikaara-${s}`,o)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??a),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=a=>typeof a=="number"?`${a}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,a])=>a!==void 0&&a!=="").map(([a,n])=>`--aikaara-${a}: ${n};`).join(`
|
|
9
9
|
`)}setUploadAdapter(e){this._config.uploadAdapter=e,this.controller?.getClient().setUploadAdapter(e)}setHistoryAdapter(e){this._config.historyAdapter=e}render(){const e=this.getConfig(),t=e.display==="embed";this.propagateThemeToDocument(e.themeTokens,e.primaryColor,e.borderRadius,e.fontFamily);const r=`
|
|
10
10
|
font-family: var(--aikaara-font);
|
|
11
11
|
position: fixed;
|
|
@@ -11614,25 +11614,17 @@ const _s = {
|
|
|
11614
11614
|
png: "image/png",
|
|
11615
11615
|
csv: "text/csv",
|
|
11616
11616
|
doc: "application/msword",
|
|
11617
|
-
|
|
11618
|
-
xls: "application/vnd.ms-excel",
|
|
11619
|
-
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
11620
|
-
json: "application/json",
|
|
11621
|
-
zip: "application/zip"
|
|
11617
|
+
json: "application/json"
|
|
11622
11618
|
};
|
|
11623
11619
|
function Hu(c) {
|
|
11624
11620
|
const e = c.lastIndexOf(".");
|
|
11625
11621
|
return e < 0 || e === c.length - 1 ? "" : c.slice(e + 1).toLowerCase();
|
|
11626
11622
|
}
|
|
11627
11623
|
function zu(c, e, t) {
|
|
11628
|
-
const r = c.
|
|
11629
|
-
if (r &&
|
|
11630
|
-
const a =
|
|
11631
|
-
|
|
11632
|
-
if (e && e[a]) return e[a];
|
|
11633
|
-
if (_s[a]) return _s[a];
|
|
11634
|
-
}
|
|
11635
|
-
return t;
|
|
11624
|
+
const r = Hu(c.name || "");
|
|
11625
|
+
if (r && e && e[r]) return e[r];
|
|
11626
|
+
const a = c.type;
|
|
11627
|
+
return a && a.trim().length > 0 ? a : r && _s[r] ? _s[r] : t;
|
|
11636
11628
|
}
|
|
11637
11629
|
function Wr(c, e) {
|
|
11638
11630
|
return c.replace(/\{(\w+)\}/g, (t, r) => e[r] ?? "");
|
|
@@ -5,7 +5,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
5
5
|
`+ie.prev+ie.base;return xe+I.call(z,","+xe)+`
|
|
6
6
|
`+ie.prev}function ke(z,ie){var xe=be(z),Ae=[];if(xe){Ae.length=z.length;for(var Ie=0;Ie<z.length;Ie++)Ae[Ie]=oe(z,Ie)?ie(z[Ie],z):""}var Oe=typeof T=="function"?T(z):[],Je;if(F){Je={};for(var Xe=0;Xe<Oe.length;Xe++)Je["$"+Oe[Xe]]=Oe[Xe]}for(var $e in z)oe(z,$e)&&(xe&&String(Number($e))===$e&&$e<z.length||F&&Je["$"+$e]instanceof Symbol||(x.call(/[^\w$]/,$e)?Ae.push(ie($e,z)+": "+ie(z[$e],z)):Ae.push($e+": "+ie(z[$e],z))));if(typeof T=="function")for(var Ze=0;Ze<Oe.length;Ze++)ae.call(z,Oe[Ze])&&Ae.push("["+ie(Oe[Ze])+"]: "+ie(z[Oe[Ze]],z));return Ae}return xr}function Ku(){if(Ki)return Ir;Ki=!0;var c=jt(),e=Pu(),t=zu(),r=Kt(),a=c("%WeakMap%",!0),n=c("%Map%",!0),i=e("WeakMap.prototype.get",!0),s=e("WeakMap.prototype.set",!0),o=e("WeakMap.prototype.has",!0),l=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),d=e("Map.prototype.has",!0),p=function(b,k){for(var m=b,w;(w=m.next)!==null;m=w)if(w.key===k)return m.next=w.next,w.next=b.next,b.next=w,w},y=function(b,k){var m=p(b,k);return m&&m.value},f=function(b,k,m){var w=p(b,k);w?w.value=m:b.next={key:k,next:b.next,value:m}},g=function(b,k){return!!p(b,k)};return Ir=function(){var b,k,m,w={assert:function(E){if(!w.has(E))throw new r("Side channel does not contain "+t(E))},get:function(E){if(a&&E&&(typeof E=="object"||typeof E=="function")){if(b)return i(b,E)}else if(n){if(k)return l(k,E)}else if(m)return y(m,E)},has:function(E){if(a&&E&&(typeof E=="object"||typeof E=="function")){if(b)return o(b,E)}else if(n){if(k)return d(k,E)}else if(m)return g(m,E);return!1},set:function(E,v){a&&E&&(typeof E=="object"||typeof E=="function")?(b||(b=new a),s(b,E,v)):n?(k||(k=new n),u(k,E,v)):(m||(m={key:{},next:null}),f(m,E,v))}};return w},Ir}function Hi(){if(Vi)return Tr;Vi=!0;var c=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return Tr={default:t.RFC3986,formatters:{RFC1738:function(r){return c.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},Tr}function wa(){if(Gi)return Cr;Gi=!0;var c=Hi(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r=(function(){for(var b=[],k=0;k<256;++k)b.push("%"+((k<16?"0":"")+k.toString(16)).toUpperCase());return b})(),a=function(b){for(;b.length>1;){var k=b.pop(),m=k.obj[k.prop];if(t(m)){for(var w=[],E=0;E<m.length;++E)typeof m[E]<"u"&&w.push(m[E]);k.obj[k.prop]=w}}},n=function(b,k){for(var m=k&&k.plainObjects?Object.create(null):{},w=0;w<b.length;++w)typeof b[w]<"u"&&(m[w]=b[w]);return m},i=function b(k,m,w){if(!m)return k;if(typeof m!="object"){if(t(k))k.push(m);else if(k&&typeof k=="object")(w&&(w.plainObjects||w.allowPrototypes)||!e.call(Object.prototype,m))&&(k[m]=!0);else return[k,m];return k}if(!k||typeof k!="object")return[k].concat(m);var E=k;return t(k)&&!t(m)&&(E=n(k,w)),t(k)&&t(m)?(m.forEach(function(v,x){if(e.call(k,x)){var S=k[x];S&&typeof S=="object"&&v&&typeof v=="object"?k[x]=b(S,v,w):k.push(v)}else k[x]=v}),k):Object.keys(m).reduce(function(v,x){var S=m[x];return e.call(v,x)?v[x]=b(v[x],S,w):v[x]=S,v},E)},s=function(b,k){return Object.keys(k).reduce(function(m,w){return m[w]=k[w],m},b)},o=function(b,k,m){var w=b.replace(/\+/g," ");if(m==="iso-8859-1")return w.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(w)}catch{return w}},l=1024,u=function(b,k,m,w,E){if(b.length===0)return b;var v=b;if(typeof b=="symbol"?v=Symbol.prototype.toString.call(b):typeof b!="string"&&(v=String(b)),m==="iso-8859-1")return escape(v).replace(/%u[0-9a-f]{4}/gi,function(T){return"%26%23"+parseInt(T.slice(2),16)+"%3B"});for(var x="",S=0;S<v.length;S+=l){for(var I=v.length>=l?v.slice(S,S+l):v,M=[],O=0;O<I.length;++O){var B=I.charCodeAt(O);if(B===45||B===46||B===95||B===126||B>=48&&B<=57||B>=65&&B<=90||B>=97&&B<=122||E===c.RFC1738&&(B===40||B===41)){M[M.length]=I.charAt(O);continue}if(B<128){M[M.length]=r[B];continue}if(B<2048){M[M.length]=r[192|B>>6]+r[128|B&63];continue}if(B<55296||B>=57344){M[M.length]=r[224|B>>12]+r[128|B>>6&63]+r[128|B&63];continue}O+=1,B=65536+((B&1023)<<10|I.charCodeAt(O)&1023),M[M.length]=r[240|B>>18]+r[128|B>>12&63]+r[128|B>>6&63]+r[128|B&63]}x+=M.join("")}return x},d=function(b){for(var k=[{obj:{o:b},prop:"o"}],m=[],w=0;w<k.length;++w)for(var E=k[w],v=E.obj[E.prop],x=Object.keys(v),S=0;S<x.length;++S){var I=x[S],M=v[I];typeof M=="object"&&M!==null&&m.indexOf(M)===-1&&(k.push({obj:v,prop:I}),m.push(M))}return a(k),b},p=function(b){return Object.prototype.toString.call(b)==="[object RegExp]"},y=function(b){return!b||typeof b!="object"?!1:!!(b.constructor&&b.constructor.isBuffer&&b.constructor.isBuffer(b))},f=function(b,k){return[].concat(b,k)},g=function(b,k){if(t(b)){for(var m=[],w=0;w<b.length;w+=1)m.push(k(b[w]));return m}return k(b)};return Cr={arrayToObject:n,assign:s,combine:f,compact:d,decode:o,encode:u,isBuffer:y,isRegExp:p,maybeMap:g,merge:i},Cr}function Vu(){if(Yi)return Or;Yi=!0;var c=Ku(),e=wa(),t=Hi(),r=Object.prototype.hasOwnProperty,a={brackets:function(g){return g+"[]"},comma:"comma",indices:function(g,b){return g+"["+b+"]"},repeat:function(g){return g}},n=Array.isArray,i=Array.prototype.push,s=function(g,b){i.apply(g,n(b)?b:[b])},o=Date.prototype.toISOString,l=t.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:l,formatter:t.formatters[l],indices:!1,serializeDate:function(g){return o.call(g)},skipNulls:!1,strictNullHandling:!1},d=function(g){return typeof g=="string"||typeof g=="number"||typeof g=="boolean"||typeof g=="symbol"||typeof g=="bigint"},p={},y=function g(b,k,m,w,E,v,x,S,I,M,O,B,T,W,F,N,ae,Y){for(var K=b,re=Y,D=0,Z=!1;(re=re.get(p))!==void 0&&!Z;){var P=re.get(b);if(D+=1,typeof P<"u"){if(P===D)throw new RangeError("Cyclic object value");Z=!0}typeof re.get(p)>"u"&&(D=0)}if(typeof M=="function"?K=M(k,K):K instanceof Date?K=T(K):m==="comma"&&n(K)&&(K=e.maybeMap(K,function(R){return R instanceof Date?T(R):R})),K===null){if(v)return I&&!N?I(k,u.encoder,ae,"key",W):k;K=""}if(d(K)||e.isBuffer(K)){if(I){var J=N?k:I(k,u.encoder,ae,"key",W);return[F(J)+"="+F(I(K,u.encoder,ae,"value",W))]}return[F(k)+"="+F(String(K))]}var be=[];if(typeof K>"u")return be;var te;if(m==="comma"&&n(K))N&&I&&(K=e.maybeMap(K,I)),te=[{value:K.length>0?K.join(",")||null:void 0}];else if(n(M))te=M;else{var we=Object.keys(K);te=O?we.sort(O):we}var V=S?k.replace(/\./g,"%2E"):k,L=w&&n(K)&&K.length===1?V+"[]":V;if(E&&n(K)&&K.length===0)return L+"[]";for(var ne=0;ne<te.length;++ne){var H=te[ne],G=typeof H=="object"&&typeof H.value<"u"?H.value:K[H];if(!(x&&G===null)){var Q=B&&S?H.replace(/\./g,"%2E"):H,me=n(K)?typeof m=="function"?m(L,Q):L:L+(B?"."+Q:"["+Q+"]");Y.set(b,D);var oe=c();oe.set(p,Y),s(be,g(G,me,m,w,E,v,x,S,m==="comma"&&N&&n(K)?null:I,M,O,B,T,W,F,N,ae,oe))}}return be},f=function(g){if(!g)return u;if(typeof g.allowEmptyArrays<"u"&&typeof g.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof g.encodeDotInKeys<"u"&&typeof g.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(g.encoder!==null&&typeof g.encoder<"u"&&typeof g.encoder!="function")throw new TypeError("Encoder has to be a function.");var b=g.charset||u.charset;if(typeof g.charset<"u"&&g.charset!=="utf-8"&&g.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var k=t.default;if(typeof g.format<"u"){if(!r.call(t.formatters,g.format))throw new TypeError("Unknown format option provided.");k=g.format}var m=t.formatters[k],w=u.filter;(typeof g.filter=="function"||n(g.filter))&&(w=g.filter);var E;if(g.arrayFormat in a?E=g.arrayFormat:"indices"in g?E=g.indices?"indices":"repeat":E=u.arrayFormat,"commaRoundTrip"in g&&typeof g.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var v=typeof g.allowDots>"u"?g.encodeDotInKeys===!0?!0:u.allowDots:!!g.allowDots;return{addQueryPrefix:typeof g.addQueryPrefix=="boolean"?g.addQueryPrefix:u.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof g.allowEmptyArrays=="boolean"?!!g.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:E,charset:b,charsetSentinel:typeof g.charsetSentinel=="boolean"?g.charsetSentinel:u.charsetSentinel,commaRoundTrip:g.commaRoundTrip,delimiter:typeof g.delimiter>"u"?u.delimiter:g.delimiter,encode:typeof g.encode=="boolean"?g.encode:u.encode,encodeDotInKeys:typeof g.encodeDotInKeys=="boolean"?g.encodeDotInKeys:u.encodeDotInKeys,encoder:typeof g.encoder=="function"?g.encoder:u.encoder,encodeValuesOnly:typeof g.encodeValuesOnly=="boolean"?g.encodeValuesOnly:u.encodeValuesOnly,filter:w,format:k,formatter:m,serializeDate:typeof g.serializeDate=="function"?g.serializeDate:u.serializeDate,skipNulls:typeof g.skipNulls=="boolean"?g.skipNulls:u.skipNulls,sort:typeof g.sort=="function"?g.sort:null,strictNullHandling:typeof g.strictNullHandling=="boolean"?g.strictNullHandling:u.strictNullHandling}};return Or=function(g,b){var k=g,m=f(b),w,E;typeof m.filter=="function"?(E=m.filter,k=E("",k)):n(m.filter)&&(E=m.filter,w=E);var v=[];if(typeof k!="object"||k===null)return"";var x=a[m.arrayFormat],S=x==="comma"&&m.commaRoundTrip;w||(w=Object.keys(k)),m.sort&&w.sort(m.sort);for(var I=c(),M=0;M<w.length;++M){var O=w[M];m.skipNulls&&k[O]===null||s(v,y(k[O],O,x,S,m.allowEmptyArrays,m.strictNullHandling,m.skipNulls,m.encodeDotInKeys,m.encode?m.encoder:null,m.filter,m.sort,m.allowDots,m.serializeDate,m.format,m.formatter,m.encodeValuesOnly,m.charset,I))}var B=v.join(m.delimiter),T=m.addQueryPrefix===!0?"?":"";return m.charsetSentinel&&(m.charset==="iso-8859-1"?T+="utf8=%26%2310003%3B&":T+="utf8=%E2%9C%93&"),B.length>0?T+B:""},Or}function Gu(){if(Qi)return Pr;Qi=!0;var c=wa(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:c.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1},a=function(p){return p.replace(/&#(\d+);/g,function(y,f){return String.fromCharCode(parseInt(f,10))})},n=function(p,y){return p&&typeof p=="string"&&y.comma&&p.indexOf(",")>-1?p.split(","):p},i="utf8=%26%2310003%3B",s="utf8=%E2%9C%93",o=function(p,y){var f={__proto__:null},g=y.ignoreQueryPrefix?p.replace(/^\?/,""):p;g=g.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var b=y.parameterLimit===1/0?void 0:y.parameterLimit,k=g.split(y.delimiter,b),m=-1,w,E=y.charset;if(y.charsetSentinel)for(w=0;w<k.length;++w)k[w].indexOf("utf8=")===0&&(k[w]===s?E="utf-8":k[w]===i&&(E="iso-8859-1"),m=w,w=k.length);for(w=0;w<k.length;++w)if(w!==m){var v=k[w],x=v.indexOf("]="),S=x===-1?v.indexOf("="):x+1,I,M;S===-1?(I=y.decoder(v,r.decoder,E,"key"),M=y.strictNullHandling?null:""):(I=y.decoder(v.slice(0,S),r.decoder,E,"key"),M=c.maybeMap(n(v.slice(S+1),y),function(B){return y.decoder(B,r.decoder,E,"value")})),M&&y.interpretNumericEntities&&E==="iso-8859-1"&&(M=a(M)),v.indexOf("[]=")>-1&&(M=t(M)?[M]:M);var O=e.call(f,I);O&&y.duplicates==="combine"?f[I]=c.combine(f[I],M):(!O||y.duplicates==="last")&&(f[I]=M)}return f},l=function(p,y,f,g){for(var b=g?y:n(y,f),k=p.length-1;k>=0;--k){var m,w=p[k];if(w==="[]"&&f.parseArrays)m=f.allowEmptyArrays&&(b===""||f.strictNullHandling&&b===null)?[]:[].concat(b);else{m=f.plainObjects?Object.create(null):{};var E=w.charAt(0)==="["&&w.charAt(w.length-1)==="]"?w.slice(1,-1):w,v=f.decodeDotInKeys?E.replace(/%2E/g,"."):E,x=parseInt(v,10);!f.parseArrays&&v===""?m={0:b}:!isNaN(x)&&w!==v&&String(x)===v&&x>=0&&f.parseArrays&&x<=f.arrayLimit?(m=[],m[x]=b):v!=="__proto__"&&(m[v]=b)}b=m}return b},u=function(p,y,f,g){if(p){var b=f.allowDots?p.replace(/\.([^.[]+)/g,"[$1]"):p,k=/(\[[^[\]]*])/,m=/(\[[^[\]]*])/g,w=f.depth>0&&k.exec(b),E=w?b.slice(0,w.index):b,v=[];if(E){if(!f.plainObjects&&e.call(Object.prototype,E)&&!f.allowPrototypes)return;v.push(E)}for(var x=0;f.depth>0&&(w=m.exec(b))!==null&&x<f.depth;){if(x+=1,!f.plainObjects&&e.call(Object.prototype,w[1].slice(1,-1))&&!f.allowPrototypes)return;v.push(w[1])}if(w){if(f.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+f.depth+" and strictDepth is true");v.push("["+b.slice(w.index)+"]")}return l(v,y,f,g)}},d=function(p){if(!p)return r;if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.decodeDotInKeys<"u"&&typeof p.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(p.decoder!==null&&typeof p.decoder<"u"&&typeof p.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var y=typeof p.charset>"u"?r.charset:p.charset,f=typeof p.duplicates>"u"?r.duplicates:p.duplicates;if(f!=="combine"&&f!=="first"&&f!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var g=typeof p.allowDots>"u"?p.decodeDotInKeys===!0?!0:r.allowDots:!!p.allowDots;return{allowDots:g,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof p.allowPrototypes=="boolean"?p.allowPrototypes:r.allowPrototypes,allowSparse:typeof p.allowSparse=="boolean"?p.allowSparse:r.allowSparse,arrayLimit:typeof p.arrayLimit=="number"?p.arrayLimit:r.arrayLimit,charset:y,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:r.charsetSentinel,comma:typeof p.comma=="boolean"?p.comma:r.comma,decodeDotInKeys:typeof p.decodeDotInKeys=="boolean"?p.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof p.decoder=="function"?p.decoder:r.decoder,delimiter:typeof p.delimiter=="string"||c.isRegExp(p.delimiter)?p.delimiter:r.delimiter,depth:typeof p.depth=="number"||p.depth===!1?+p.depth:r.depth,duplicates:f,ignoreQueryPrefix:p.ignoreQueryPrefix===!0,interpretNumericEntities:typeof p.interpretNumericEntities=="boolean"?p.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof p.parameterLimit=="number"?p.parameterLimit:r.parameterLimit,parseArrays:p.parseArrays!==!1,plainObjects:typeof p.plainObjects=="boolean"?p.plainObjects:r.plainObjects,strictDepth:typeof p.strictDepth=="boolean"?!!p.strictDepth:r.strictDepth,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:r.strictNullHandling}};return Pr=function(p,y){var f=d(y);if(p===""||p===null||typeof p>"u")return f.plainObjects?Object.create(null):{};for(var g=typeof p=="string"?o(p,f):p,b=f.plainObjects?Object.create(null):{},k=Object.keys(g),m=0;m<k.length;++m){var w=k[m],E=u(w,g[w],f,typeof p=="string");b=c.merge(b,E,f)}return f.allowSparse===!0?b:c.compact(b)},Pr}function Yu(){if(Ji)return Mr;Ji=!0;var c=Vu(),e=Gu(),t=Hi();return Mr={formats:t,parse:e,stringify:c},Mr}function Qu(){if(Xi)return yt;Xi=!0;var c=mt;function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var t=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,a=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["<",">",'"',"`"," ","\r",`
|
|
7
7
|
`," "],i=["{","}","|","\\","^","`"].concat(n),s=["'"].concat(i),o=["%","/","?",";","#"].concat(s),l=["/","?","#"],u=255,d=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,y={javascript:!0,"javascript:":!0},f={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=Yu();function k(v,x,S){if(v&&typeof v=="object"&&v instanceof e)return v;var I=new e;return I.parse(v,x,S),I}e.prototype.parse=function(v,x,S){if(typeof v!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof v);var I=v.indexOf("?"),M=I!==-1&&I<v.indexOf("#")?"?":"#",O=v.split(M),B=/\\/g;O[0]=O[0].replace(B,"/"),v=O.join(M);var T=v;if(T=T.trim(),!S&&v.split("#").length===1){var W=a.exec(T);if(W)return this.path=T,this.href=T,this.pathname=W[1],W[2]?(this.search=W[2],x?this.query=b.parse(this.search.substr(1)):this.query=this.search.substr(1)):x&&(this.search="",this.query={}),this}var F=t.exec(T);if(F){F=F[0];var N=F.toLowerCase();this.protocol=N,T=T.substr(F.length)}if(S||F||T.match(/^\/\/[^@/]+@[^@/]+/)){var ae=T.substr(0,2)==="//";ae&&!(F&&f[F])&&(T=T.substr(2),this.slashes=!0)}if(!f[F]&&(ae||F&&!g[F])){for(var Y=-1,K=0;K<l.length;K++){var re=T.indexOf(l[K]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}var D,Z;Y===-1?Z=T.lastIndexOf("@"):Z=T.lastIndexOf("@",Y),Z!==-1&&(D=T.slice(0,Z),T=T.slice(Z+1),this.auth=decodeURIComponent(D)),Y=-1;for(var K=0;K<o.length;K++){var re=T.indexOf(o[K]);re!==-1&&(Y===-1||re<Y)&&(Y=re)}Y===-1&&(Y=T.length),this.host=T.slice(0,Y),T=T.slice(Y),this.parseHost(),this.hostname=this.hostname||"";var P=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!P)for(var J=this.hostname.split(/\./),K=0,be=J.length;K<be;K++){var te=J[K];if(te&&!te.match(d)){for(var we="",V=0,L=te.length;V<L;V++)te.charCodeAt(V)>127?we+="x":we+=te[V];if(!we.match(d)){var ne=J.slice(0,K),H=J.slice(K+1),G=te.match(p);G&&(ne.push(G[1]),H.unshift(G[2])),H.length&&(T="/"+H.join(".")+T),this.hostname=ne.join(".");break}}}this.hostname.length>u?this.hostname="":this.hostname=this.hostname.toLowerCase(),P||(this.hostname=c.toASCII(this.hostname));var Q=this.port?":"+this.port:"",me=this.hostname||"";this.host=me+Q,this.href+=this.host,P&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),T[0]!=="/"&&(T="/"+T))}if(!y[N])for(var K=0,be=s.length;K<be;K++){var oe=s[K];if(T.indexOf(oe)!==-1){var R=encodeURIComponent(oe);R===oe&&(R=escape(oe)),T=T.split(oe).join(R)}}var $=T.indexOf("#");$!==-1&&(this.hash=T.substr($),T=T.slice(0,$));var ee=T.indexOf("?");if(ee!==-1?(this.search=T.substr(ee),this.query=T.substr(ee+1),x&&(this.query=b.parse(this.query)),T=T.slice(0,ee)):x&&(this.search="",this.query={}),T&&(this.pathname=T),g[N]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var Q=this.pathname||"",fe=this.search||"";this.path=Q+fe}return this.href=this.format(),this};function m(v){return typeof v=="string"&&(v=k(v)),v instanceof e?v.format():e.prototype.format.call(v)}e.prototype.format=function(){var v=this.auth||"";v&&(v=encodeURIComponent(v),v=v.replace(/%3A/i,":"),v+="@");var x=this.protocol||"",S=this.pathname||"",I=this.hash||"",M=!1,O="";this.host?M=v+this.host:this.hostname&&(M=v+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(M+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&(O=b.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var B=this.search||O&&"?"+O||"";return x&&x.substr(-1)!==":"&&(x+=":"),this.slashes||(!x||g[x])&&M!==!1?(M="//"+(M||""),S&&S.charAt(0)!=="/"&&(S="/"+S)):M||(M=""),I&&I.charAt(0)!=="#"&&(I="#"+I),B&&B.charAt(0)!=="?"&&(B="?"+B),S=S.replace(/[?#]/g,function(T){return encodeURIComponent(T)}),B=B.replace("#","%23"),x+M+S+B+I};function w(v,x){return k(v,!1,!0).resolve(x)}e.prototype.resolve=function(v){return this.resolveObject(k(v,!1,!0)).format()};function E(v,x){return v?k(v,!1,!0).resolveObject(x):x}return e.prototype.resolveObject=function(v){if(typeof v=="string"){var x=new e;x.parse(v,!1,!0),v=x}for(var S=new e,I=Object.keys(this),M=0;M<I.length;M++){var O=I[M];S[O]=this[O]}if(S.hash=v.hash,v.href==="")return S.href=S.format(),S;if(v.slashes&&!v.protocol){for(var B=Object.keys(v),T=0;T<B.length;T++){var W=B[T];W!=="protocol"&&(S[W]=v[W])}return g[S.protocol]&&S.hostname&&!S.pathname&&(S.pathname="/",S.path=S.pathname),S.href=S.format(),S}if(v.protocol&&v.protocol!==S.protocol){if(!g[v.protocol]){for(var F=Object.keys(v),N=0;N<F.length;N++){var ae=F[N];S[ae]=v[ae]}return S.href=S.format(),S}if(S.protocol=v.protocol,!v.host&&!f[v.protocol]){for(var be=(v.pathname||"").split("/");be.length&&!(v.host=be.shift()););v.host||(v.host=""),v.hostname||(v.hostname=""),be[0]!==""&&be.unshift(""),be.length<2&&be.unshift(""),S.pathname=be.join("/")}else S.pathname=v.pathname;if(S.search=v.search,S.query=v.query,S.host=v.host||"",S.auth=v.auth,S.hostname=v.hostname||v.host,S.port=v.port,S.pathname||S.search){var Y=S.pathname||"",K=S.search||"";S.path=Y+K}return S.slashes=S.slashes||v.slashes,S.href=S.format(),S}var re=S.pathname&&S.pathname.charAt(0)==="/",D=v.host||v.pathname&&v.pathname.charAt(0)==="/",Z=D||re||S.host&&v.pathname,P=Z,J=S.pathname&&S.pathname.split("/")||[],be=v.pathname&&v.pathname.split("/")||[],te=S.protocol&&!g[S.protocol];if(te&&(S.hostname="",S.port=null,S.host&&(J[0]===""?J[0]=S.host:J.unshift(S.host)),S.host="",v.protocol&&(v.hostname=null,v.port=null,v.host&&(be[0]===""?be[0]=v.host:be.unshift(v.host)),v.host=null),Z=Z&&(be[0]===""||J[0]==="")),D)S.host=v.host||v.host===""?v.host:S.host,S.hostname=v.hostname||v.hostname===""?v.hostname:S.hostname,S.search=v.search,S.query=v.query,J=be;else if(be.length)J||(J=[]),J.pop(),J=J.concat(be),S.search=v.search,S.query=v.query;else if(v.search!=null){if(te){S.host=J.shift(),S.hostname=S.host;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return S.search=v.search,S.query=v.query,(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.href=S.format(),S}if(!J.length)return S.pathname=null,S.search?S.path="/"+S.search:S.path=null,S.href=S.format(),S;for(var V=J.slice(-1)[0],L=(S.host||v.host||J.length>1)&&(V==="."||V==="..")||V==="",ne=0,H=J.length;H>=0;H--)V=J[H],V==="."?J.splice(H,1):V===".."?(J.splice(H,1),ne++):ne&&(J.splice(H,1),ne--);if(!Z&&!P)for(;ne--;ne)J.unshift("..");Z&&J[0]!==""&&(!J[0]||J[0].charAt(0)!=="/")&&J.unshift(""),L&&J.join("/").substr(-1)!=="/"&&J.push("");var G=J[0]===""||J[0]&&J[0].charAt(0)==="/";if(te){S.hostname=G?"":J.length?J.shift():"",S.host=S.hostname;var we=S.host&&S.host.indexOf("@")>0?S.host.split("@"):!1;we&&(S.auth=we.shift(),S.hostname=we.shift(),S.host=S.hostname)}return Z=Z||S.host&&J.length,Z&&!G&&J.unshift(""),J.length>0?S.pathname=J.join("/"):(S.pathname=null,S.path=null),(S.pathname!==null||S.search!==null)&&(S.path=(S.pathname?S.pathname:"")+(S.search?S.search:"")),S.auth=v.auth||S.auth,S.slashes=S.slashes||v.slashes,S.href=S.format(),S},e.prototype.parseHost=function(){var v=this.host,x=r.exec(v);x&&(x=x[0],x!==":"&&(this.port=x.substr(1)),v=v.substr(0,v.length-x.length)),v&&(this.hostname=v)},yt.parse=k,yt.resolve=w,yt.resolveObject=E,yt.format=m,yt.Url=e,yt}function _a(c){if(typeof c=="string")c=new URL(c);else if(!(c instanceof URL))throw new Deno.errors.InvalidData("invalid argument path , must be a string or URL");if(c.protocol!=="file:")throw new Deno.errors.InvalidData("invalid url scheme");return Rr?Ju(c):Xu(c)}function Ju(c){let e=c.hostname,t=c.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let a=t.codePointAt(r+2)||32;if(t[r+1]==="2"&&a===102||t[r+1]==="5"&&a===99)throw new Deno.errors.InvalidData("must not include encoded \\ or / characters")}if(t=t.replace(La,"\\"),t=decodeURIComponent(t),e!=="")return`\\\\${e}${t}`;{let r=t.codePointAt(1)|32,a=t[2];if(r<Ra||r>ja||a!==":")throw new Deno.errors.InvalidData("file url path must be absolute");return t.slice(1)}}function Xu(c){if(c.hostname!=="")throw new Deno.errors.InvalidData("invalid file url hostname");let e=c.pathname;for(let t=0;t<e.length;t++)if(e[t]==="%"){let r=e.codePointAt(t+2)||32;if(e[t+1]==="2"&&r===102)throw new Deno.errors.InvalidData("must not include encoded / characters")}return decodeURIComponent(e)}function ka(c){let e=qi.resolve(c),t=c.charCodeAt(c.length-1);(t===Ma||Rr&&t===Pa)&&e[e.length-1]!==qi.sep&&(e+="/");let r=new URL("file://");return e.includes("%")&&(e=e.replace(Na,"%25")),!Rr&&e.includes("\\")&&(e=e.replace(Ua,"%5C")),e.includes(`
|
|
8
|
-
`)&&(e=e.replace(Ba,"%0A")),e.includes("\r")&&(e=e.replace(Fa,"%0D")),e.includes(" ")&&(e=e.replace(Da,"%09")),r.pathname=e,r}var Sa,xr,zi,Ar,Ir,Ki,Tr,Vi,Cr,Gi,Or,Yi,Pr,Qi,Mr,Ji,yt,Xi,De,Ea,xa,Aa,Ia,Ta,Ca,Oa,Pa,Ma,Ra,ja,Rr,La,Na,Ua,Ba,Fa,Da,Zu=He(()=>{le(),ue(),ce(),mu(),Mu(),Hu(),ya(),Sa=Object.freeze(Object.create(null)),xr={},zi=!1,Ar=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Ir={},Ki=!1,Tr={},Vi=!1,Cr={},Gi=!1,Or={},Yi=!1,Pr={},Qi=!1,Mr={},Ji=!1,yt={},Xi=!1,De=Qu(),De.parse,De.resolve,De.resolveObject,De.format,De.Url,Ea=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,De.URL=typeof URL<"u"?URL:null,De.pathToFileURL=ka,De.fileURLToPath=_a,xa=De.Url,Aa=De.format,Ia=De.resolve,Ta=De.resolveObject,Ca=De.parse,Oa=De.URL,Pa=92,Ma=47,Ra=97,ja=122,Rr=Ea==="win32",La=/\//g,Na=/%/g,Ua=/\\/g,Ba=/\n/g,Fa=/\r/g,Da=/\t/g}),eh=pe((c,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),Zi=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.BufferedDuplex=void 0,c.writev=r;var e=Et(),t=(Ue(),Pe(Ne));function r(n,i){let s=new Array(n.length);for(let o=0;o<n.length;o++)typeof n[o].chunk=="string"?s[o]=t.Buffer.from(n[o].chunk,"utf8"):s[o]=n[o].chunk;this._write(t.Buffer.concat(s),"binary",i)}var a=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,s){super({objectMode:!0}),this.proxy=i,this.socket=s,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",o=>{!this.destroyed&&this.readable&&this.push(o)})}_read(n){this.proxy.read(n)}_write(n,i,s){this.isSocketOpen?this.writeToProxy(n,i,s):this.writeQueue.push({chunk:n,encoding:i,cb:s})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,s){this.proxy.write(n,i)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:s}=this.writeQueue.shift();this.writeToProxy(n,i,s)}}};c.BufferedDuplex=a}),jr=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(k){return k&&k.__esModule?k:{default:k}};Object.defineProperty(c,"__esModule",{value:!0}),c.streamBuilder=c.browserStreamBuilder=void 0;var t=(Ue(),Pe(Ne)),r=e(eh()),a=e(lt()),n=Et(),i=e(lr()),s=Zi(),o=(0,a.default)("mqttjs:ws"),l=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(k,m){let w=`${k.protocol}://${k.hostname}:${k.port}${k.path}`;return typeof k.transformWsUrl=="function"&&(w=k.transformWsUrl(w,k,m)),w}function d(k){let m=k;return k.port||(k.protocol==="wss"?m.port=443:m.port=80),k.path||(m.path="/"),k.wsOptions||(m.wsOptions={}),!i.default&&!k.forceNativeWebSocket&&k.protocol==="wss"&&l.forEach(w=>{Object.prototype.hasOwnProperty.call(k,w)&&!Object.prototype.hasOwnProperty.call(k.wsOptions,w)&&(m.wsOptions[w]=k[w])}),m}function p(k){let m=d(k);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let w=new URL(document.URL);m.hostname=w.hostname,m.port||(m.port=Number(w.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function y(k,m,w){o("createWebSocket"),o(`protocol: ${w.protocolId} ${w.protocolVersion}`);let E=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";o(`creating new Websocket for url: ${m} and protocol: ${E}`);let v;return w.createWebsocket?v=w.createWebsocket(m,[E],w):v=new r.default(m,[E],w.wsOptions),v}function f(k,m){let w=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",E=u(m,k),v;return m.createWebsocket?v=m.createWebsocket(E,[w],m):v=new WebSocket(E,[w]),v.binaryType="arraybuffer",v}var g=(k,m)=>{o("streamBuilder");let w=d(m);w.hostname=w.hostname||w.host||"localhost";let E=u(w,k),v=y(k,E,w),x=r.default.createWebSocketStream(v,w.wsOptions);return x.url=E,v.on("close",()=>{x.destroy()}),x};c.streamBuilder=g;var b=(k,m)=>{o("browserStreamBuilder");let w,E=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,x=!m.objectMode,S=f(k,m),I=O(m,N,ae);m.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{S.close()});let M=typeof S.addEventListener<"u";S.readyState===S.OPEN?(w=I,w.socket=S):(w=new s.BufferedDuplex(m,I,S),M?S.addEventListener("open",B):S.onopen=B),M?(S.addEventListener("close",T),S.addEventListener("error",W),S.addEventListener("message",F)):(S.onclose=T,S.onerror=W,S.onmessage=F);function O(Y,K,re){let D=new n.Transform({objectMode:Y.objectMode});return D._write=K,D._flush=re,D}function B(){o("WebSocket onOpen"),w instanceof s.BufferedDuplex&&w.socketReady()}function T(Y){o("WebSocket onClose",Y),w.end(),w.destroy()}function W(Y){o("WebSocket onError",Y);let K=new Error("WebSocket error");K.event=Y,w.destroy(K)}async function F(Y){if(!I||!I.readable||!I.writable)return;let{data:K}=Y;K instanceof ArrayBuffer?K=t.Buffer.from(K):K instanceof Blob?K=t.Buffer.from(await new Response(K).arrayBuffer()):K=t.Buffer.from(K,"utf8"),I.push(K)}function N(Y,K,re){if(S.bufferedAmount>E){setTimeout(N,v,Y,K,re);return}x&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch(D){return re(D)}re()}function ae(Y){S.close(),Y()}return w};c.browserStreamBuilder=b}),eo={};Ct(eo,{Server:()=>Re,Socket:()=>Re,Stream:()=>Re,_createServerHandle:()=>Re,_normalizeArgs:()=>Re,_setSimultaneousAccepts:()=>Re,connect:()=>Re,createConnection:()=>Re,createServer:()=>Re,default:()=>$a,isIP:()=>Re,isIPv4:()=>Re,isIPv6:()=>Re});function Re(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var $a,Wa=He(()=>{le(),ue(),ce(),$a={_createServerHandle:Re,_normalizeArgs:Re,_setSimultaneousAccepts:Re,connect:Re,createConnection:Re,createServer:Re,isIP:Re,isIPv4:Re,isIPv6:Re,Server:Re,Socket:Re,Stream:Re}}),qa=pe((c,e)=>{le(),ue(),ce(),e.exports={}}),Ha=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(c,"__esModule",{value:!0});var t=e((Wa(),Pe(eo))),r=e(lt()),a=e(qa()),n=(0,r.default)("mqttjs:tcp"),i=(s,o)=>{if(o.port=o.port||1883,o.hostname=o.hostname||o.host||"localhost",o.socksProxy)return(0,a.default)(o.hostname,o.port,o.socksProxy,{timeout:o.socksTimeout});let{port:l,path:u}=o,d=o.hostname;return n("port %d and host %s",l,d),t.default.createConnection({port:l,host:d,path:u})};c.default=i}),za={};Ct(za,{default:()=>Ka});var Ka,th=He(()=>{le(),ue(),ce(),Ka={}}),Va=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(c,"__esModule",{value:!0});var t=(th(),Pe(za)),r=e((Wa(),Pe(eo))),a=e(lt()),n=e(qa()),i=(0,a.default)("mqttjs:tls");function s(l){let{host:u,port:d,socksProxy:p,...y}=l;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:l.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(l)}var o=(l,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=s(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(y){u.rejectUnauthorized&&l.emit("error",y),d.end()}return d.on("error",p),d};c.default=o}),Ga=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ue(),Pe(Ne)),t=Et(),r=Zi(),a,n,i;function s(){let p=new t.Transform;return p._write=(y,f,g)=>{a.send({data:y.buffer,success(){g()},fail(b){g(new Error(b))}})},p._flush=y=>{a.close({success(){y()}})},p}function o(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function l(p,y){let f=p.protocol==="wxs"?"wss":"ws",g=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,y)),g}function u(){a.onOpen(()=>{i.socketReady()}),a.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),n.push(y)}),a.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),a.onError(p=>{let y=new Error(p.errMsg);i.destroy(y)})}var d=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";o(y);let g=l(y,p);a=wx.connectSocket({url:g,protocols:[f]}),n=s(),i=new r.BufferedDuplex(y,n,a),i._destroy=(k,m)=>{a.close({success(){m&&m(k)}})};let b=i.destroy;return i.destroy=(k,m)=>(i.destroy=b,setTimeout(()=>{a.close({fail(){i._destroy(k,m)}})},0),i),u(),i};c.default=d}),Ya=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ue(),Pe(Ne)),t=Et(),r=Zi(),a,n,i,s=!1;function o(){let y=new t.Transform;return y._write=(f,g,b)=>{a.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{a.closeSocket({success(){f()}})},y}function l(y){y.hostname||(y.hostname="localhost"),y.path||(y.path="/"),y.wsOptions||(y.wsOptions={})}function u(y,f){let g=y.protocol==="alis"?"wss":"ws",b=`${g}://${y.hostname}${y.path}`;return y.port&&y.port!==80&&y.port!==443&&(b=`${g}://${y.hostname}:${y.port}${y.path}`),typeof y.transformWsUrl=="function"&&(b=y.transformWsUrl(b,y,f)),b}function d(){s||(s=!0,a.onSocketOpen(()=>{i.socketReady()}),a.onSocketMessage(y=>{if(typeof y.data=="string"){let f=e.Buffer.from(y.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(y.data)}}),a.onSocketClose(()=>{i.end(),i.destroy()}),a.onSocketError(y=>{i.destroy(y)}))}var p=(y,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let g=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";l(f);let b=u(f,y);return a=f.my,a.connectSocket({url:b,protocols:g}),n=o(),i=new r.BufferedDuplex(f,n,a),d(),i};c.default=p}),rh=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(c,"__esModule",{value:!0}),c.connectAsync=u;var t=e(lt()),r=e((Zu(),Pe(va))),a=e(oi()),n=e(lr());typeof Me?.nextTick!="function"&&(Me.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),s=null;function o(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;d.username=y,d.password=f}else d.username=d.auth}function l(d,p){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let g=r.default.parse(d,!0),b={};if(g.port!=null&&(b.port=Number(g.port)),b.host=g.hostname,b.query=g.query,b.auth=g.auth,b.protocol=g.protocol,b.path=g.path,p={...b,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,o(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Me<"u"&&(p.socksProxy=Me.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=jr().streamBuilder,s.wss=jr().streamBuilder,s.mqtt=Ha().default,s.tcp=Ha().default,s.ssl=Va().default,s.tls=s.ssl,s.mqtts=Va().default):(s.ws=jr().browserStreamBuilder,s.wss=jr().browserStreamBuilder,s.wx=Ga().default,s.wxs=Ga().default,s.ali=Ya().default,s.alis=Ya().default)),!s[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,k)=>g&&k%2===0?!1:typeof s[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function y(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),s[p.protocol](g,p)}let f=new a.default(y,p);return f.on("error",()=>{}),f}function u(d,p,y=!0){return new Promise((f,g)=>{let b=l(d,p),k={connect:w=>{m(),f(b)},end:()=>{m(),f(b)},error:w=>{m(),b.end(),g(w)}};y===!1&&(k.close=()=>{k.error(new Error("Couldn't connect to server"))});function m(){Object.keys(k).forEach(w=>{b.off(w,k[w])})}Object.keys(k).forEach(w=>{b.on(w,k[w])})})}c.default=l}),Qa=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(y,f,g,b){b===void 0&&(b=g);var k=Object.getOwnPropertyDescriptor(f,g);(!k||("get"in k?!f.__esModule:k.writable||k.configurable))&&(k={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(y,b,k)}:function(y,f,g,b){b===void 0&&(b=g),y[b]=f[g]}),t=c&&c.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),r=c&&c.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(g){var b=[];for(var k in g)Object.prototype.hasOwnProperty.call(g,k)&&(b[b.length]=k);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var b=y(f),k=0;k<b.length;k++)b[k]!=="default"&&e(g,f,b[k]);return t(g,f),g}})(),a=c&&c.__exportStar||function(y,f){for(var g in y)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,y,g)},n=c&&c.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(c,"__esModule",{value:!0}),c.ReasonCodes=c.KeepaliveManager=c.UniqueMessageIdProvider=c.DefaultMessageIdProvider=c.Store=c.MqttClient=c.connectAsync=c.connect=c.Client=void 0;var i=n(oi());c.MqttClient=i.default;var s=n(ns());c.DefaultMessageIdProvider=s.default;var o=n(pu());c.UniqueMessageIdProvider=o.default;var l=n(Qo());c.Store=l.default;var u=r(rh());c.connect=u.default,Object.defineProperty(c,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(us());c.KeepaliveManager=d.default,c.Client=i.default,a(oi(),c),a(Rt(),c),a(Yo(),c);var p=sr();Object.defineProperty(c,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),nh=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(i,s,o,l){l===void 0&&(l=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,l,u)}:function(i,s,o,l){l===void 0&&(l=o),i[l]=s[o]}),t=c&&c.__setModuleDefault||(Object.create?function(i,s){Object.defineProperty(i,"default",{enumerable:!0,value:s})}:function(i,s){i.default=s}),r=c&&c.__importStar||(function(){var i=function(s){return i=Object.getOwnPropertyNames||function(o){var l=[];for(var u in o)Object.prototype.hasOwnProperty.call(o,u)&&(l[l.length]=u);return l},i(s)};return function(s){if(s&&s.__esModule)return s;var o={};if(s!=null)for(var l=i(s),u=0;u<l.length;u++)l[u]!=="default"&&e(o,s,l[u]);return t(o,s),o}})(),a=c&&c.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(c,"__esModule",{value:!0});var n=r(Qa());c.default=n,a(Qa(),c)});const ih=nh();const oh={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},sh=300,ah={templateId:"7",type:"link",isDeepLink:!0},lh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Ja{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;disposed=!1;reconnectTimer=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??`aikaara_${e.userId}_${Date.now()}`,this.topics={...oh,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??10,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0},r={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!0,reconnectPeriod:0,connectTimeout:this.config.connectTimeoutMs??1e4,keepalive:this.config.keepAliveSec??60,protocolVersion:this.config.protocolVersion??3,protocolId:this.config.protocolId??"MQIsdp"};return this.config.enablePresence!==!1&&(r.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),new Promise((a,n)=>{this.client=ih.connect(this.config.mqttEndpoint,r),this.client.on("connect",()=>{if(this.reconnectAttempt=0,this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const i=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(i),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:i})}a()}),this.client.on("message",(i,s)=>{this.dispatchInbound(i,s)}),this.client.on("close",()=>{this.debugLog("CLOSE",{}),this.notifyStateChange(!1),this.disposed||this.scheduleReconnect()}),this.client.on("error",i=>{this.debugLog("ERROR",{message:i.message}),this.reconnectAttempt===0&&n(i)}),this.client.on("packetsend",i=>{(i.cmd==="subscribe"||i.cmd==="unsubscribe"||i.cmd==="pingreq")&&this.debugLog(i.cmd.toUpperCase(),{topic:i.topic,packetId:i.messageId})})})}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[a,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[a]=`${n.slice(0,200)}…(${n.length})`:r[a]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const a=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,a)}publishFileMessage(e,t){if(!this.client)return;const r={...ah,...this.config.fileTemplate??{},...ch(t)},a={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(a),type:"html",attributes:n,metadata:a.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=sh){if(!this.client)return;const a=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(a,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed)return;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const t=[...this.subscribedTopics];this.subscribedTopics.clear(),t.forEach(r=>{this.client&&(this.client.subscribe(r,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(r))})}catch{}}},e)}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let a=null;try{a=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!a)return;this.debugLog("RECV",{topic:e,sender:a.sender,type:a.type,contentType:a.metadata?.contentType,templateId:a.metadata?.templateId,messageId:a.message_id,text:typeof a.text=="string"?a.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const l=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof a.status=="number"?a.status:Number(a.status??0),p={conversationId:l,messageId:u,status:d,raw:a};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(a,{topic:e,conversationId:l,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),s=i?.groups?.conversationId,o={topic:e,conversationId:s,messageId:typeof a.message_id=="string"?a.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(l=>l(a,o))}buildOutgoingEnvelope(e,t){const r={...lh,...this.config.messageDefaults??{}},a=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:a,senderFullname:a,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(a,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(a,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const s=i[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function ch(c){const e={};for(const[t,r]of Object.entries(c))r!==void 0&&(e[t]=r);return e}function Xa(c,e){return(c.sender??"").toString()===e}function Za(c,e){const t=(c.sender??"").toString(),r=e.systemSenders??["metadata","system"],a=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(a)?"assistant":r.includes(t)?"system":"agent":"system"}function to(c){const e={raw:c},t=c.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof c.text=="string"&&c.text.trim().startsWith("{"))try{const r=JSON.parse(c.text);typeof r.message=="string"&&(e.innerMessage=r.message);const a=r.metadata;a&&typeof a=="object"&&(!e.contentType&&typeof a.contentType=="string"&&(e.contentType=a.contentType),!e.templateId&&typeof a.templateId=="string"&&(e.templateId=a.templateId),e.payload===void 0&&a.payload!==void 0&&(e.payload=a.payload))}catch{}return e}function el(c){const e=to(c);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const a=r[0],n=a.action,i=n&&typeof n.url=="string"?n.url:void 0,s=typeof a.description=="string"?a.description:void 0,o=c.attributes,l=o&&typeof o.cloudFileId=="string"?o.cloudFileId:void 0;return!i&&!s?null:{fileName:s,fileUrl:i,cloudFileId:l,templateId:e.templateId}}function tl(c,e,t){const r=Za(c,t),a=to(c),n=el(c);let i="";a.innerMessage?i=a.innerMessage:typeof c.text=="string"&&(c.text.trim().startsWith("{")?a.contentType!=="300"&&(i=c.text):i=c.text);const s=typeof c.message_id=="string"?c.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=typeof c.timestamp=="number"?new Date(c.timestamp).toISOString():new Date().toISOString(),l=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof c.status=="number"?uh(c.status):"delivered",d={id:s,externalId:s,conversationId:e,role:l,content:i,createdAt:o,status:u,metadata:{sender:c.sender,sender_fullname:c.sender_fullname??c.senderFullname,app_id:c.app_id,attributes:c.attributes}};return a.contentType&&(d.template={contentType:a.contentType,templateId:a.templateId,payload:a.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:a}}function uh(c){return c<0?"error":c>=250?"read":c>=150?"delivered":"sent"}class rl extends Zt{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new yo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new vo,this.conversationManager=new wo(e.conversationId),this.usesAikaara()&&(this.connection=new bo(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Ja({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const a=r?"connected":"disconnected";this.emit("connection:state",a),this.config.onConnectionStateChange?.(a)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,a)=>this.handleTiledeskMessage(r,a))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),a=this.config.tiledesk?.autoInitiateOnEmpty??!0;r==="empty"&&a&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const a=r.map(s=>tl(s,e,{userId:t}).message).sort((s,o)=>new Date(s.createdAt).getTime()-new Date(o.createdAt).getTime()),n=this.messageStore.messages,i=[...a,...n.filter(s=>!a.some(o=>o.externalId&&o.externalId===s.externalId))];if(this.messageStore.setMessages(i),this.config.onMessage)for(const s of a)try{this.config.onMessage(s)}catch(o){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",o)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",a),this.config.onMessage?.(a);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:a.fileName,fileUrl:a.url,cloudFileId:a.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const a=this.conversationManager.conversationId;if(!a)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(a,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=t.conversationId??this.conversationManager.conversationId;if(!r)return;const a=this.config.tiledeskIdentity?.userId??"",{message:n,template:i}=tl(e,r,{userId:a,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(Xa(e,a)){const l=this.messageStore.reconcileOptimistic(n);if(l){this.emit("message:updated",l);return}}const{message:s,deduped:o}=this.messageStore.upsertRemoteMessage(n);if(o?this.emit("message:updated",s):(this.emit("message:received",s),this.config.onMessage?.(s)),i.contentType){const l={messageId:s.id,conversationId:r,role:n.role==="tool"?"system":n.role,contentType:i.contentType,templateId:i.templateId,payload:i.payload,innerMessage:i.innerMessage,raw:e};this.config.onTemplateMessage?.(l)}}handleTiledeskStatusUpdate(e){e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered")}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",a=e.content||"";a?this.messageStore.updateStreaming(a):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,a=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),a&&(this.emit("stream:end",{messageId:a.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",a),this.config.onMessage?.(a));break}case"message_queued":{const r=this.messageStore.messages.findLast(a=>a.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class hh extends Zt{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const nl={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",json:"application/json",zip:"application/zip"};function fh(c){const e=c.lastIndexOf(".");return e<0||e===c.length-1?"":c.slice(e+1).toLowerCase()}function dh(c,e,t){const r=c.type;if(r&&r.trim().length>0)return r;const a=fh(c.name||"");if(a){if(e&&e[a])return e[a];if(nl[a])return nl[a]}return t}function ro(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function ph(c,e){const t=e.split(".");let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return"";return typeof r=="string"?r:""}function il(c){const e=c.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const a=t.name||`upload-${Date.now()}`,n={fileName:a,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId},i=c.authHeader?await c.authHeader():void 0,s={accept:"application/json",...c.extraHeaders??{},...i?{authorization:i}:{}},o=ro(c.signEndpoint.includes("{")?c.signEndpoint:`${c.signEndpoint}?fileName={fileName}`,n),l=await fetch(o,{method:c.signMethod??"GET",headers:s});if(!l.ok)throw new Error(`Sign request failed: ${l.status}`);const u=await l.json().catch(()=>({})),d=ph(u,e);if(!d)throw new Error(`Sign response missing path "${e}"`);const p=dh(t,c.contentTypeMap,c.contentTypeFallback??"application/octet-stream"),y=c.s3HostRewrite?d.replace(/^https:\/\/[^/]+/i,c.s3HostRewrite):d,f=await fetch(y,{method:"PUT",headers:{"content-type":p},body:t});if(!f.ok){const b=await f.text().catch(()=>"");throw new Error(`S3 PUT failed: ${f.status} ${b.slice(0,200)}`)}if(c.registerEndpoint){const b=JSON.parse(ro(JSON.stringify(c.registerBody??{}),n)),k=await fetch(c.registerEndpoint,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify(b)});if(!k.ok){const m=await k.text().catch(()=>"");throw new Error(`Register failed: ${k.status} ${m.slice(0,200)}`)}}return{url:c.viewerTemplate?ro(c.viewerTemplate,n):d.split("?")[0],fileName:a,contentType:p,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function no(c){return{async upload(e,t){const r=new FormData,a=c.fieldName??"file";r.append(a,e,e.name);const n=typeof c.extraFields=="function"?c.extraFields(t):c.extraFields;if(n)for(const[p,y]of Object.entries(n))r.append(p,y);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof c.headers=="function"?await c.headers():c.headers??{},s=await fetch(c.endpoint,{method:c.method??"POST",body:r,headers:i,credentials:c.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const o=await s.json().catch(()=>({}));if(c.parseResponse)return c.parseResponse(o,t);const l=o,u=l.url??l.fileUrl??l.publicUrl,d=l.fileName??l.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof l.cloudFileId=="string"?l.cloudFileId:void 0,relativePath:typeof l.path=="string"?l.path:void 0,contentType:typeof l.contentType=="string"?l.contentType:void 0,byteSize:typeof l.byteSize=="number"?l.byteSize:void 0,meta:l}}}}const gh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function ol(c){const e=c.apiBase.replace(/\/$/,""),t=c.pageSize??200,r=c.pathTemplate??gh;return{async fetchMessages(a,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(a)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),s=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,o={accept:"application/json","content-type":"application/json",...c.extraHeaders??{}};if(c.getToken){const p=await c.getToken();p&&(o.authorization=p)}const l=await fetch(s,{method:"GET",headers:o}),u=await l.json().catch(()=>null);if(c.parseResponse&&u)return c.parseResponse(u);const d=u;if(d&&Array.isArray(d.result))return d.result;if(!l.ok)throw new Error(`History fetch failed: ${l.status} ${l.statusText}`);return[]}}}class mh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;constructor(e,t,r){this.client=new rl(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e)}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.client.config.templateActionAttributes??{},a=t.attributes?.action??{},n={...t.attributes,action:{...r,...a}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class sl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||Yl,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||go,position:this.getAttribute("position")||this._config.position||Gl,width:Number(this.getAttribute("width"))||this._config.width||Hl,height:Number(this.getAttribute("height"))||this._config.height||zl,fontFamily:this._config.fontFamily||Vl,borderRadius:this._config.borderRadius??Kl,placeholder:this.getAttribute("placeholder")||this._config.placeholder||mo,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Ql,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,a){if(typeof document>"u")return;const n=document.documentElement,i=(s,o)=>{o!==void 0&&o!==""&&n.style.setProperty(`--aikaara-${s}`,o)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??a),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=a=>typeof a=="number"?`${a}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,a])=>a!==void 0&&a!=="").map(([a,n])=>`--aikaara-${a}: ${n};`).join(`
|
|
8
|
+
`)&&(e=e.replace(Ba,"%0A")),e.includes("\r")&&(e=e.replace(Fa,"%0D")),e.includes(" ")&&(e=e.replace(Da,"%09")),r.pathname=e,r}var Sa,xr,zi,Ar,Ir,Ki,Tr,Vi,Cr,Gi,Or,Yi,Pr,Qi,Mr,Ji,yt,Xi,De,Ea,xa,Aa,Ia,Ta,Ca,Oa,Pa,Ma,Ra,ja,Rr,La,Na,Ua,Ba,Fa,Da,Zu=He(()=>{le(),ue(),ce(),mu(),Mu(),Hu(),ya(),Sa=Object.freeze(Object.create(null)),xr={},zi=!1,Ar=typeof globalThis<"u"?globalThis:typeof self<"u"?self:global,Ir={},Ki=!1,Tr={},Vi=!1,Cr={},Gi=!1,Or={},Yi=!1,Pr={},Qi=!1,Mr={},Ji=!1,yt={},Xi=!1,De=Qu(),De.parse,De.resolve,De.resolveObject,De.format,De.Url,Ea=typeof Deno<"u"?Deno.build.os==="windows"?"win32":Deno.build.os:void 0,De.URL=typeof URL<"u"?URL:null,De.pathToFileURL=ka,De.fileURLToPath=_a,xa=De.Url,Aa=De.format,Ia=De.resolve,Ta=De.resolveObject,Ca=De.parse,Oa=De.URL,Pa=92,Ma=47,Ra=97,ja=122,Rr=Ea==="win32",La=/\//g,Na=/%/g,Ua=/\\/g,Ba=/\n/g,Fa=/\r/g,Da=/\t/g}),eh=pe((c,e)=>{le(),ue(),ce(),e.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}}),Zi=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0}),c.BufferedDuplex=void 0,c.writev=r;var e=Et(),t=(Ue(),Pe(Ne));function r(n,i){let s=new Array(n.length);for(let o=0;o<n.length;o++)typeof n[o].chunk=="string"?s[o]=t.Buffer.from(n[o].chunk,"utf8"):s[o]=n[o].chunk;this._write(t.Buffer.concat(s),"binary",i)}var a=class extends e.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(n,i,s){super({objectMode:!0}),this.proxy=i,this.socket=s,this.writeQueue=[],n.objectMode||(this._writev=r.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",o=>{!this.destroyed&&this.readable&&this.push(o)})}_read(n){this.proxy.read(n)}_write(n,i,s){this.isSocketOpen?this.writeToProxy(n,i,s):this.writeQueue.push({chunk:n,encoding:i,cb:s})}_final(n){this.writeQueue=[],this.proxy.end(n)}_destroy(n,i){this.writeQueue=[],this.proxy.destroy(),i(n)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(n,i,s){this.proxy.write(n,i)===!1?this.proxy.once("drain",s):s()}processWriteQueue(){for(;this.writeQueue.length>0;){let{chunk:n,encoding:i,cb:s}=this.writeQueue.shift();this.writeToProxy(n,i,s)}}};c.BufferedDuplex=a}),jr=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(k){return k&&k.__esModule?k:{default:k}};Object.defineProperty(c,"__esModule",{value:!0}),c.streamBuilder=c.browserStreamBuilder=void 0;var t=(Ue(),Pe(Ne)),r=e(eh()),a=e(lt()),n=Et(),i=e(lr()),s=Zi(),o=(0,a.default)("mqttjs:ws"),l=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function u(k,m){let w=`${k.protocol}://${k.hostname}:${k.port}${k.path}`;return typeof k.transformWsUrl=="function"&&(w=k.transformWsUrl(w,k,m)),w}function d(k){let m=k;return k.port||(k.protocol==="wss"?m.port=443:m.port=80),k.path||(m.path="/"),k.wsOptions||(m.wsOptions={}),!i.default&&!k.forceNativeWebSocket&&k.protocol==="wss"&&l.forEach(w=>{Object.prototype.hasOwnProperty.call(k,w)&&!Object.prototype.hasOwnProperty.call(k.wsOptions,w)&&(m.wsOptions[w]=k[w])}),m}function p(k){let m=d(k);if(m.hostname||(m.hostname=m.host),!m.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let w=new URL(document.URL);m.hostname=w.hostname,m.port||(m.port=Number(w.port))}return m.objectMode===void 0&&(m.objectMode=!(m.binary===!0||m.binary===void 0)),m}function y(k,m,w){o("createWebSocket"),o(`protocol: ${w.protocolId} ${w.protocolVersion}`);let E=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";o(`creating new Websocket for url: ${m} and protocol: ${E}`);let v;return w.createWebsocket?v=w.createWebsocket(m,[E],w):v=new r.default(m,[E],w.wsOptions),v}function f(k,m){let w=m.protocolId==="MQIsdp"&&m.protocolVersion===3?"mqttv3.1":"mqtt",E=u(m,k),v;return m.createWebsocket?v=m.createWebsocket(E,[w],m):v=new WebSocket(E,[w]),v.binaryType="arraybuffer",v}var g=(k,m)=>{o("streamBuilder");let w=d(m);w.hostname=w.hostname||w.host||"localhost";let E=u(w,k),v=y(k,E,w),x=r.default.createWebSocketStream(v,w.wsOptions);return x.url=E,v.on("close",()=>{x.destroy()}),x};c.streamBuilder=g;var b=(k,m)=>{o("browserStreamBuilder");let w,E=p(m).browserBufferSize||1024*512,v=m.browserBufferTimeout||1e3,x=!m.objectMode,S=f(k,m),I=O(m,N,ae);m.objectMode||(I._writev=s.writev.bind(I)),I.on("close",()=>{S.close()});let M=typeof S.addEventListener<"u";S.readyState===S.OPEN?(w=I,w.socket=S):(w=new s.BufferedDuplex(m,I,S),M?S.addEventListener("open",B):S.onopen=B),M?(S.addEventListener("close",T),S.addEventListener("error",W),S.addEventListener("message",F)):(S.onclose=T,S.onerror=W,S.onmessage=F);function O(Y,K,re){let D=new n.Transform({objectMode:Y.objectMode});return D._write=K,D._flush=re,D}function B(){o("WebSocket onOpen"),w instanceof s.BufferedDuplex&&w.socketReady()}function T(Y){o("WebSocket onClose",Y),w.end(),w.destroy()}function W(Y){o("WebSocket onError",Y);let K=new Error("WebSocket error");K.event=Y,w.destroy(K)}async function F(Y){if(!I||!I.readable||!I.writable)return;let{data:K}=Y;K instanceof ArrayBuffer?K=t.Buffer.from(K):K instanceof Blob?K=t.Buffer.from(await new Response(K).arrayBuffer()):K=t.Buffer.from(K,"utf8"),I.push(K)}function N(Y,K,re){if(S.bufferedAmount>E){setTimeout(N,v,Y,K,re);return}x&&typeof Y=="string"&&(Y=t.Buffer.from(Y,"utf8"));try{S.send(Y)}catch(D){return re(D)}re()}function ae(Y){S.close(),Y()}return w};c.browserStreamBuilder=b}),eo={};Ct(eo,{Server:()=>Re,Socket:()=>Re,Stream:()=>Re,_createServerHandle:()=>Re,_normalizeArgs:()=>Re,_setSimultaneousAccepts:()=>Re,connect:()=>Re,createConnection:()=>Re,createServer:()=>Re,default:()=>$a,isIP:()=>Re,isIPv4:()=>Re,isIPv6:()=>Re});function Re(){throw new Error("Node.js net module is not supported by JSPM core outside of Node.js")}var $a,Wa=He(()=>{le(),ue(),ce(),$a={_createServerHandle:Re,_normalizeArgs:Re,_setSimultaneousAccepts:Re,connect:Re,createConnection:Re,createServer:Re,isIP:Re,isIPv4:Re,isIPv6:Re,Server:Re,Socket:Re,Stream:Re}}),qa=pe((c,e)=>{le(),ue(),ce(),e.exports={}}),Ha=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(c,"__esModule",{value:!0});var t=e((Wa(),Pe(eo))),r=e(lt()),a=e(qa()),n=(0,r.default)("mqttjs:tcp"),i=(s,o)=>{if(o.port=o.port||1883,o.hostname=o.hostname||o.host||"localhost",o.socksProxy)return(0,a.default)(o.hostname,o.port,o.socksProxy,{timeout:o.socksTimeout});let{port:l,path:u}=o,d=o.hostname;return n("port %d and host %s",l,d),t.default.createConnection({port:l,host:d,path:u})};c.default=i}),za={};Ct(za,{default:()=>Ka});var Ka,th=He(()=>{le(),ue(),ce(),Ka={}}),Va=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(c,"__esModule",{value:!0});var t=(th(),Pe(za)),r=e((Wa(),Pe(eo))),a=e(lt()),n=e(qa()),i=(0,a.default)("mqttjs:tls");function s(l){let{host:u,port:d,socksProxy:p,...y}=l;if(p!==void 0){let f=(0,n.default)(u,d,p,{timeout:l.socksTimeout});return(0,t.connect)({...y,socket:f})}return(0,t.connect)(l)}var o=(l,u)=>{u.port=u.port||8883,u.host=u.hostname||u.host||"localhost",r.default.isIP(u.host)===0&&(u.servername=u.host),u.rejectUnauthorized=u.rejectUnauthorized!==!1,delete u.path,i("port %d host %s rejectUnauthorized %b",u.port,u.host,u.rejectUnauthorized);let d=s(u);d.on("secureConnect",()=>{u.rejectUnauthorized&&!d.authorized?d.emit("error",new Error("TLS not authorized")):d.removeListener("error",p)});function p(y){u.rejectUnauthorized&&l.emit("error",y),d.end()}return d.on("error",p),d};c.default=o}),Ga=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ue(),Pe(Ne)),t=Et(),r=Zi(),a,n,i;function s(){let p=new t.Transform;return p._write=(y,f,g)=>{a.send({data:y.buffer,success(){g()},fail(b){g(new Error(b))}})},p._flush=y=>{a.close({success(){y()}})},p}function o(p){p.hostname||(p.hostname="localhost"),p.path||(p.path="/"),p.wsOptions||(p.wsOptions={})}function l(p,y){let f=p.protocol==="wxs"?"wss":"ws",g=`${f}://${p.hostname}${p.path}`;return p.port&&p.port!==80&&p.port!==443&&(g=`${f}://${p.hostname}:${p.port}${p.path}`),typeof p.transformWsUrl=="function"&&(g=p.transformWsUrl(g,p,y)),g}function u(){a.onOpen(()=>{i.socketReady()}),a.onMessage(p=>{let{data:y}=p;y instanceof ArrayBuffer?y=e.Buffer.from(y):y=e.Buffer.from(y,"utf8"),n.push(y)}),a.onClose(()=>{i.emit("close"),i.end(),i.destroy()}),a.onError(p=>{let y=new Error(p.errMsg);i.destroy(y)})}var d=(p,y)=>{if(y.hostname=y.hostname||y.host,!y.hostname)throw new Error("Could not determine host. Specify host manually.");let f=y.protocolId==="MQIsdp"&&y.protocolVersion===3?"mqttv3.1":"mqtt";o(y);let g=l(y,p);a=wx.connectSocket({url:g,protocols:[f]}),n=s(),i=new r.BufferedDuplex(y,n,a),i._destroy=(k,m)=>{a.close({success(){m&&m(k)}})};let b=i.destroy;return i.destroy=(k,m)=>(i.destroy=b,setTimeout(()=>{a.close({fail(){i._destroy(k,m)}})},0),i),u(),i};c.default=d}),Ya=pe(c=>{le(),ue(),ce(),Object.defineProperty(c,"__esModule",{value:!0});var e=(Ue(),Pe(Ne)),t=Et(),r=Zi(),a,n,i,s=!1;function o(){let y=new t.Transform;return y._write=(f,g,b)=>{a.sendSocketMessage({data:f.buffer,success(){b()},fail(){b(new Error)}})},y._flush=f=>{a.closeSocket({success(){f()}})},y}function l(y){y.hostname||(y.hostname="localhost"),y.path||(y.path="/"),y.wsOptions||(y.wsOptions={})}function u(y,f){let g=y.protocol==="alis"?"wss":"ws",b=`${g}://${y.hostname}${y.path}`;return y.port&&y.port!==80&&y.port!==443&&(b=`${g}://${y.hostname}:${y.port}${y.path}`),typeof y.transformWsUrl=="function"&&(b=y.transformWsUrl(b,y,f)),b}function d(){s||(s=!0,a.onSocketOpen(()=>{i.socketReady()}),a.onSocketMessage(y=>{if(typeof y.data=="string"){let f=e.Buffer.from(y.data,"base64");n.push(f)}else{let f=new FileReader;f.addEventListener("load",()=>{if(f.result instanceof ArrayBuffer){n.push(e.Buffer.from(f.result));return}n.push(e.Buffer.from(f.result,"utf-8"))}),f.readAsArrayBuffer(y.data)}}),a.onSocketClose(()=>{i.end(),i.destroy()}),a.onSocketError(y=>{i.destroy(y)}))}var p=(y,f)=>{if(f.hostname=f.hostname||f.host,!f.hostname)throw new Error("Could not determine host. Specify host manually.");let g=f.protocolId==="MQIsdp"&&f.protocolVersion===3?"mqttv3.1":"mqtt";l(f);let b=u(f,y);return a=f.my,a.connectSocket({url:b,protocols:g}),n=o(),i=new r.BufferedDuplex(f,n,a),d(),i};c.default=p}),rh=pe(c=>{le(),ue(),ce();var e=c&&c.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(c,"__esModule",{value:!0}),c.connectAsync=u;var t=e(lt()),r=e((Zu(),Pe(va))),a=e(oi()),n=e(lr());typeof Me?.nextTick!="function"&&(Me.nextTick=setImmediate);var i=(0,t.default)("mqttjs"),s=null;function o(d){let p;if(d.auth)if(p=d.auth.match(/^(.+):(.+)$/),p){let[,y,f]=p;d.username=y,d.password=f}else d.username=d.auth}function l(d,p){if(i("connecting to an MQTT broker..."),typeof d=="object"&&!p&&(p=d,d=""),p=p||{},d&&typeof d=="string"){let g=r.default.parse(d,!0),b={};if(g.port!=null&&(b.port=Number(g.port)),b.host=g.hostname,b.query=g.query,b.auth=g.auth,b.protocol=g.protocol,b.path=g.path,p={...b,...p},!p.protocol)throw new Error("Missing protocol");p.protocol=p.protocol.replace(/:$/,"")}if(p.unixSocket=p.unixSocket||p.protocol?.includes("+unix"),p.unixSocket?p.protocol=p.protocol.replace("+unix",""):!p.protocol?.startsWith("ws")&&!p.protocol?.startsWith("wx")&&delete p.path,o(p),p.query&&typeof p.query.clientId=="string"&&(p.clientId=p.query.clientId),n.default||p.unixSocket?p.socksProxy=void 0:p.socksProxy===void 0&&typeof Me<"u"&&(p.socksProxy=Me.env.MQTTJS_SOCKS_PROXY),p.cert&&p.key)if(p.protocol){if(["mqtts","wss","wxs","alis"].indexOf(p.protocol)===-1)switch(p.protocol){case"mqtt":p.protocol="mqtts";break;case"ws":p.protocol="wss";break;case"wx":p.protocol="wxs";break;case"ali":p.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${p.protocol}"!`)}}else throw new Error("Missing secure protocol key");if(s||(s={},!n.default&&!p.forceNativeWebSocket?(s.ws=jr().streamBuilder,s.wss=jr().streamBuilder,s.mqtt=Ha().default,s.tcp=Ha().default,s.ssl=Va().default,s.tls=s.ssl,s.mqtts=Va().default):(s.ws=jr().browserStreamBuilder,s.wss=jr().browserStreamBuilder,s.wx=Ga().default,s.wxs=Ga().default,s.ali=Ya().default,s.alis=Ya().default)),!s[p.protocol]){let g=["mqtts","wss"].indexOf(p.protocol)!==-1;p.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((b,k)=>g&&k%2===0?!1:typeof s[b]=="function")[0]}if(p.clean===!1&&!p.clientId)throw new Error("Missing clientId for unclean clients");p.protocol&&(p.defaultProtocol=p.protocol);function y(g){return p.servers&&((!g._reconnectCount||g._reconnectCount===p.servers.length)&&(g._reconnectCount=0),p.host=p.servers[g._reconnectCount].host,p.port=p.servers[g._reconnectCount].port,p.protocol=p.servers[g._reconnectCount].protocol?p.servers[g._reconnectCount].protocol:p.defaultProtocol,p.hostname=p.host,g._reconnectCount++),i("calling streambuilder for",p.protocol),s[p.protocol](g,p)}let f=new a.default(y,p);return f.on("error",()=>{}),f}function u(d,p,y=!0){return new Promise((f,g)=>{let b=l(d,p),k={connect:w=>{m(),f(b)},end:()=>{m(),f(b)},error:w=>{m(),b.end(),g(w)}};y===!1&&(k.close=()=>{k.error(new Error("Couldn't connect to server"))});function m(){Object.keys(k).forEach(w=>{b.off(w,k[w])})}Object.keys(k).forEach(w=>{b.on(w,k[w])})})}c.default=l}),Qa=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(y,f,g,b){b===void 0&&(b=g);var k=Object.getOwnPropertyDescriptor(f,g);(!k||("get"in k?!f.__esModule:k.writable||k.configurable))&&(k={enumerable:!0,get:function(){return f[g]}}),Object.defineProperty(y,b,k)}:function(y,f,g,b){b===void 0&&(b=g),y[b]=f[g]}),t=c&&c.__setModuleDefault||(Object.create?function(y,f){Object.defineProperty(y,"default",{enumerable:!0,value:f})}:function(y,f){y.default=f}),r=c&&c.__importStar||(function(){var y=function(f){return y=Object.getOwnPropertyNames||function(g){var b=[];for(var k in g)Object.prototype.hasOwnProperty.call(g,k)&&(b[b.length]=k);return b},y(f)};return function(f){if(f&&f.__esModule)return f;var g={};if(f!=null)for(var b=y(f),k=0;k<b.length;k++)b[k]!=="default"&&e(g,f,b[k]);return t(g,f),g}})(),a=c&&c.__exportStar||function(y,f){for(var g in y)g!=="default"&&!Object.prototype.hasOwnProperty.call(f,g)&&e(f,y,g)},n=c&&c.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(c,"__esModule",{value:!0}),c.ReasonCodes=c.KeepaliveManager=c.UniqueMessageIdProvider=c.DefaultMessageIdProvider=c.Store=c.MqttClient=c.connectAsync=c.connect=c.Client=void 0;var i=n(oi());c.MqttClient=i.default;var s=n(ns());c.DefaultMessageIdProvider=s.default;var o=n(pu());c.UniqueMessageIdProvider=o.default;var l=n(Qo());c.Store=l.default;var u=r(rh());c.connect=u.default,Object.defineProperty(c,"connectAsync",{enumerable:!0,get:function(){return u.connectAsync}});var d=n(us());c.KeepaliveManager=d.default,c.Client=i.default,a(oi(),c),a(Rt(),c),a(Yo(),c);var p=sr();Object.defineProperty(c,"ReasonCodes",{enumerable:!0,get:function(){return p.ReasonCodes}})}),nh=pe(c=>{le(),ue(),ce();var e=c&&c.__createBinding||(Object.create?function(i,s,o,l){l===void 0&&(l=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(i,l,u)}:function(i,s,o,l){l===void 0&&(l=o),i[l]=s[o]}),t=c&&c.__setModuleDefault||(Object.create?function(i,s){Object.defineProperty(i,"default",{enumerable:!0,value:s})}:function(i,s){i.default=s}),r=c&&c.__importStar||(function(){var i=function(s){return i=Object.getOwnPropertyNames||function(o){var l=[];for(var u in o)Object.prototype.hasOwnProperty.call(o,u)&&(l[l.length]=u);return l},i(s)};return function(s){if(s&&s.__esModule)return s;var o={};if(s!=null)for(var l=i(s),u=0;u<l.length;u++)l[u]!=="default"&&e(o,s,l[u]);return t(o,s),o}})(),a=c&&c.__exportStar||function(i,s){for(var o in i)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,i,o)};Object.defineProperty(c,"__esModule",{value:!0});var n=r(Qa());c.default=n,a(Qa(),c)});const ih=nh();const oh={inbound:"apps/{appId}/users/{userId}/messages/{conversationId}/clientadded",inboundUpdate:"apps/{appId}/users/{userId}/messages/{conversationId}/{messageId}/update",outbound:"apps/{appId}/outgoing/users/{userId}/messages/{conversationId}/outgoing",presence:"apps/{appId}/users/{userId}/presence/{clientId}",wildcardSubscribe:"apps/{appId}/users/{userId}/#"},sh=300,ah={templateId:"7",type:"link",isDeepLink:!0},lh={channelType:"group",channel:"chat21",requestChannel:"chat21",platform:"WEBSITE",medium:"CHATBUDDY"};class Ja{client=null;config;currentToken;clientId;appId;topics;messageHandlers=[];stateHandlers=[];statusUpdateHandlers=[];subscribedTopics=new Set;reconnectAttempt=0;maxReconnectAttempts;reconnectMaxDelayMs;disposed=!1;reconnectTimer=null;inboundRegex;inboundUpdateRegex;constructor(e){this.config=e,this.currentToken=e.jwtToken,this.appId=e.appId??"tilechat",this.clientId=e.clientId??`aikaara_${e.userId}_${Date.now()}`,this.topics={...oh,...e.topicTemplates??{}},this.maxReconnectAttempts=e.maxReconnectAttempts??10,this.reconnectMaxDelayMs=e.reconnectMaxDelayMs??3e4,this.inboundRegex=this.buildTopicRegex(this.topics.inbound,["conversationId"]),this.inboundUpdateRegex=this.buildTopicRegex(this.topics.inboundUpdate,["conversationId","messageId"])}async connect(){if(this.disposed)return;const e=this.renderPresenceTopic(),t=this.config.presencePayloadDisconnected??{disconnected:!0},r={clientId:this.clientId,username:this.config.mqttUsername??"JWT",password:this.currentToken,clean:!0,reconnectPeriod:0,connectTimeout:this.config.connectTimeoutMs??1e4,keepalive:this.config.keepAliveSec??60,protocolVersion:this.config.protocolVersion??3,protocolId:this.config.protocolId??"MQIsdp"};return this.config.enablePresence!==!1&&(r.will={topic:e,payload:JSON.stringify(t),qos:0,retain:!1}),new Promise((a,n)=>{this.client=ih.connect(this.config.mqttEndpoint,r),this.client.on("connect",()=>{if(this.reconnectAttempt=0,this.debugLog("CONNECT",{endpoint:this.config.mqttEndpoint,clientId:this.clientId}),this.notifyStateChange(!0),this.config.enablePresence!==!1){const i=this.config.presencePayloadConnected??{connected:!0};this.client.publish(e,JSON.stringify(i),{qos:0,retain:!1}),this.debugLog("PUBLISH",{topic:e,payload:i})}a()}),this.client.on("message",(i,s)=>{this.dispatchInbound(i,s)}),this.client.on("close",()=>{this.debugLog("CLOSE",{}),this.notifyStateChange(!1),this.disposed||this.scheduleReconnect()}),this.client.on("error",i=>{this.debugLog("ERROR",{message:i.message}),this.reconnectAttempt===0&&n(i)}),this.client.on("packetsend",i=>{(i.cmd==="subscribe"||i.cmd==="unsubscribe"||i.cmd==="pingreq")&&this.debugLog(i.cmd.toUpperCase(),{topic:i.topic,packetId:i.messageId})})})}debugLog(e,t){if(!this.config.debug)return;const r={};for(const[a,n]of Object.entries(t))typeof n=="string"&&n.length>200?r[a]=`${n.slice(0,200)}…(${n.length})`:r[a]=n;console.info(`[tiledesk-mqtt] ${e}`,r)}subscribeWildcard(){if(!this.client)return;const e=this.renderTemplate(this.topics.wildcardSubscribe,{});this.subscribedTopics.has(e)||(this.client.subscribe(e,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(e))}subscribeToConversation(e){if(!this.client)return;if(this.config.wildcardSubscribe){this.subscribeWildcard();return}const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)||(this.client.subscribe(t,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(t))}unsubscribeFromConversation(e){if(!this.client)return;const t=this.renderInboundTopic(e);this.subscribedTopics.has(t)&&(this.client.unsubscribe(t),this.subscribedTopics.delete(t))}publishMessage(e,t,r={}){if(!this.client)return;const a=this.buildOutgoingEnvelope(e,{text:t,type:"text",...r});this.publishEnvelope(e,a)}publishFileMessage(e,t){if(!this.client)return;const r={...ah,...this.config.fileTemplate??{},...ch(t)},a={metadata:{contentType:"300",templateId:r.templateId,payload:{...r.headerImgSrc?{headerImgSrc:r.headerImgSrc}:{},elements:[{description:t.description??t.fileName,action:{url:t.fileUrl,type:r.type??"link",isDeepLink:r.isDeepLink??!0}}]},...t.metadata??{}}},n={fileMessage:!0,...t.cloudFileId?{cloudFileId:t.cloudFileId}:{},...t.attributes??{}},i=this.buildOutgoingEnvelope(e,{text:JSON.stringify(a),type:"html",attributes:n,metadata:a.metadata});this.publishEnvelope(e,i)}publishRaw(e,t){this.client&&this.publishEnvelope(e,t)}publishReadReceipt(e,t,r=sh){if(!this.client)return;const a=this.renderTemplate(this.topics.inboundUpdate,{conversationId:e,messageId:t});this.client.publish(a,JSON.stringify({status:r}),{qos:this.config.publishQos??0,retain:!1})}publishChatInitiated(e,t={}){if(!this.client)return;const r=this.buildOutgoingEnvelope(e,{text:"CHAT_INITIATED",type:"text",attributes:{subtype:"info",...t}});this.publishEnvelope(e,r)}onMessage(e){return this.messageHandlers.push(e),()=>{this.messageHandlers=this.messageHandlers.filter(t=>t!==e)}}onStateChange(e){return this.stateHandlers.push(e),()=>{this.stateHandlers=this.stateHandlers.filter(t=>t!==e)}}onStatusUpdate(e){return this.statusUpdateHandlers.push(e),()=>{this.statusUpdateHandlers=this.statusUpdateHandlers.filter(t=>t!==e)}}disconnect(){this.disposed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.subscribedTopics.forEach(e=>this.client.unsubscribe(e)),this.subscribedTopics.clear(),this.client.end(!0),this.client=null),this.messageHandlers=[],this.stateHandlers=[],this.statusUpdateHandlers=[]}get isConnected(){return this.client?.connected??!1}async scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts||this.disposed)return;const e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),this.reconnectMaxDelayMs);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.disposed){if(this.config.tokenProvider)try{this.currentToken=await this.config.tokenProvider()}catch{}try{await this.connect();const t=[...this.subscribedTopics];this.subscribedTopics.clear(),t.forEach(r=>{this.client&&(this.client.subscribe(r,{qos:this.config.subscribeQos??2}),this.subscribedTopics.add(r))})}catch{}}},e)}notifyStateChange(e){this.stateHandlers.forEach(t=>t(e))}dispatchInbound(e,t){const r=t.toString();let a=null;try{a=JSON.parse(r)}catch{this.debugLog("RECV (non-json)",{topic:e,raw:r});return}if(!a)return;this.debugLog("RECV",{topic:e,sender:a.sender,type:a.type,contentType:a.metadata?.contentType,templateId:a.metadata?.templateId,messageId:a.message_id,text:typeof a.text=="string"?a.text:void 0});const n=e.match(this.inboundUpdateRegex);if(n){const l=n.groups?.conversationId??"",u=n.groups?.messageId??"",d=typeof a.status=="number"?a.status:Number(a.status??0),p={conversationId:l,messageId:u,status:d,raw:a};this.statusUpdateHandlers.forEach(y=>y(p)),this.messageHandlers.forEach(y=>y(a,{topic:e,conversationId:l,messageId:u,kind:"update"}));return}const i=e.match(this.inboundRegex),s=i?.groups?.conversationId,o={topic:e,conversationId:s,messageId:typeof a.message_id=="string"?a.message_id:void 0,kind:i?"clientadded":"unknown"};this.messageHandlers.forEach(l=>l(a,o))}buildOutgoingEnvelope(e,t){const r={...lh,...this.config.messageDefaults??{}},a=this.config.senderFullname??this.config.userName??this.config.userId,n=this.config.recipientFullnameResolver?.(e),i={projectId:this.config.projectId,...r.departmentId?{departmentId:r.departmentId}:{},...this.config.userName?{userFullname:this.config.userName}:{},...r.channel?{channel:r.channel}:{},...r.requestChannel?{request_channel:r.requestChannel}:{},...r.attributes??{},...t.attributes??{}};return{type:"text",sender:this.config.userId,sender_fullname:a,senderFullname:a,recipient:e,...n?{recipient_fullname:n}:{},...r.channelType?{channel_type:r.channelType}:{},...r.medium?{medium:r.medium}:{},...r.platform?{platform:r.platform}:{},app_id:this.appId,timestamp:Date.now(),...t,attributes:i}}publishEnvelope(e,t){if(!this.client)return;const r=this.renderOutboundTopic(e);this.client.publish(r,JSON.stringify(t),{qos:this.config.publishQos??0,retain:this.config.publishRetain??!1}),this.debugLog("SEND",{topic:r,type:t.type,sender:t.sender,text:typeof t.text=="string"?t.text:void 0,contentType:t.metadata?.contentType,templateId:t.metadata?.templateId})}renderInboundTopic(e){return this.renderTemplate(this.topics.inbound,{conversationId:e})}renderOutboundTopic(e){return this.renderTemplate(this.topics.outbound,{conversationId:e})}renderPresenceTopic(){return this.renderTemplate(this.topics.presence,{})}renderTemplate(e,t){const r={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId,...t};return e.replace(/\{(\w+)\}/g,(a,n)=>r[n]??"")}buildTopicRegex(e,t){const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\{(\w+)\\\}/g,(a,n)=>{const i={appId:this.appId,userId:this.config.userId,projectId:this.config.projectId,clientId:this.clientId};if(t.includes(n))return`(?<${n}>[^/]+)`;const s=i[n];return s?s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"[^/]+"});return new RegExp(`^${r}$`)}}function ch(c){const e={};for(const[t,r]of Object.entries(c))r!==void 0&&(e[t]=r);return e}function Xa(c,e){return(c.sender??"").toString()===e}function Za(c,e){const t=(c.sender??"").toString(),r=e.systemSenders??["metadata","system"],a=e.botSenderPrefix??"bot_";return t?t===e.userId?"user":t.startsWith(a)?"assistant":r.includes(t)?"system":"agent":"system"}function to(c){const e={raw:c},t=c.metadata;if(t&&typeof t=="object"&&(typeof t.contentType=="string"&&(e.contentType=t.contentType),typeof t.templateId=="string"&&(e.templateId=t.templateId),t.payload!==void 0&&(e.payload=t.payload)),typeof c.text=="string"&&c.text.trim().startsWith("{"))try{const r=JSON.parse(c.text);typeof r.message=="string"&&(e.innerMessage=r.message);const a=r.metadata;a&&typeof a=="object"&&(!e.contentType&&typeof a.contentType=="string"&&(e.contentType=a.contentType),!e.templateId&&typeof a.templateId=="string"&&(e.templateId=a.templateId),e.payload===void 0&&a.payload!==void 0&&(e.payload=a.payload))}catch{}return e}function el(c){const e=to(c);if(e.contentType!=="300")return null;const t=e.payload,r=t&&Array.isArray(t.elements)?t.elements:null;if(!r||r.length===0)return null;const a=r[0],n=a.action,i=n&&typeof n.url=="string"?n.url:void 0,s=typeof a.description=="string"?a.description:void 0,o=c.attributes,l=o&&typeof o.cloudFileId=="string"?o.cloudFileId:void 0;return!i&&!s?null:{fileName:s,fileUrl:i,cloudFileId:l,templateId:e.templateId}}function tl(c,e,t){const r=Za(c,t),a=to(c),n=el(c);let i="";a.innerMessage?i=a.innerMessage:typeof c.text=="string"&&(c.text.trim().startsWith("{")?a.contentType!=="300"&&(i=c.text):i=c.text);const s=typeof c.message_id=="string"?c.message_id:`td_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=typeof c.timestamp=="number"?new Date(c.timestamp).toISOString():new Date().toISOString(),l=r==="assistant"?"assistant":r==="agent"?"agent":r==="system"?"system":"user",u=typeof c.status=="number"?uh(c.status):"delivered",d={id:s,externalId:s,conversationId:e,role:l,content:i,createdAt:o,status:u,metadata:{sender:c.sender,sender_fullname:c.sender_fullname??c.senderFullname,app_id:c.app_id,attributes:c.attributes}};return a.contentType&&(d.template={contentType:a.contentType,templateId:a.templateId,payload:a.payload}),n?.fileUrl&&(d.attachments=[{fileName:n.fileName??"file",fileUrl:n.fileUrl,cloudFileId:n.cloudFileId}]),{message:d,template:a}}function uh(c){return c<0?"error":c>=250?"read":c>=150?"delivered":"sent"}class rl extends Zt{connection=null;tiledesk=null;api;messageStore;conversationManager;subscription=null;config;mode;uploadAdapter;historyAdapter;tiledeskUnsubs=[];constructor(e,t){super(),this.config=e,this.mode=e.transport??"aikaara",this.uploadAdapter=t?.uploadAdapter??null,this.historyAdapter=t?.historyAdapter??null,this.api=new yo(e.baseUrl,e.userToken,e.apiKey,e.authToken),this.messageStore=new vo,this.conversationManager=new wo(e.conversationId),this.usesAikaara()&&(this.connection=new bo(e),this.connection.on("connection:state",r=>{this.emit("connection:state",r),this.config.onConnectionStateChange?.(r)}),this.connection.on("error",r=>{this.emit("error",r),this.config.onError?.(r)})),this.usesTiledesk()&&this.initTiledeskTransport()}usesAikaara(){return this.mode==="aikaara"||this.mode==="dual"}usesTiledesk(){return this.mode==="tiledesk"||this.mode==="dual"}initTiledeskTransport(){const e=this.config.tiledesk,t=this.config.tiledeskIdentity;if(!e)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledesk` (TiledeskTransportConfig)");if(!t?.userId)throw new Error("AikaaraChatClient: tiledesk transport requires `config.tiledeskIdentity.userId`");this.tiledesk=new Ja({...e,userId:t.userId,userName:t.userName??e.userName,senderFullname:t.senderFullname??e.senderFullname,messageDefaults:{...e.messageDefaults,departmentId:t.departmentId??e.messageDefaults?.departmentId}}),this.tiledeskUnsubs.push(this.tiledesk.onStateChange(r=>{const a=r?"connected":"disconnected";this.emit("connection:state",a),this.config.onConnectionStateChange?.(a)})),this.tiledeskUnsubs.push(this.tiledesk.onMessage((r,a)=>this.handleTiledeskMessage(r,a))),this.tiledeskUnsubs.push(this.tiledesk.onStatusUpdate(r=>this.handleTiledeskStatusUpdate(r)))}async connect(){if(this.usesAikaara()&&this.connection){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}if(this.usesTiledesk()&&this.tiledesk){await this.tiledesk.connect(),this.config.tiledesk?.wildcardSubscribe??!0?this.tiledesk.subscribeWildcard():this.conversationManager.conversationId&&this.tiledesk.subscribeToConversation(this.conversationManager.conversationId);const t=this.conversationManager.conversationId;if(t){const r=await this.hydrateTiledeskHistory(t),a=this.config.tiledesk?.autoInitiateOnEmpty??!0;r==="empty"&&a&&this.tiledesk.publishChatInitiated(t,this.config.tiledesk?.chatInitiatedAttributes??{})}}}async hydrateTiledeskHistory(e){if(!this.historyAdapter)return"unknown";const t=this.config.tiledeskIdentity?.userId??"";let r;try{r=await this.historyAdapter.fetchMessages(e,{userId:t,appId:this.config.tiledesk?.appId,projectId:this.config.tiledesk?.projectId})}catch(s){return this.config.onError?.(s instanceof Error?s:new Error(String(s))),"unknown"}if(!r.length)return"empty";const a=r.map(s=>tl(s,e,{userId:t}).message).sort((s,o)=>new Date(s.createdAt).getTime()-new Date(o.createdAt).getTime()),n=this.messageStore.messages,i=[...a,...n.filter(s=>!a.some(o=>o.externalId&&o.externalId===s.externalId))];if(this.messageStore.setMessages(i),this.config.onMessage)for(const s of a)try{this.config.onMessage(s)}catch(o){console.warn("[aikaara-chat-sdk] onMessage threw on history replay",o)}return"has-history"}async sendMessage(e,t={}){const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=this.messageStore.addOptimistic("user",e,r);this.emit("message:sent",a),this.config.onMessage?.(a);const n={};if(t.attributes&&(n.attributes=t.attributes),t.metadata&&(n.metadata=t.metadata),this.mode==="tiledesk"&&this.tiledesk){this.tiledesk.publishMessage(r,e,n);return}this.mode==="dual"&&this.tiledesk&&this.tiledesk.publishMessage(r,e,n),this.usesAikaara()&&this.connection&&this.connection.sendMessage(r,e)}async sendFile(e,t){if(!this.uploadAdapter)throw new Error("AikaaraChatClient: sendFile requires an UploadAdapter");const r=this.conversationManager.conversationId;if(!r)throw new Error("No active conversation");const a=await this.uploadAdapter.upload(e,{conversationId:r,userId:this.config.tiledeskIdentity?.userId??this.config.userToken,projectId:this.config.tiledesk?.projectId,appId:this.config.tiledesk?.appId});if(this.usesTiledesk()&&this.tiledesk){const n={fileName:a.fileName,fileUrl:a.url,cloudFileId:a.cloudFileId};this.tiledesk.publishFileMessage(r,n)}t?.caption&&await this.sendMessage(t.caption)}initiateTiledeskChat(e={}){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishChatInitiated(t,e)}markTiledeskRead(e){const t=this.conversationManager.conversationId;!this.tiledesk||!t||this.tiledesk.publishReadReceipt(t,e)}setUploadAdapter(e){this.uploadAdapter=e}async sendUserEvent(e,t,r){const a=this.conversationManager.conversationId;if(!a)throw new Error("No active conversation");this.connection&&this.connection.sendUserEvent(a,e,t,r)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const t=await this.api.getMessages(e);return this.messageStore.setMessages(t),t}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){if(this.mode==="tiledesk")return this.tiledesk?.isConnected??!1;if(this.mode==="dual"){const e=this.connection?.connectionState==="connected",t=this.tiledesk?.isConnected??!1;return e&&t}return this.connection?.connectionState==="connected"}async setContext(e){const t=this.conversationManager.conversationId;t&&await this.api.updateContext(t,{current_page:e.currentPage,entity_type:e.entityType,entity_id:e.entityId,project_id:e.projectId,available_routes:e.availableRoutes,custom_context:e.custom})}async disconnect(){this.subscription&&(this.subscription=null),this.connection&&await this.connection.disconnect(),this.tiledesk&&(this.tiledeskUnsubs.forEach(e=>e()),this.tiledeskUnsubs=[],this.tiledesk.disconnect(),this.tiledesk=null)}handleTiledeskMessage(e,t){if(t.kind==="update")return;const r=t.conversationId??this.conversationManager.conversationId;if(!r)return;const a=this.config.tiledeskIdentity?.userId??"",{message:n,template:i}=tl(e,r,{userId:a,systemSenders:this.config.tiledesk?.messageDefaults?.attributes?.systemSenders});if(this.mode==="dual"&&n.role==="assistant")return;if(Xa(e,a)){const l=this.messageStore.reconcileOptimistic(n);if(l){this.emit("message:updated",l);return}}const{message:s,deduped:o}=this.messageStore.upsertRemoteMessage(n);if(o?this.emit("message:updated",s):(this.emit("message:received",s),this.config.onMessage?.(s)),i.contentType){const l={messageId:s.id,conversationId:r,role:n.role==="tool"?"system":n.role,contentType:i.contentType,templateId:i.templateId,payload:i.payload,innerMessage:i.innerMessage,raw:e};this.config.onTemplateMessage?.(l)}}handleTiledeskStatusUpdate(e){e.status>=250?this.messageStore.updateMessageStatus(e.messageId,"read"):e.status>=150&&this.messageStore.updateMessageStatus(e.messageId,"delivered")}parseActionResult(e){try{const t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")return;t.navigate_to?this.emit("action:navigate",t):t.action==="edit_entity"?this.emit("action:edit_entity",t):t.action==="save_entity"?this.emit("action:save_entity",t):t.action==="test_tool"&&this.emit("action:test_tool",t)}catch{}}handleBroadcast(e){const t=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),this.config.onStatusChange?.(r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),this.config.onError?.(r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(t);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.delta||"",a=e.content||"";a?this.messageStore.updateStreaming(a):r&&this.messageStore.appendToStreaming(r);const n=this.messageStore.streamingContent;this.emit("stream:update",{delta:r,content:n}),this.config.onStreamUpdate?.(r,n);break}case"message_end":{const r=e.usage,a=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),a&&(this.emit("stream:end",{messageId:a.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",a),this.config.onMessage?.(a));break}case"message_queued":{const r=this.messageStore.messages.findLast(a=>a.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":{this.emit("tool:start",{toolName:e.tool_name||"",args:e.args||{}}),this.emit("status",e.type);break}case"tool_execution_end":{this.emit("tool:end",{toolName:e.tool_name||"",result:e.result,isError:!!e.is_error}),this.emit("status",e.type),this.parseActionResult(e.result);break}case"tool_execution_update":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class hh extends Zt{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(r=>r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId));if(t.length>0){for(const r of t)e.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===e.entityType&&String(r.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,r){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:e,entityId:t,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:r}),this.emit("edit:pending",{entityType:e,entityId:t,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}const nl={txt:"text/plain",pdf:"application/pdf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",csv:"text/csv",doc:"application/msword",json:"application/json"};function fh(c){const e=c.lastIndexOf(".");return e<0||e===c.length-1?"":c.slice(e+1).toLowerCase()}function dh(c,e,t){const r=fh(c.name||"");if(r&&e&&e[r])return e[r];const a=c.type;return a&&a.trim().length>0?a:r&&nl[r]?nl[r]:t}function ro(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function ph(c,e){const t=e.split(".");let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return"";return typeof r=="string"?r:""}function il(c){const e=c.signedUrlPath??"data.s3SignedUrl";return{async upload(t,r){const a=t.name||`upload-${Date.now()}`,n={fileName:a,userId:r.userId,requestId:r.conversationId,conversationId:r.conversationId},i=c.authHeader?await c.authHeader():void 0,s={accept:"application/json",...c.extraHeaders??{},...i?{authorization:i}:{}},o=ro(c.signEndpoint.includes("{")?c.signEndpoint:`${c.signEndpoint}?fileName={fileName}`,n),l=await fetch(o,{method:c.signMethod??"GET",headers:s});if(!l.ok)throw new Error(`Sign request failed: ${l.status}`);const u=await l.json().catch(()=>({})),d=ph(u,e);if(!d)throw new Error(`Sign response missing path "${e}"`);const p=dh(t,c.contentTypeMap,c.contentTypeFallback??"application/octet-stream"),y=c.s3HostRewrite?d.replace(/^https:\/\/[^/]+/i,c.s3HostRewrite):d,f=await fetch(y,{method:"PUT",headers:{"content-type":p},body:t});if(!f.ok){const b=await f.text().catch(()=>"");throw new Error(`S3 PUT failed: ${f.status} ${b.slice(0,200)}`)}if(c.registerEndpoint){const b=JSON.parse(ro(JSON.stringify(c.registerBody??{}),n)),k=await fetch(c.registerEndpoint,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify(b)});if(!k.ok){const m=await k.text().catch(()=>"");throw new Error(`Register failed: ${k.status} ${m.slice(0,200)}`)}}return{url:c.viewerTemplate?ro(c.viewerTemplate,n):d.split("?")[0],fileName:a,contentType:p,byteSize:t.size,meta:{requestId:r.conversationId}}}}}function no(c){return{async upload(e,t){const r=new FormData,a=c.fieldName??"file";r.append(a,e,e.name);const n=typeof c.extraFields=="function"?c.extraFields(t):c.extraFields;if(n)for(const[p,y]of Object.entries(n))r.append(p,y);r.append("conversationId",t.conversationId),r.append("userId",t.userId),t.projectId&&r.append("projectId",t.projectId);const i=typeof c.headers=="function"?await c.headers():c.headers??{},s=await fetch(c.endpoint,{method:c.method??"POST",body:r,headers:i,credentials:c.credentials});if(!s.ok)throw new Error(`Upload failed: ${s.status} ${s.statusText}`);const o=await s.json().catch(()=>({}));if(c.parseResponse)return c.parseResponse(o,t);const l=o,u=l.url??l.fileUrl??l.publicUrl,d=l.fileName??l.name??e.name;if(!u)throw new Error('Upload response missing "url" / "fileUrl" / "publicUrl"');return{url:u,fileName:d,cloudFileId:typeof l.cloudFileId=="string"?l.cloudFileId:void 0,relativePath:typeof l.path=="string"?l.path:void 0,contentType:typeof l.contentType=="string"?l.contentType:void 0,byteSize:typeof l.byteSize=="number"?l.byteSize:void 0,meta:l}}}}const gh="/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}";function ol(c){const e=c.apiBase.replace(/\/$/,""),t=c.pageSize??200,r=c.pathTemplate??gh;return{async fetchMessages(a,n){const i=r.replace("{userId}",encodeURIComponent(n.userId)).replace("{conversationId}",encodeURIComponent(a)).replace("{appId}",encodeURIComponent(n.appId??"tilechat")).replace("{projectId}",encodeURIComponent(n.projectId??"")).replace("{pageSize}",String(t)),s=i.startsWith("http")?i:`${e}${i.startsWith("/")?i:`/${i}`}`,o={accept:"application/json","content-type":"application/json",...c.extraHeaders??{}};if(c.getToken){const p=await c.getToken();p&&(o.authorization=p)}const l=await fetch(s,{method:"GET",headers:o}),u=await l.json().catch(()=>null);if(c.parseResponse&&u)return c.parseResponse(u);const d=u;if(d&&Array.isArray(d.result))return d.result;if(!l.ok)throw new Error(`History fetch failed: ${l.status} ${l.statusText}`);return[]}}}class mh{client;panel;bubble;header;messageList;input;errorBanner;isOpen=!1;isEmbed=!1;constructor(e,t,r){this.client=new rl(e,{uploadAdapter:r?.uploadAdapter,historyAdapter:r?.historyAdapter}),this.isEmbed=e.display==="embed",this.bubble=t.querySelector("aikaara-chat-bubble"),this.panel=t.querySelector(".aikaara-panel"),this.header=t.querySelector("aikaara-chat-header"),this.messageList=t.querySelector("aikaara-message-list"),this.input=t.querySelector("aikaara-chat-input"),this.errorBanner=t.querySelector("aikaara-error-banner"),e.welcomeMessage&&this.messageList.setWelcomeMessage(e.welcomeMessage),e.showTimestamps!==void 0&&this.messageList.setShowTimestamps(e.showTimestamps),(e.linkHandlers||e.getLinkBearer)&&this.messageList.setLinkConfig(e.linkHandlers??[],e.getLinkBearer),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble?.addEventListener("toggle",()=>{this.togglePanel()}),this.isEmbed||this.header.addEventListener("header-close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(e=>{this.handleSend(e.detail.content)})),this.input.addEventListener("file-pick",(e=>{this.handleFile(e.detail.file)})),this.client.on("message:sent",e=>{this.messageList.addMessage(e)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const e=this.client.messages[this.client.messages.length-1];e&&this.messageList.addMessage(e)}),this.client.on("stream:update",({content:e})=>{this.messageList.updateStreamingContent(e)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const e=this.client.messages,t=e[e.length-1];(!t||t.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",e=>{this.header.setStatus(e),e==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):e==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):e==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",e=>{this.errorBanner.show(e.message,5e3)}),this.client.on("message:received",e=>{this.messageList.upsertMessage(e)}),this.client.on("message:updated",e=>{this.messageList.upsertMessage(e)}),this.messageList.addEventListener("message-action",e=>{const t=e.detail;if(!t?.text)return;const r=this.client.config.templateActionAttributes??{},a=t.attributes?.action??{},n={...t.attributes,action:{...r,...a}};this.handleSend(t.text,n)})}async handleSend(e,t){try{await this.client.sendMessage(e,t?{attributes:t}:void 0)}catch{this.errorBanner.show("Failed to send message",3e3)}}async handleFile(e){this.input.uploading=!0;try{await this.client.sendFile(e)}catch(t){this.errorBanner.show(t instanceof Error?`Upload failed: ${t.message}`:"Upload failed",4e3)}finally{this.input.uploading=!1}}sendUserEvent(e,t,r){this.client.sendUserEvent(e,t,r)}getClient(){return this.client}togglePanel(e){this.isEmbed||(this.isOpen=e!==void 0?e:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200)))}}class sl extends HTMLElement{shadow;controller=null;_config={};static get observedAttributes(){return["base-url","ws-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url","display"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){this.controller?.disconnect()}attributeChangedCallback(e,t,r){t!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",wsUrl:this.getAttribute("ws-url")||this._config.wsUrl,userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||Yl,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||go,position:this.getAttribute("position")||this._config.position||Gl,width:Number(this.getAttribute("width"))||this._config.width||Hl,height:Number(this.getAttribute("height"))||this._config.height||zl,fontFamily:this._config.fontFamily||Vl,borderRadius:this._config.borderRadius??Kl,placeholder:this.getAttribute("placeholder")||this._config.placeholder||mo,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showHeader:this._config.showHeader??!0,hideSystemMessages:this._config.hideSystemMessages,timestampFormat:this._config.timestampFormat,input:this._config.input,templateLayout:this._config.templateLayout,showBubble:this._config.showBubble??!0,display:(this.getAttribute("display")||this._config.display)??"popup",offset:this._config.offset||Ql,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,extUid:this._config.extUid,transport:this._config.transport,tiledesk:this._config.tiledesk,tiledeskIdentity:this._config.tiledeskIdentity,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange,onTemplateMessage:this._config.onTemplateMessage,themeTokens:this._config.themeTokens,linkHandlers:this._config.linkHandlers,getLinkBearer:this._config.getLinkBearer}}propagateThemeToDocument(e,t,r,a){if(typeof document>"u")return;const n=document.documentElement,i=(s,o)=>{o!==void 0&&o!==""&&n.style.setProperty(`--aikaara-${s}`,o)};i("primary",e?.primary??t),i("primary-hover",e?.primaryHover),i("primary-contrast",e?.primaryContrast),i("surface",e?.surface),i("surface-muted",e?.surfaceMuted),i("border",e?.border),i("text",e?.text),i("text-muted",e?.textMuted),i("font",e?.font??a),i("radius",e?.radius!=null?`${e.radius}px`:r!=null?`${r}px`:void 0),i("bubble-radius",e?.bubbleRadius!=null?`${e.bubbleRadius}px`:void 0),i("button-radius",e?.buttonRadius!=null?`${e.buttonRadius}px`:void 0),i("user-bubble-bg",e?.userBubbleBg),i("user-bubble-text",e?.userBubbleText),i("bot-bubble-bg",e?.botBubbleBg),i("bot-bubble-text",e?.botBubbleText),i("modal-width",e?.modalWidth),i("modal-height",e?.modalHeight),i("modal-max-width",e?.modalMaxWidth),i("modal-max-height",e?.modalMaxHeight),i("modal-padding",e?.modalPadding)}themeVars(e){if(!e)return"";const t=a=>typeof a=="number"?`${a}px`:void 0,r={primary:e.primary,"primary-hover":e.primaryHover,"primary-contrast":e.primaryContrast,surface:e.surface,"surface-muted":e.surfaceMuted,border:e.border,text:e.text,"text-muted":e.textMuted,font:e.font,radius:t(e.radius),"bubble-radius":t(e.bubbleRadius),"button-radius":t(e.buttonRadius),"user-bubble-bg":e.userBubbleBg,"user-bubble-text":e.userBubbleText,"bot-bubble-bg":e.botBubbleBg,"bot-bubble-text":e.botBubbleText,"modal-width":e.modalWidth,"modal-height":e.modalHeight,"modal-max-width":e.modalMaxWidth,"modal-max-height":e.modalMaxHeight,"modal-padding":e.modalPadding};return Object.entries(r).filter(([,a])=>a!==void 0&&a!=="").map(([a,n])=>`--aikaara-${a}: ${n};`).join(`
|
|
9
9
|
`)}setUploadAdapter(e){this._config.uploadAdapter=e,this.controller?.getClient().setUploadAdapter(e)}setHistoryAdapter(e){this._config.historyAdapter=e}render(){const e=this.getConfig(),t=e.display==="embed";this.propagateThemeToDocument(e.themeTokens,e.primaryColor,e.borderRadius,e.fontFamily);const r=`
|
|
10
10
|
font-family: var(--aikaara-font);
|
|
11
11
|
position: fixed;
|
package/dist/headless.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-BCdh7baG.cjs");class s extends e.EventEmitter{registration=null;pendingEdits=[];constructor(t){super(),this.setupListeners(t)}registerForm(t){this.registration=t;const i=this.pendingEdits.filter(r=>r.entity_type===t.entityType&&String(r.entity_id)===String(t.entityId));if(i.length>0){for(const r of i)t.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===t.entityType&&String(r.entity_id)===String(t.entityId)))}}unregisterForm(t,i){this.registration?.entityType===t&&String(this.registration?.entityId)===String(i)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(t,i,r){this.registration&&this.registration.entityType===t&&String(this.registration.entityId)===String(i)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:t,entityId:i,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:t,entity_id:i,fields:r}),this.emit("edit:pending",{entityType:t,entityId:i,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(t){const i=t instanceof Error?t.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:i}),{success:!1,error:i}}}async requestTest(t){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(t),{success:!0}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Test failed"}}}setupListeners(t){t.on("action:edit_entity",i=>{this.pushFieldUpdates(i.entity_type,i.entity_id,i.fields)}),t.on("action:save_entity",i=>{this.requestSave()}),t.on("action:test_tool",i=>{this.emit("test:triggered",{toolId:i.tool_id,parameters:i.parameters}),this.requestTest(i.parameters)})}}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.SsoExchangeAdapter=e.SsoExchangeAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.TokenDiscoveryError=e.TokenDiscoveryError;exports.TokenDiscoveryReader=e.TokenDiscoveryReader;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.discoverToken=e.discoverToken;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.FormBridge=s;
|
package/dist/headless.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { E as s } from "./MountTenant-
|
|
2
|
-
import { A as p, b as l, k as g, C as c, l as h, m as y, M as u, S as m, n as f, T, o as S, p as _, q as v, s as E, t as C, u as F, v as k, w as A, x as I, y as x, z as U, B as q, D as M, F as b } from "./MountTenant-
|
|
1
|
+
import { E as s } from "./MountTenant-Df3fIQU6.mjs";
|
|
2
|
+
import { A as p, b as l, k as g, C as c, l as h, m as y, M as u, S as m, n as f, T, o as S, p as _, q as v, s as E, t as C, u as F, v as k, w as A, x as I, y as x, z as U, B as q, D as M, F as b } from "./MountTenant-Df3fIQU6.mjs";
|
|
3
3
|
class a extends s {
|
|
4
4
|
registration = null;
|
|
5
5
|
pendingEdits = [];
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-BCdh7baG.cjs"),s=require("./headless.cjs");function l(a){e.registerComponents();const t=document.createElement("aikaara-chat-widget"),i={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[o,n]of Object.entries(i)){const r=a[o];r!=null&&t.setAttribute(n,String(r))}return t.configure(a),document.body.appendChild(t),t}function d(){const a=document.querySelector("aikaara-chat-widget");a&&a.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatBubble=e.AikaaraChatBubble;exports.AikaaraChatClient=e.AikaaraChatClient;exports.AikaaraChatHeader=e.AikaaraChatHeader;exports.AikaaraChatInput=e.AikaaraChatInput;exports.AikaaraChatWidget=e.AikaaraChatWidget;exports.AikaaraErrorBanner=e.AikaaraErrorBanner;exports.AikaaraMessageBubble=e.AikaaraMessageBubble;exports.AikaaraMessageList=e.AikaaraMessageList;exports.AikaaraStreamingMessage=e.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=e.AikaaraTypingIndicator;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.SsoExchangeAdapter=e.SsoExchangeAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.TokenDiscoveryError=e.TokenDiscoveryError;exports.TokenDiscoveryReader=e.TokenDiscoveryReader;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.discoverToken=e.discoverToken;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.registerComponents=e.registerComponents;exports.FormBridge=s.FormBridge;exports.mount=l;exports.unmount=d;
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as o } from "./MountTenant-
|
|
2
|
-
import { A as u, a as m, b as k, c as g, d as h, e as A, f as C, g as T, h as b, i as v, j as f, k as y, C as S, l as w, m as E, E as M, M as x, S as B, n as F, T as U, o as D, p as I, q as j, s as q, t as H, u as P, v as R, w as W, x as z, y as K, z as L, B as O, D as G, F as J } from "./MountTenant-
|
|
1
|
+
import { r as o } from "./MountTenant-Df3fIQU6.mjs";
|
|
2
|
+
import { A as u, a as m, b as k, c as g, d as h, e as A, f as C, g as T, h as b, i as v, j as f, k as y, C as S, l as w, m as E, E as M, M as x, S as B, n as F, T as U, o as D, p as I, q as j, s as q, t as H, u as P, v as R, w as W, x as z, y as K, z as L, B as O, D as G, F as J } from "./MountTenant-Df3fIQU6.mjs";
|
|
3
3
|
import { FormBridge as Q } from "./headless.mjs";
|
|
4
4
|
function l(e) {
|
|
5
5
|
o();
|
package/dist/ui.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./MountTenant-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./MountTenant-BCdh7baG.cjs");exports.AikaaraChat=a.AikaaraChat;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraComparePlans=a.AikaaraComparePlans;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraLinkModal=a.AikaaraLinkModal;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraModalAction=a.AikaaraModalAction;exports.AikaaraOptionList=a.AikaaraOptionList;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraSubmitAction=a.AikaaraSubmitAction;exports.AikaaraSystemPill=a.AikaaraSystemPill;exports.AikaaraTemplateRenderer=a.AikaaraTemplateRenderer;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;
|
package/dist/ui.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { G as i, a as s, c as e, d as t, e as A, H as k, f as n, I as o, g, h as l, J as d, K as m, i as p, L as C, N as h, O as b, j as M, r as c } from "./MountTenant-
|
|
1
|
+
import { G as i, a as s, c as e, d as t, e as A, H as k, f as n, I as o, g, h as l, J as d, K as m, i as p, L as C, N as h, O as b, j as M, r as c } from "./MountTenant-Df3fIQU6.mjs";
|
|
2
2
|
export {
|
|
3
3
|
i as AikaaraChat,
|
|
4
4
|
s as AikaaraChatBubble,
|